repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/CSharp/Test/Semantic/Semantics/InterpolationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using System.Collections.Immutable;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class InterpolationTests : CompilingTestBase
{
[Fact]
public void TestSimpleInterp()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""Jenny don\'t change your number { number }."");
Console.WriteLine($""Jenny don\'t change your number { number , -12 }."");
Console.WriteLine($""Jenny don\'t change your number { number , 12 }."");
Console.WriteLine($""Jenny don\'t change your number { number :###-####}."");
Console.WriteLine($""Jenny don\'t change your number { number , -12 :###-####}."");
Console.WriteLine($""Jenny don\'t change your number { number , 12 :###-####}."");
Console.WriteLine($""{number}"");
}
}";
string expectedOutput =
@"Jenny don't change your number 8675309.
Jenny don't change your number 8675309 .
Jenny don't change your number 8675309.
Jenny don't change your number 867-5309.
Jenny don't change your number 867-5309 .
Jenny don't change your number 867-5309.
8675309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestOnlyInterp()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""{number}"");
}
}";
string expectedOutput =
@"8675309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestDoubleInterp01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""{number}{number}"");
}
}";
string expectedOutput =
@"86753098675309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestDoubleInterp02()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""Jenny don\'t change your number { number :###-####} { number :###-####}."");
}
}";
string expectedOutput =
@"Jenny don't change your number 867-5309 867-5309.";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestEmptyInterp()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { /*trash*/ }."");
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,73): error CS1733: Expected expression
// Console.WriteLine("Jenny don\'t change your number \{ /*trash*/ }.");
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(5, 73)
);
}
[Fact]
public void TestHalfOpenInterp01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { "");
}
}";
// too many diagnostics perhaps, but it starts the right way.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,63): error CS1010: Newline in constant
// Console.WriteLine($"Jenny don\'t change your number { ");
Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(5, 63),
// (5,66): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string
// Console.WriteLine($"Jenny don\'t change your number { ");
Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 66),
// (6,6): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6),
// (6,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2));
}
[Fact]
public void TestHalfOpenInterp02()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { 8675309 // "");
}
}";
// too many diagnostics perhaps, but it starts the right way.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,71): error CS8077: A single-line comment may not be used in an interpolated string.
// Console.WriteLine($"Jenny don\'t change your number { 8675309 // ");
Diagnostic(ErrorCode.ERR_SingleLineCommentInExpressionHole, "//").WithLocation(5, 71),
// (6,6): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6),
// (6,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2));
}
[Fact]
public void TestHalfOpenInterp03()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { 8675309 /* "");
}
}";
// too many diagnostics perhaps, but it starts the right way.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,71): error CS1035: End-of-file found, '*/' expected
// Console.WriteLine($"Jenny don\'t change your number { 8675309 /* ");
Diagnostic(ErrorCode.ERR_OpenEndedComment, "").WithLocation(5, 71),
// (5,77): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string
// Console.WriteLine($"Jenny don\'t change your number { 8675309 /* ");
Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 77),
// (7,2): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 2),
// (7,2): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 2),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2));
}
[Fact]
public void LambdaInInterp()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
//Console.WriteLine(""jenny {0:(408) ###-####}"", new object[] { ((Func<int>)(() => { return number; })).Invoke() });
Console.WriteLine($""jenny { ((Func<int>)(() => { return number; })).Invoke() :(408) ###-####}"");
}
static int number = 8675309;
}
";
string expectedOutput = @"jenny (408) 867-5309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void OneLiteral()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""Hello"" );
}
}";
string expectedOutput = @"Hello";
var verifier = CompileAndVerify(source, expectedOutput: expectedOutput);
verifier.VerifyIL("Program.Main", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""Hello""
IL_0005: call ""void System.Console.WriteLine(string)""
IL_000a: ret
}
");
}
[Fact]
public void OneInsert()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var hello = $""Hello"";
Console.WriteLine( $""{hello}"" );
}
}";
string expectedOutput = @"Hello";
var verifier = CompileAndVerify(source, expectedOutput: expectedOutput);
verifier.VerifyIL("Program.Main", @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldstr ""Hello""
IL_0005: dup
IL_0006: brtrue.s IL_000e
IL_0008: pop
IL_0009: ldstr """"
IL_000e: call ""void System.Console.WriteLine(string)""
IL_0013: ret
}
");
}
[Fact]
public void TwoInserts()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var hello = $""Hello"";
var world = $""world"" ;
Console.WriteLine( $""{hello}, { world }."" );
}
}";
string expectedOutput = @"Hello, world.";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TwoInserts02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var hello = $""Hello"";
var world = $""world"" ;
Console.WriteLine( $@""{
hello
},
{
world }."" );
}
}";
string expectedOutput = @"Hello,
world.";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact, WorkItem(306, "https://github.com/dotnet/roslyn/issues/306"), WorkItem(308, "https://github.com/dotnet/roslyn/issues/308")]
public void DynamicInterpolation()
{
string source =
@"using System;
using System.Linq.Expressions;
class Program
{
static void Main(string[] args)
{
dynamic nil = null;
dynamic a = new string[] {""Hello"", ""world""};
Console.WriteLine($""<{nil}>"");
Console.WriteLine($""<{a}>"");
}
Expression<Func<string>> M(dynamic d) {
return () => $""Dynamic: {d}"";
}
}";
string expectedOutput = @"<>
<System.String[]>";
var verifier = CompileAndVerify(source, new[] { CSharpRef }, expectedOutput: expectedOutput).VerifyDiagnostics();
}
[Fact]
public void UnclosedInterpolation01()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,31): error CS1010: Newline in constant
// Console.WriteLine( $"{" );
Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(6, 31),
// (6,35): error CS8958: Newlines are not allowed inside a non-verbatim interpolated string
// Console.WriteLine( $"{" );
Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(6, 35),
// (7,6): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 6),
// (7,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 6),
// (8,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 2));
}
[Fact]
public void UnclosedInterpolation02()
{
string source =
@"class Program
{
static void Main(string[] args)
{
var x = $"";";
// The precise error messages are not important, but this must be an error.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,19): error CS1010: Newline in constant
// var x = $";
Diagnostic(ErrorCode.ERR_NewlineInConst, ";").WithLocation(5, 19),
// (5,20): error CS1002: ; expected
// var x = $";
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 20),
// (5,20): error CS1513: } expected
// var x = $";
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20),
// (5,20): error CS1513: } expected
// var x = $";
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20)
);
}
[Fact]
public void EmptyFormatSpecifier()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{3:}"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,32): error CS8089: Empty format specifier.
// Console.WriteLine( $"{3:}" );
Diagnostic(ErrorCode.ERR_EmptyFormatSpecifier, ":").WithLocation(6, 32)
);
}
[Fact]
public void TrailingSpaceInFormatSpecifier()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{3:d }"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,32): error CS8088: A format specifier may not contain trailing whitespace.
// Console.WriteLine( $"{3:d }" );
Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ":d ").WithLocation(6, 32)
);
}
[Fact]
public void TrailingSpaceInFormatSpecifier02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $@""{3:d
}"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,33): error CS8088: A format specifier may not contain trailing whitespace.
// Console.WriteLine( $@"{3:d
Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, @":d
").WithLocation(6, 33)
);
}
[Fact]
public void MissingInterpolationExpression01()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{ }"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,32): error CS1733: Expected expression
// Console.WriteLine( $"{ }" );
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 32)
);
}
[Fact]
public void MissingInterpolationExpression02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $@""{ }"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,33): error CS1733: Expected expression
// Console.WriteLine( $@"{ }" );
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 33)
);
}
[Fact]
public void MissingInterpolationExpression03()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( ";
var normal = "$\"";
var verbat = "$@\"";
// ensure reparsing of interpolated string token is precise in error scenarios (assertions do not fail)
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void MisplacedNewline01()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var s = $""{ @""
"" }
"";
}
}";
// The precise error messages are not important, but this must be an error.
Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void MisplacedNewline02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var s = $""{ @""
""}
"";
}
}";
// The precise error messages are not important, but this must be an error.
Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void PreprocessorInsideInterpolation()
{
string source =
@"class Program
{
static void Main()
{
var s = $@""{
#region :
#endregion
0
}"";
}
}";
// The precise error messages are not important, but this must be an error.
Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void EscapedCurly()
{
string source =
@"class Program
{
static void Main()
{
var s1 = $"" \u007B "";
var s2 = $"" \u007D"";
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,21): error CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string.
// var s1 = $" \u007B ";
Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007B").WithArguments("{").WithLocation(5, 21),
// (6,21): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string.
// var s2 = $" \u007D";
Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007D").WithArguments("}").WithLocation(6, 21)
);
}
[Fact, WorkItem(1119878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119878")]
public void NoFillIns01()
{
string source =
@"class Program
{
static void Main()
{
System.Console.Write($""{{ x }}"");
System.Console.WriteLine($@""This is a test"");
}
}";
string expectedOutput = @"{ x }This is a test";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void BadAlignment()
{
string source =
@"class Program
{
static void Main()
{
var s = $""{1,1E10}"";
var t = $""{1,(int)1E10}"";
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,22): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
// var s = $"{1,1E10}";
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1E10").WithArguments("double", "int").WithLocation(5, 22),
// (5,22): error CS0150: A constant value is expected
// var s = $"{1,1E10}";
Diagnostic(ErrorCode.ERR_ConstantExpected, "1E10").WithLocation(5, 22),
// (6,22): error CS0221: Constant value '10000000000' cannot be converted to a 'int' (use 'unchecked' syntax to override)
// var t = $"{1,(int)1E10}";
Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)1E10").WithArguments("10000000000", "int").WithLocation(6, 22),
// (6,22): error CS0150: A constant value is expected
// var t = $"{1,(int)1E10}";
Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)1E10").WithLocation(6, 22)
);
}
[Fact]
public void NestedInterpolatedVerbatim()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var s = $@""{$@""{1}""}"";
Console.WriteLine(s);
}
}";
string expectedOutput = @"1";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
// Since the platform type System.FormattableString is not yet in our platforms (at the
// time of writing), we explicitly include the required platform types into the sources under test.
private const string formattableString = @"
/*============================================================
**
** Class: FormattableString
**
**
** Purpose: implementation of the FormattableString
** class.
**
===========================================================*/
namespace System
{
/// <summary>
/// A composite format string along with the arguments to be formatted. An instance of this
/// type may result from the use of the C# or VB language primitive ""interpolated string"".
/// </summary>
public abstract class FormattableString : IFormattable
{
/// <summary>
/// The composite format string.
/// </summary>
public abstract string Format { get; }
/// <summary>
/// Returns an object array that contains zero or more objects to format. Clients should not
/// mutate the contents of the array.
/// </summary>
public abstract object[] GetArguments();
/// <summary>
/// The number of arguments to be formatted.
/// </summary>
public abstract int ArgumentCount { get; }
/// <summary>
/// Returns one argument to be formatted from argument position <paramref name=""index""/>.
/// </summary>
public abstract object GetArgument(int index);
/// <summary>
/// Format to a string using the given culture.
/// </summary>
public abstract string ToString(IFormatProvider formatProvider);
string IFormattable.ToString(string ignored, IFormatProvider formatProvider)
{
return ToString(formatProvider);
}
/// <summary>
/// Format the given object in the invariant culture. This static method may be
/// imported in C# by
/// <code>
/// using static System.FormattableString;
/// </code>.
/// Within the scope
/// of that import directive an interpolated string may be formatted in the
/// invariant culture by writing, for example,
/// <code>
/// Invariant($""{{ lat = {latitude}; lon = {longitude} }}"")
/// </code>
/// </summary>
public static string Invariant(FormattableString formattable)
{
if (formattable == null)
{
throw new ArgumentNullException(""formattable"");
}
return formattable.ToString(Globalization.CultureInfo.InvariantCulture);
}
public override string ToString()
{
return ToString(Globalization.CultureInfo.CurrentCulture);
}
}
}
/*============================================================
**
** Class: FormattableStringFactory
**
**
** Purpose: implementation of the FormattableStringFactory
** class.
**
===========================================================*/
namespace System.Runtime.CompilerServices
{
/// <summary>
/// A factory type used by compilers to create instances of the type <see cref=""FormattableString""/>.
/// </summary>
public static class FormattableStringFactory
{
/// <summary>
/// Create a <see cref=""FormattableString""/> from a composite format string and object
/// array containing zero or more objects to format.
/// </summary>
public static FormattableString Create(string format, params object[] arguments)
{
if (format == null)
{
throw new ArgumentNullException(""format"");
}
if (arguments == null)
{
throw new ArgumentNullException(""arguments"");
}
return new ConcreteFormattableString(format, arguments);
}
private sealed class ConcreteFormattableString : FormattableString
{
private readonly string _format;
private readonly object[] _arguments;
internal ConcreteFormattableString(string format, object[] arguments)
{
_format = format;
_arguments = arguments;
}
public override string Format { get { return _format; } }
public override object[] GetArguments() { return _arguments; }
public override int ArgumentCount { get { return _arguments.Length; } }
public override object GetArgument(int index) { return _arguments[index]; }
public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, Format, _arguments); }
}
}
}
";
[Fact]
public void TargetType01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
IFormattable f = $""test"";
Console.Write(f is System.FormattableString);
}
}";
CompileAndVerify(source + formattableString, expectedOutput: "True");
}
[Fact]
public void TargetType02()
{
string source =
@"using System;
interface I1 { void M(String s); }
interface I2 { void M(FormattableString s); }
interface I3 { void M(IFormattable s); }
interface I4 : I1, I2 {}
interface I5 : I1, I3 {}
interface I6 : I2, I3 {}
interface I7 : I1, I2, I3 {}
class C : I1, I2, I3, I4, I5, I6, I7
{
public void M(String s) { Console.Write(1); }
public void M(FormattableString s) { Console.Write(2); }
public void M(IFormattable s) { Console.Write(3); }
}
class Program {
public static void Main(string[] args)
{
C c = new C();
((I1)c).M($"""");
((I2)c).M($"""");
((I3)c).M($"""");
((I4)c).M($"""");
((I5)c).M($"""");
((I6)c).M($"""");
((I7)c).M($"""");
((C)c).M($"""");
}
}";
CompileAndVerify(source + formattableString, expectedOutput: "12311211");
}
[Fact]
public void MissingHelper()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
IFormattable f = $""test"";
}
}";
CreateCompilationWithMscorlib40(source).VerifyEmitDiagnostics(
// (5,26): error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported
// IFormattable f = $"test";
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""test""").WithArguments("System.Runtime.CompilerServices.FormattableStringFactory").WithLocation(5, 26)
);
}
[Fact]
public void AsyncInterp()
{
string source =
@"using System;
using System.Threading.Tasks;
class Program {
public static void Main(string[] args)
{
Task<string> hello = Task.FromResult(""Hello"");
Task<string> world = Task.FromResult(""world"");
M(hello, world).Wait();
}
public static async Task M(Task<string> hello, Task<string> world)
{
Console.WriteLine($""{ await hello }, { await world }!"");
}
}";
CompileAndVerify(
source, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }, expectedOutput: "Hello, world!", targetFramework: TargetFramework.Empty);
}
[Fact]
public void AlignmentExpression()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { 123 , -(3+4) }."");
}
}";
CompileAndVerify(source + formattableString, expectedOutput: "X = 123 .");
}
[Fact]
public void AlignmentMagnitude()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { 123 , (32768) }."");
Console.WriteLine($""X = { 123 , -(32768) }."");
Console.WriteLine($""X = { 123 , (32767) }."");
Console.WriteLine($""X = { 123 , -(32767) }."");
Console.WriteLine($""X = { 123 , int.MaxValue }."");
Console.WriteLine($""X = { 123 , int.MinValue }."");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,42): warning CS8094: Alignment value 32768 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , (32768) }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "32768").WithArguments("32768", "32767").WithLocation(5, 42),
// (6,41): warning CS8094: Alignment value -32768 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , -(32768) }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "-(32768)").WithArguments("-32768", "32767").WithLocation(6, 41),
// (9,41): warning CS8094: Alignment value 2147483647 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , int.MaxValue }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MaxValue").WithArguments("2147483647", "32767").WithLocation(9, 41),
// (10,41): warning CS8094: Alignment value -2147483648 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , int.MinValue }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MinValue").WithArguments("-2147483648", "32767").WithLocation(10, 41)
);
}
[WorkItem(1097388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097388")]
[Fact]
public void InterpolationExpressionMustBeValue01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { String }."");
Console.WriteLine($""X = { null }."");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,35): error CS0119: 'string' is a type, which is not valid in the given context
// Console.WriteLine($"X = { String }.");
Diagnostic(ErrorCode.ERR_BadSKunknown, "String").WithArguments("string", "type").WithLocation(5, 35)
);
}
[Fact]
public void InterpolationExpressionMustBeValue02()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { x=>3 }."");
Console.WriteLine($""X = { Program.Main }."");
Console.WriteLine($""X = { Program.Main(null) }."");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,35): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type
// Console.WriteLine($"X = { x=>3 }.");
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x=>3").WithArguments("lambda expression", "object").WithLocation(5, 35),
// (6,43): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method?
// Console.WriteLine($"X = { Program.Main }.");
Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 43),
// (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object'
// Console.WriteLine($"X = { Program.Main(null) }.");
Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35)
);
}
[WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")]
[Fact]
public void BadCorelib01()
{
var text =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } }
public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } }
public struct Char { }
public class String { }
internal class Program
{
public static void Main()
{
var s = $""X = { 1 } "";
}
}
}";
CreateEmptyCompilation(text, options: TestOptions.DebugExe)
.VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"),
// (15,21): error CS0117: 'string' does not contain a definition for 'Format'
// var s = $"X = { 1 } ";
Diagnostic(ErrorCode.ERR_NoSuchMember, @"$""X = { 1 } """).WithArguments("string", "Format").WithLocation(15, 21)
);
}
[WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")]
[Fact]
public void BadCorelib02()
{
var text =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } }
public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } }
public struct Char { }
public class String {
public static Boolean Format(string format, int arg) { return true; }
}
internal class Program
{
public static void Main()
{
var s = $""X = { 1 } "";
}
}
}";
CreateEmptyCompilation(text, options: TestOptions.DebugExe)
.VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"),
// (17,21): error CS0029: Cannot implicitly convert type 'bool' to 'string'
// var s = $"X = { 1 } ";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""X = { 1 } """).WithArguments("bool", "string").WithLocation(17, 21)
);
}
[Fact]
public void SillyCoreLib01()
{
var text =
@"namespace System
{
interface IFormattable { }
namespace Runtime.CompilerServices {
public static class FormattableStringFactory {
public static Bozo Create(string format, int arg) { return new Bozo(); }
}
}
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } }
public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } }
public struct Char { }
public class String {
public static Bozo Format(string format, int arg) { return new Bozo(); }
}
public class FormattableString {
}
public class Bozo {
public static implicit operator string(Bozo bozo) { return ""zz""; }
public static implicit operator FormattableString(Bozo bozo) { return new FormattableString(); }
}
internal class Program
{
public static void Main()
{
var s1 = $""X = { 1 } "";
FormattableString s2 = $""X = { 1 } "";
}
}
}";
var comp = CreateEmptyCompilation(text, options: Test.Utilities.TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
var compilation = CompileAndVerify(comp, verify: Verification.Fails);
compilation.VerifyIL("System.Program.Main",
@"{
// Code size 35 (0x23)
.maxstack 2
IL_0000: ldstr ""X = {0} ""
IL_0005: ldc.i4.1
IL_0006: call ""System.Bozo string.Format(string, int)""
IL_000b: call ""string System.Bozo.op_Implicit(System.Bozo)""
IL_0010: pop
IL_0011: ldstr ""X = {0} ""
IL_0016: ldc.i4.1
IL_0017: call ""System.Bozo System.Runtime.CompilerServices.FormattableStringFactory.Create(string, int)""
IL_001c: call ""System.FormattableString System.Bozo.op_Implicit(System.Bozo)""
IL_0021: pop
IL_0022: ret
}");
}
[WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")]
[Fact]
public void Syntax01()
{
var text =
@"using System;
class Program
{
static void Main(string[] args)
{
var x = $""{ Math.Abs(value: 1):\}"";
var y = x;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,40): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string.
// var x = $"{ Math.Abs(value: 1):\}";
Diagnostic(ErrorCode.ERR_EscapedCurly, @"\").WithArguments("}").WithLocation(6, 40),
// (6,40): error CS1009: Unrecognized escape sequence
// var x = $"{ Math.Abs(value: 1):\}";
Diagnostic(ErrorCode.ERR_IllegalEscape, @"\}").WithLocation(6, 40)
);
}
[WorkItem(1097941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097941")]
[Fact]
public void Syntax02()
{
var text =
@"using S = System;
class C
{
void M()
{
var x = $""{ (S:
}
}";
// the precise diagnostics do not matter, as long as it is an error and not a crash.
Assert.True(SyntaxFactory.ParseSyntaxTree(text).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")]
[Fact]
public void Syntax03()
{
var text =
@"using System;
class Program
{
static void Main(string[] args)
{
var x = $""{ Math.Abs(value: 1):}}"";
var y = x;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,18): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'.
// var x = $"{ Math.Abs(value: 1):}}";
Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, @"""{").WithLocation(6, 18)
);
}
[WorkItem(1099105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099105")]
[Fact]
public void NoUnexpandedForm()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
string[] arr1 = new string[] { ""xyzzy"" };
object[] arr2 = arr1;
Console.WriteLine($""-{null}-"");
Console.WriteLine($""-{arr1}-"");
Console.WriteLine($""-{arr2}-"");
}
}";
CompileAndVerify(source + formattableString, expectedOutput:
@"--
-System.String[]-
-System.String[]-");
}
[WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")]
[Fact]
public void Dynamic01()
{
var text =
@"class C
{
const dynamic a = a;
string s = $""{0,a}"";
}";
CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (3,19): error CS0110: The evaluation of the constant value for 'C.a' involves a circular definition
// const dynamic a = a;
Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("C.a").WithLocation(3, 19),
// (3,23): error CS0134: 'C.a' is of type 'dynamic'. A const field of a reference type other than string can only be initialized with null.
// const dynamic a = a;
Diagnostic(ErrorCode.ERR_NotNullConstRefField, "a").WithArguments("C.a", "dynamic").WithLocation(3, 23),
// (4,21): error CS0150: A constant value is expected
// string s = $"{0,a}";
Diagnostic(ErrorCode.ERR_ConstantExpected, "a").WithLocation(4, 21)
);
}
[WorkItem(1099238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099238")]
[Fact]
public void Syntax04()
{
var text =
@"using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<string>> e = () => $""\u1{0:\u2}"";
Console.WriteLine(e);
}
}";
CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,46): error CS1009: Unrecognized escape sequence
// Expression<Func<string>> e = () => $"\u1{0:\u2}";
Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u1").WithLocation(8, 46),
// (8,52): error CS1009: Unrecognized escape sequence
// Expression<Func<string>> e = () => $"\u1{0:\u2}";
Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u2").WithLocation(8, 52)
);
}
[Fact, WorkItem(1098612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098612")]
public void MissingConversionFromFormattableStringToIFormattable()
{
var text =
@"namespace System.Runtime.CompilerServices
{
public static class FormattableStringFactory
{
public static FormattableString Create(string format, params object[] arguments)
{
return null;
}
}
}
namespace System
{
public abstract class FormattableString
{
}
}
static class C
{
static void Main()
{
System.IFormattable i = $""{""""}"";
}
}";
CreateCompilationWithMscorlib40AndSystemCore(text).VerifyEmitDiagnostics(
// (23,33): error CS0029: Cannot implicitly convert type 'FormattableString' to 'IFormattable'
// System.IFormattable i = $"{""}";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{""""}""").WithArguments("System.FormattableString", "System.IFormattable").WithLocation(23, 33)
);
}
[Theory, WorkItem(54702, "https://github.com/dotnet/roslyn/issues/54702")]
[InlineData(@"$""{s1}{s2}""", @"$""{s1}{s2}{s3}""", @"$""{s1}{s2}{s3}{s4}""", @"$""{s1}{s2}{s3}{s4}{s5}""")]
[InlineData(@"$""{s1}"" + $""{s2}""", @"$""{s1}"" + $""{s2}"" + $""{s3}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}"" + $""{s5}""")]
public void InterpolatedStringHandler_ConcatPreferencesForAllStringElements(string twoComponents, string threeComponents, string fourComponents, string fiveComponents)
{
var code = @"
using System;
Console.WriteLine(TwoComponents());
Console.WriteLine(ThreeComponents());
Console.WriteLine(FourComponents());
Console.WriteLine(FiveComponents());
string TwoComponents()
{
string s1 = ""1"";
string s2 = ""2"";
return " + twoComponents + @";
}
string ThreeComponents()
{
string s1 = ""1"";
string s2 = ""2"";
string s3 = ""3"";
return " + threeComponents + @";
}
string FourComponents()
{
string s1 = ""1"";
string s2 = ""2"";
string s3 = ""3"";
string s4 = ""4"";
return " + fourComponents + @";
}
string FiveComponents()
{
string s1 = ""1"";
string s2 = ""2"";
string s3 = ""3"";
string s4 = ""4"";
string s5 = ""5"";
return " + fiveComponents + @";
}
";
var handler = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { code, handler }, expectedOutput: @"
12
123
1234
value:1
value:2
value:3
value:4
value:5
");
verifier.VerifyIL("<Program>$.<<Main>$>g__TwoComponents|0_0()", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (string V_0) //s2
IL_0000: ldstr ""1""
IL_0005: ldstr ""2""
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: call ""string string.Concat(string, string)""
IL_0011: ret
}
");
verifier.VerifyIL("<Program>$.<<Main>$>g__ThreeComponents|0_1()", @"
{
// Code size 25 (0x19)
.maxstack 3
.locals init (string V_0, //s2
string V_1) //s3
IL_0000: ldstr ""1""
IL_0005: ldstr ""2""
IL_000a: stloc.0
IL_000b: ldstr ""3""
IL_0010: stloc.1
IL_0011: ldloc.0
IL_0012: ldloc.1
IL_0013: call ""string string.Concat(string, string, string)""
IL_0018: ret
}
");
verifier.VerifyIL("<Program>$.<<Main>$>g__FourComponents|0_2()", @"
{
// Code size 32 (0x20)
.maxstack 4
.locals init (string V_0, //s2
string V_1, //s3
string V_2) //s4
IL_0000: ldstr ""1""
IL_0005: ldstr ""2""
IL_000a: stloc.0
IL_000b: ldstr ""3""
IL_0010: stloc.1
IL_0011: ldstr ""4""
IL_0016: stloc.2
IL_0017: ldloc.0
IL_0018: ldloc.1
IL_0019: ldloc.2
IL_001a: call ""string string.Concat(string, string, string, string)""
IL_001f: ret
}
");
verifier.VerifyIL("<Program>$.<<Main>$>g__FiveComponents|0_3()", @"
{
// Code size 89 (0x59)
.maxstack 3
.locals init (string V_0, //s1
string V_1, //s2
string V_2, //s3
string V_3, //s4
string V_4, //s5
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_5)
IL_0000: ldstr ""1""
IL_0005: stloc.0
IL_0006: ldstr ""2""
IL_000b: stloc.1
IL_000c: ldstr ""3""
IL_0011: stloc.2
IL_0012: ldstr ""4""
IL_0017: stloc.3
IL_0018: ldstr ""5""
IL_001d: stloc.s V_4
IL_001f: ldloca.s V_5
IL_0021: ldc.i4.0
IL_0022: ldc.i4.5
IL_0023: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0028: ldloca.s V_5
IL_002a: ldloc.0
IL_002b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0030: ldloca.s V_5
IL_0032: ldloc.1
IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0038: ldloca.s V_5
IL_003a: ldloc.2
IL_003b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0040: ldloca.s V_5
IL_0042: ldloc.3
IL_0043: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0048: ldloca.s V_5
IL_004a: ldloc.s V_4
IL_004c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0051: ldloca.s V_5
IL_0053: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0058: ret
}
");
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandler_OverloadsAndBoolReturns(
bool useDefaultParameters,
bool useBoolReturns,
bool constructorBoolArg,
[CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression)
{
var source =
@"int a = 1;
System.Console.WriteLine(" + expression + @");";
string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg);
string expectedOutput = useDefaultParameters ?
@"base
value:1,alignment:0:format:
value:1,alignment:1:format:
value:1,alignment:0:format:X
value:1,alignment:2:format:Y" :
@"base
value:1
value:1,alignment:1
value:1:format:X
value:1,alignment:2:format:Y";
string expectedIl = getIl();
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
var comp1 = CreateCompilation(interpolatedStringBuilder);
foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() })
{
var comp2 = CreateCompilation(source, new[] { reference });
verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
}
string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch
{
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 80 (0x50)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_1
IL_0019: ldloc.0
IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_001f: ldloca.s V_1
IL_0021: ldloc.0
IL_0022: ldc.i4.1
IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_0028: ldloca.s V_1
IL_002a: ldloc.0
IL_002b: ldstr ""X""
IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldloc.0
IL_0038: ldc.i4.2
IL_0039: ldstr ""Y""
IL_003e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0043: ldloca.s V_1
IL_0045: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_004a: call ""void System.Console.WriteLine(string)""
IL_004f: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 84 (0x54)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_1
IL_0019: ldloc.0
IL_001a: ldc.i4.0
IL_001b: ldnull
IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0021: ldloca.s V_1
IL_0023: ldloc.0
IL_0024: ldc.i4.1
IL_0025: ldnull
IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_002b: ldloca.s V_1
IL_002d: ldloc.0
IL_002e: ldc.i4.0
IL_002f: ldstr ""X""
IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0039: ldloca.s V_1
IL_003b: ldloc.0
IL_003c: ldc.i4.2
IL_003d: ldstr ""Y""
IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0047: ldloca.s V_1
IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_004e: call ""void System.Console.WriteLine(string)""
IL_0053: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 92 (0x5c)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: brfalse.s IL_004d
IL_0019: ldloca.s V_1
IL_001b: ldloc.0
IL_001c: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0021: brfalse.s IL_004d
IL_0023: ldloca.s V_1
IL_0025: ldloc.0
IL_0026: ldc.i4.1
IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_002c: brfalse.s IL_004d
IL_002e: ldloca.s V_1
IL_0030: ldloc.0
IL_0031: ldstr ""X""
IL_0036: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_003b: brfalse.s IL_004d
IL_003d: ldloca.s V_1
IL_003f: ldloc.0
IL_0040: ldc.i4.2
IL_0041: ldstr ""Y""
IL_0046: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004b: br.s IL_004e
IL_004d: ldc.i4.0
IL_004e: pop
IL_004f: ldloca.s V_1
IL_0051: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0056: call ""void System.Console.WriteLine(string)""
IL_005b: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 96 (0x60)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: brfalse.s IL_0051
IL_0019: ldloca.s V_1
IL_001b: ldloc.0
IL_001c: ldc.i4.0
IL_001d: ldnull
IL_001e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0023: brfalse.s IL_0051
IL_0025: ldloca.s V_1
IL_0027: ldloc.0
IL_0028: ldc.i4.1
IL_0029: ldnull
IL_002a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_002f: brfalse.s IL_0051
IL_0031: ldloca.s V_1
IL_0033: ldloc.0
IL_0034: ldc.i4.0
IL_0035: ldstr ""X""
IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_003f: brfalse.s IL_0051
IL_0041: ldloca.s V_1
IL_0043: ldloc.0
IL_0044: ldc.i4.2
IL_0045: ldstr ""Y""
IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004f: br.s IL_0052
IL_0051: ldc.i4.0
IL_0052: pop
IL_0053: ldloca.s V_1
IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005a: call ""void System.Console.WriteLine(string)""
IL_005f: ret
}
",
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 89 (0x59)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_004a
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: ldloca.s V_1
IL_001d: ldloc.0
IL_001e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0023: ldloca.s V_1
IL_0025: ldloc.0
IL_0026: ldc.i4.1
IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_002c: ldloca.s V_1
IL_002e: ldloc.0
IL_002f: ldstr ""X""
IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_0039: ldloca.s V_1
IL_003b: ldloc.0
IL_003c: ldc.i4.2
IL_003d: ldstr ""Y""
IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0047: ldc.i4.1
IL_0048: br.s IL_004b
IL_004a: ldc.i4.0
IL_004b: pop
IL_004c: ldloca.s V_1
IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0053: call ""void System.Console.WriteLine(string)""
IL_0058: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 93 (0x5d)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_004e
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: ldloca.s V_1
IL_001d: ldloc.0
IL_001e: ldc.i4.0
IL_001f: ldnull
IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0025: ldloca.s V_1
IL_0027: ldloc.0
IL_0028: ldc.i4.1
IL_0029: ldnull
IL_002a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_002f: ldloca.s V_1
IL_0031: ldloc.0
IL_0032: ldc.i4.0
IL_0033: ldstr ""X""
IL_0038: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_003d: ldloca.s V_1
IL_003f: ldloc.0
IL_0040: ldc.i4.2
IL_0041: ldstr ""Y""
IL_0046: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004b: ldc.i4.1
IL_004c: br.s IL_004f
IL_004e: ldc.i4.0
IL_004f: pop
IL_0050: ldloca.s V_1
IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0057: call ""void System.Console.WriteLine(string)""
IL_005c: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 96 (0x60)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_0051
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: brfalse.s IL_0051
IL_001d: ldloca.s V_1
IL_001f: ldloc.0
IL_0020: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0025: brfalse.s IL_0051
IL_0027: ldloca.s V_1
IL_0029: ldloc.0
IL_002a: ldc.i4.1
IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_0030: brfalse.s IL_0051
IL_0032: ldloca.s V_1
IL_0034: ldloc.0
IL_0035: ldstr ""X""
IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_003f: brfalse.s IL_0051
IL_0041: ldloca.s V_1
IL_0043: ldloc.0
IL_0044: ldc.i4.2
IL_0045: ldstr ""Y""
IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004f: br.s IL_0052
IL_0051: ldc.i4.0
IL_0052: pop
IL_0053: ldloca.s V_1
IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005a: call ""void System.Console.WriteLine(string)""
IL_005f: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 100 (0x64)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_0055
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: brfalse.s IL_0055
IL_001d: ldloca.s V_1
IL_001f: ldloc.0
IL_0020: ldc.i4.0
IL_0021: ldnull
IL_0022: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0027: brfalse.s IL_0055
IL_0029: ldloca.s V_1
IL_002b: ldloc.0
IL_002c: ldc.i4.1
IL_002d: ldnull
IL_002e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0033: brfalse.s IL_0055
IL_0035: ldloca.s V_1
IL_0037: ldloc.0
IL_0038: ldc.i4.0
IL_0039: ldstr ""X""
IL_003e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0043: brfalse.s IL_0055
IL_0045: ldloca.s V_1
IL_0047: ldloc.0
IL_0048: ldc.i4.2
IL_0049: ldstr ""Y""
IL_004e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0053: br.s IL_0056
IL_0055: ldc.i4.0
IL_0056: pop
IL_0057: ldloca.s V_1
IL_0059: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005e: call ""void System.Console.WriteLine(string)""
IL_0063: ret
}
",
};
}
[Fact]
public void UseOfSpanInInterpolationHole_CSharp9()
{
var source = @"
using System;
ReadOnlySpan<char> span = stackalloc char[1];
Console.WriteLine($""{span}"");";
var comp = CreateCompilation(new[] { source, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false) }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,22): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// Console.WriteLine($"{span}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "span").WithArguments("interpolated string handlers", "10.0").WithLocation(4, 22)
);
}
[ConditionalTheory(typeof(MonoOrCoreClrOnly))]
[CombinatorialData]
public void UseOfSpanInInterpolationHole(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg,
[CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression)
{
var source =
@"
using System;
ReadOnlySpan<char> a = ""1"";
System.Console.WriteLine(" + expression + ");";
string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg);
string expectedOutput = useDefaultParameters ?
@"base
value:1,alignment:0:format:
value:1,alignment:1:format:
value:1,alignment:0:format:X
value:1,alignment:2:format:Y" :
@"base
value:1
value:1,alignment:1
value:1:format:X
value:1,alignment:2:format:Y";
string expectedIl = getIl();
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
var comp1 = CreateCompilation(interpolatedStringBuilder, targetFramework: TargetFramework.NetCoreApp);
foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() })
{
var comp2 = CreateCompilation(source, new[] { reference }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10);
verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
}
string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch
{
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 89 (0x59)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: ldloca.s V_1
IL_0022: ldloc.0
IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_0028: ldloca.s V_1
IL_002a: ldloc.0
IL_002b: ldc.i4.1
IL_002c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0031: ldloca.s V_1
IL_0033: ldloc.0
IL_0034: ldstr ""X""
IL_0039: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_003e: ldloca.s V_1
IL_0040: ldloc.0
IL_0041: ldc.i4.2
IL_0042: ldstr ""Y""
IL_0047: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_004c: ldloca.s V_1
IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0053: call ""void System.Console.WriteLine(string)""
IL_0058: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 93 (0x5d)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: ldloca.s V_1
IL_0022: ldloc.0
IL_0023: ldc.i4.0
IL_0024: ldnull
IL_0025: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_002a: ldloca.s V_1
IL_002c: ldloc.0
IL_002d: ldc.i4.1
IL_002e: ldnull
IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0034: ldloca.s V_1
IL_0036: ldloc.0
IL_0037: ldc.i4.0
IL_0038: ldstr ""X""
IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0042: ldloca.s V_1
IL_0044: ldloc.0
IL_0045: ldc.i4.2
IL_0046: ldstr ""Y""
IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0050: ldloca.s V_1
IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0057: call ""void System.Console.WriteLine(string)""
IL_005c: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 101 (0x65)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: brfalse.s IL_0056
IL_0022: ldloca.s V_1
IL_0024: ldloc.0
IL_0025: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_002a: brfalse.s IL_0056
IL_002c: ldloca.s V_1
IL_002e: ldloc.0
IL_002f: ldc.i4.1
IL_0030: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0035: brfalse.s IL_0056
IL_0037: ldloca.s V_1
IL_0039: ldloc.0
IL_003a: ldstr ""X""
IL_003f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_0044: brfalse.s IL_0056
IL_0046: ldloca.s V_1
IL_0048: ldloc.0
IL_0049: ldc.i4.2
IL_004a: ldstr ""Y""
IL_004f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0054: br.s IL_0057
IL_0056: ldc.i4.0
IL_0057: pop
IL_0058: ldloca.s V_1
IL_005a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005f: call ""void System.Console.WriteLine(string)""
IL_0064: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 105 (0x69)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: brfalse.s IL_005a
IL_0022: ldloca.s V_1
IL_0024: ldloc.0
IL_0025: ldc.i4.0
IL_0026: ldnull
IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_002c: brfalse.s IL_005a
IL_002e: ldloca.s V_1
IL_0030: ldloc.0
IL_0031: ldc.i4.1
IL_0032: ldnull
IL_0033: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0038: brfalse.s IL_005a
IL_003a: ldloca.s V_1
IL_003c: ldloc.0
IL_003d: ldc.i4.0
IL_003e: ldstr ""X""
IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0048: brfalse.s IL_005a
IL_004a: ldloca.s V_1
IL_004c: ldloc.0
IL_004d: ldc.i4.2
IL_004e: ldstr ""Y""
IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0058: br.s IL_005b
IL_005a: ldc.i4.0
IL_005b: pop
IL_005c: ldloca.s V_1
IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0063: call ""void System.Console.WriteLine(string)""
IL_0068: ret
}
",
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 98 (0x62)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_0053
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: ldloca.s V_1
IL_0026: ldloc.0
IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_002c: ldloca.s V_1
IL_002e: ldloc.0
IL_002f: ldc.i4.1
IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0035: ldloca.s V_1
IL_0037: ldloc.0
IL_0038: ldstr ""X""
IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_0042: ldloca.s V_1
IL_0044: ldloc.0
IL_0045: ldc.i4.2
IL_0046: ldstr ""Y""
IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0050: ldc.i4.1
IL_0051: br.s IL_0054
IL_0053: ldc.i4.0
IL_0054: pop
IL_0055: ldloca.s V_1
IL_0057: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005c: call ""void System.Console.WriteLine(string)""
IL_0061: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 105 (0x69)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_005a
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: brfalse.s IL_005a
IL_0026: ldloca.s V_1
IL_0028: ldloc.0
IL_0029: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_002e: brfalse.s IL_005a
IL_0030: ldloca.s V_1
IL_0032: ldloc.0
IL_0033: ldc.i4.1
IL_0034: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0039: brfalse.s IL_005a
IL_003b: ldloca.s V_1
IL_003d: ldloc.0
IL_003e: ldstr ""X""
IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_0048: brfalse.s IL_005a
IL_004a: ldloca.s V_1
IL_004c: ldloc.0
IL_004d: ldc.i4.2
IL_004e: ldstr ""Y""
IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0058: br.s IL_005b
IL_005a: ldc.i4.0
IL_005b: pop
IL_005c: ldloca.s V_1
IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0063: call ""void System.Console.WriteLine(string)""
IL_0068: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 102 (0x66)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_0057
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: ldloca.s V_1
IL_0026: ldloc.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_002e: ldloca.s V_1
IL_0030: ldloc.0
IL_0031: ldc.i4.1
IL_0032: ldnull
IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0038: ldloca.s V_1
IL_003a: ldloc.0
IL_003b: ldc.i4.0
IL_003c: ldstr ""X""
IL_0041: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0046: ldloca.s V_1
IL_0048: ldloc.0
IL_0049: ldc.i4.2
IL_004a: ldstr ""Y""
IL_004f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0054: ldc.i4.1
IL_0055: br.s IL_0058
IL_0057: ldc.i4.0
IL_0058: pop
IL_0059: ldloca.s V_1
IL_005b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0060: call ""void System.Console.WriteLine(string)""
IL_0065: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 109 (0x6d)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_005e
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: brfalse.s IL_005e
IL_0026: ldloca.s V_1
IL_0028: ldloc.0
IL_0029: ldc.i4.0
IL_002a: ldnull
IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0030: brfalse.s IL_005e
IL_0032: ldloca.s V_1
IL_0034: ldloc.0
IL_0035: ldc.i4.1
IL_0036: ldnull
IL_0037: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_003c: brfalse.s IL_005e
IL_003e: ldloca.s V_1
IL_0040: ldloc.0
IL_0041: ldc.i4.0
IL_0042: ldstr ""X""
IL_0047: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_004c: brfalse.s IL_005e
IL_004e: ldloca.s V_1
IL_0050: ldloc.0
IL_0051: ldc.i4.2
IL_0052: ldstr ""Y""
IL_0057: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_005c: br.s IL_005f
IL_005e: ldc.i4.0
IL_005f: pop
IL_0060: ldloca.s V_1
IL_0062: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0067: call ""void System.Console.WriteLine(string)""
IL_006c: ret
}
",
};
}
[Theory]
[InlineData(@"$""base{Throw()}{a = 2}""")]
[InlineData(@"$""base"" + $""{Throw()}"" + $""{a = 2}""")]
public void BoolReturns_ShortCircuit(string expression)
{
var source = @"
using System;
int a = 1;
Console.Write(" + expression + @");
Console.WriteLine(a);
string Throw() => throw new Exception();";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true, returnExpression: "false");
CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
base
1");
}
[Theory]
[CombinatorialData]
public void BoolOutParameter_ShortCircuits(bool useBoolReturns,
[CombinatorialValues(@"$""{Throw()}{a = 2}""", @"$""{Throw()}"" + $""{a = 2}""")] string expression)
{
var source = @"
using System;
int a = 1;
Console.WriteLine(a);
Console.WriteLine(" + expression + @");
Console.WriteLine(a);
string Throw() => throw new Exception();
";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: useBoolReturns, constructorBoolArg: true, constructorSuccessResult: false);
CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
1
1");
}
[Theory]
[InlineData(@"$""base{await Hole()}""")]
[InlineData(@"$""base"" + $""{await Hole()}""")]
public void AwaitInHoles_UsesFormat(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
Console.WriteLine(" + expression + @");
Task<int> Hole() => Task.FromResult(1);";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1");
verifier.VerifyIL("<Program>$.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", !expression.Contains("+") ? @"
{
// Code size 164 (0xa4)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_003e
IL_000a: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__Hole|0_0()""
IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.0
IL_0022: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_002e: ldarg.0
IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)""
IL_003c: leave.s IL_00a3
IL_003e: ldarg.0
IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_0044: stloc.2
IL_0045: ldarg.0
IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: dup
IL_0054: stloc.0
IL_0055: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_005a: ldloca.s V_2
IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0061: stloc.1
IL_0062: ldstr ""base{0}""
IL_0067: ldloc.1
IL_0068: box ""int""
IL_006d: call ""string string.Format(string, object)""
IL_0072: call ""void System.Console.WriteLine(string)""
IL_0077: leave.s IL_0090
}
catch System.Exception
{
IL_0079: stloc.3
IL_007a: ldarg.0
IL_007b: ldc.i4.s -2
IL_007d: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0082: ldarg.0
IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0088: ldloc.3
IL_0089: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_008e: leave.s IL_00a3
}
IL_0090: ldarg.0
IL_0091: ldc.i4.s -2
IL_0093: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0098: ldarg.0
IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00a3: ret
}
"
: @"
{
// Code size 174 (0xae)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_003e
IL_000a: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__Hole|0_0()""
IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.0
IL_0022: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_002e: ldarg.0
IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)""
IL_003c: leave.s IL_00ad
IL_003e: ldarg.0
IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_0044: stloc.2
IL_0045: ldarg.0
IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: dup
IL_0054: stloc.0
IL_0055: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_005a: ldloca.s V_2
IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0061: stloc.1
IL_0062: ldstr ""base""
IL_0067: ldstr ""{0}""
IL_006c: ldloc.1
IL_006d: box ""int""
IL_0072: call ""string string.Format(string, object)""
IL_0077: call ""string string.Concat(string, string)""
IL_007c: call ""void System.Console.WriteLine(string)""
IL_0081: leave.s IL_009a
}
catch System.Exception
{
IL_0083: stloc.3
IL_0084: ldarg.0
IL_0085: ldc.i4.s -2
IL_0087: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_008c: ldarg.0
IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0092: ldloc.3
IL_0093: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0098: leave.s IL_00ad
}
IL_009a: ldarg.0
IL_009b: ldc.i4.s -2
IL_009d: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_00a2: ldarg.0
IL_00a3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_00a8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00ad: ret
}");
}
[Theory]
[InlineData(@"$""base{hole}""")]
[InlineData(@"$""base"" + $""{hole}""")]
public void NoAwaitInHoles_UsesBuilder(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
var hole = await Hole();
Console.WriteLine(" + expression + @");
Task<int> Hole() => Task.FromResult(1);";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
base
value:1");
verifier.VerifyIL("<Program>$.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 185 (0xb9)
.maxstack 3
.locals init (int V_0,
int V_1, //hole
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_003e
IL_000a: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__Hole|0_0()""
IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.0
IL_0022: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_002e: ldarg.0
IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)""
IL_003c: leave.s IL_00b8
IL_003e: ldarg.0
IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_0044: stloc.2
IL_0045: ldarg.0
IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: dup
IL_0054: stloc.0
IL_0055: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_005a: ldloca.s V_2
IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0061: stloc.1
IL_0062: ldc.i4.4
IL_0063: ldc.i4.1
IL_0064: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0069: stloc.3
IL_006a: ldloca.s V_3
IL_006c: ldstr ""base""
IL_0071: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0076: ldloca.s V_3
IL_0078: ldloc.1
IL_0079: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_007e: ldloca.s V_3
IL_0080: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0085: call ""void System.Console.WriteLine(string)""
IL_008a: leave.s IL_00a5
}
catch System.Exception
{
IL_008c: stloc.s V_4
IL_008e: ldarg.0
IL_008f: ldc.i4.s -2
IL_0091: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0096: ldarg.0
IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_009c: ldloc.s V_4
IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_00a3: leave.s IL_00b8
}
IL_00a5: ldarg.0
IL_00a6: ldc.i4.s -2
IL_00a8: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_00ad: ldarg.0
IL_00ae: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_00b3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00b8: ret
}
");
}
[Theory]
[InlineData(@"$""base{hole}""")]
[InlineData(@"$""base"" + $""{hole}""")]
public void NoAwaitInHoles_AwaitInExpression_UsesBuilder(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
var hole = 2;
Test(await M(1), " + expression + @", await M(3));
void Test(int i1, string s, int i2) => Console.WriteLine(s);
Task<int> M(int i)
{
Console.WriteLine(i);
return Task.FromResult(1);
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
1
3
base
value:2");
verifier.VerifyIL("<Program>$.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 328 (0x148)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0050
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq IL_00dc
IL_0011: ldarg.0
IL_0012: ldc.i4.2
IL_0013: stfld ""int <Program>$.<<Main>$>d__0.<hole>5__2""
IL_0018: ldc.i4.1
IL_0019: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__M|0_1(int)""
IL_001e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0023: stloc.2
IL_0024: ldloca.s V_2
IL_0026: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_002b: brtrue.s IL_006c
IL_002d: ldarg.0
IL_002e: ldc.i4.0
IL_002f: dup
IL_0030: stloc.0
IL_0031: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0036: ldarg.0
IL_0037: ldloc.2
IL_0038: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_003d: ldarg.0
IL_003e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0043: ldloca.s V_2
IL_0045: ldarg.0
IL_0046: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)""
IL_004b: leave IL_0147
IL_0050: ldarg.0
IL_0051: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_0056: stloc.2
IL_0057: ldarg.0
IL_0058: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_005d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0063: ldarg.0
IL_0064: ldc.i4.m1
IL_0065: dup
IL_0066: stloc.0
IL_0067: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_006c: ldarg.0
IL_006d: ldloca.s V_2
IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0074: stfld ""int <Program>$.<<Main>$>d__0.<>7__wrap2""
IL_0079: ldarg.0
IL_007a: ldc.i4.4
IL_007b: ldc.i4.1
IL_007c: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0081: stloc.3
IL_0082: ldloca.s V_3
IL_0084: ldstr ""base""
IL_0089: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_008e: ldloca.s V_3
IL_0090: ldarg.0
IL_0091: ldfld ""int <Program>$.<<Main>$>d__0.<hole>5__2""
IL_0096: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_009b: ldloca.s V_3
IL_009d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_00a2: stfld ""string <Program>$.<<Main>$>d__0.<>7__wrap3""
IL_00a7: ldc.i4.3
IL_00a8: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__M|0_1(int)""
IL_00ad: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_00b2: stloc.2
IL_00b3: ldloca.s V_2
IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_00ba: brtrue.s IL_00f8
IL_00bc: ldarg.0
IL_00bd: ldc.i4.1
IL_00be: dup
IL_00bf: stloc.0
IL_00c0: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_00c5: ldarg.0
IL_00c6: ldloc.2
IL_00c7: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_00cc: ldarg.0
IL_00cd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_00d2: ldloca.s V_2
IL_00d4: ldarg.0
IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)""
IL_00da: leave.s IL_0147
IL_00dc: ldarg.0
IL_00dd: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_00e2: stloc.2
IL_00e3: ldarg.0
IL_00e4: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_00e9: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_00ef: ldarg.0
IL_00f0: ldc.i4.m1
IL_00f1: dup
IL_00f2: stloc.0
IL_00f3: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_00f8: ldloca.s V_2
IL_00fa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_00ff: stloc.1
IL_0100: ldarg.0
IL_0101: ldfld ""int <Program>$.<<Main>$>d__0.<>7__wrap2""
IL_0106: ldarg.0
IL_0107: ldfld ""string <Program>$.<<Main>$>d__0.<>7__wrap3""
IL_010c: ldloc.1
IL_010d: call ""void <Program>$.<<Main>$>g__Test|0_0(int, string, int)""
IL_0112: ldarg.0
IL_0113: ldnull
IL_0114: stfld ""string <Program>$.<<Main>$>d__0.<>7__wrap3""
IL_0119: leave.s IL_0134
}
catch System.Exception
{
IL_011b: stloc.s V_4
IL_011d: ldarg.0
IL_011e: ldc.i4.s -2
IL_0120: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0125: ldarg.0
IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_012b: ldloc.s V_4
IL_012d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0132: leave.s IL_0147
}
IL_0134: ldarg.0
IL_0135: ldc.i4.s -2
IL_0137: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_013c: ldarg.0
IL_013d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0142: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0147: ret
}
");
}
[Fact]
public void MissingCreate_01()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public override string ToString() => throw null;
public void Dispose() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5)
);
}
[Fact]
public void MissingCreate_02()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength) => throw null;
public override string ToString() => throw null;
public void Dispose() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5)
);
}
[Fact]
public void MissingCreate_03()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(ref int literalLength, int formattedCount) => throw null;
public override string ToString() => throw null;
public void Dispose() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS1620: Argument 1 must be passed with the 'ref' keyword
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{(object)1}""").WithArguments("1", "ref").WithLocation(1, 5)
);
}
[Theory]
[InlineData(null)]
[InlineData("public string ToStringAndClear(int literalLength) => throw null;")]
[InlineData("public void ToStringAndClear() => throw null;")]
[InlineData("public static string ToStringAndClear() => throw null;")]
public void MissingWellKnownMethod_ToStringAndClear(string toStringAndClearMethod)
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
" + toStringAndClearMethod + @"
public override string ToString() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics(
// (1,5): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear'
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "ToStringAndClear").WithLocation(1, 5)
);
}
[Fact]
public void ObsoleteCreateMethod()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
[System.Obsolete(""Constructor is obsolete"", error: true)]
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
public void Dispose() => throw null;
public override string ToString() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS0619: 'DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)' is obsolete: 'Constructor is obsolete'
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)", "Constructor is obsolete").WithLocation(1, 5)
);
}
[Fact]
public void ObsoleteAppendLiteralMethod()
{
var code = @"_ = $""base{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
public void Dispose() => throw null;
public override string ToString() => throw null;
[System.Obsolete(""AppendLiteral is obsolete"", error: true)]
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,7): error CS0619: 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is obsolete: 'AppendLiteral is obsolete'
// _ = $"base{(object)1}";
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "base").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "AppendLiteral is obsolete").WithLocation(1, 7)
);
}
[Fact]
public void ObsoleteAppendFormattedMethod()
{
var code = @"_ = $""base{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
public void Dispose() => throw null;
public override string ToString() => throw null;
public void AppendLiteral(string value) => throw null;
[System.Obsolete(""AppendFormatted is obsolete"", error: true)]
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,11): error CS0619: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is obsolete: 'AppendFormatted is obsolete'
// _ = $"base{(object)1}";
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)", "AppendFormatted is obsolete").WithLocation(1, 11)
);
}
private const string UnmanagedCallersOnlyIl = @"
.class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = (
01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72
69 74 65 64 00
)
.field public class [mscorlib]System.Type[] CallConvs
.field public string EntryPoint
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Attribute::.ctor()
ret
}
}";
[Fact]
public void UnmanagedCallersOnlyAppendFormattedMethod()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
.class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = (
01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d
62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65
73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72
74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73
69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70
69 6c 65 72 2e 01 00 00
)
.pack 0
.size 1
.method public hidebysig specialname rtspecialname
instance void .ctor (
int32 literalLength,
int32 formattedCount
) cil managed
{
ldnull
throw
}
.method public hidebysig
instance void Dispose () cil managed
{
ldnull
throw
}
.method public hidebysig virtual
instance string ToString () cil managed
{
ldnull
throw
}
.method public hidebysig
instance void AppendLiteral (
string 'value'
) cil managed
{
ldnull
throw
}
.method public hidebysig
instance void AppendFormatted<T> (
!!T hole,
[opt] int32 'alignment',
[opt] string format
) cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
.param [2] = int32(0)
.param [3] = nullref
ldnull
throw
}
}
";
var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl);
comp.VerifyDiagnostics(
// (1,7): error CS0570: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is not supported by the language
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BindToBogus, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)").WithLocation(1, 7)
);
}
[Fact]
public void UnmanagedCallersOnlyToStringMethod()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
.class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = (
01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d
62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65
73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72
74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73
69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70
69 6c 65 72 2e 01 00 00
)
.pack 0
.size 1
.method public hidebysig specialname rtspecialname
instance void .ctor (
int32 literalLength,
int32 formattedCount
) cil managed
{
ldnull
throw
}
.method public hidebysig instance string ToStringAndClear () cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
}
.method public hidebysig
instance void AppendLiteral (
string 'value'
) cil managed
{
ldnull
throw
}
.method public hidebysig
instance void AppendFormatted<T> (
!!T hole,
[opt] int32 'alignment',
[opt] string format
) cil managed
{
.param [2] = int32(0)
.param [3] = nullref
ldnull
throw
}
}
";
var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl);
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics(
// (1,5): error CS0570: 'DefaultInterpolatedStringHandler.ToStringAndClear()' is not supported by the language
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BindToBogus, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()").WithLocation(1, 5)
);
}
[Theory]
[InlineData(@"$""{i}{s}""")]
[InlineData(@"$""{i}"" + $""{s}""")]
public void UnsupportedArgumentType(string expression)
{
var source = @"
unsafe
{
int* i = null;
var s = new S();
_ = " + expression + @";
}
ref struct S
{
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: true, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (6,11): error CS0306: The type 'int*' may not be used as a type argument
// _ = $"{i}{s}";
Diagnostic(ErrorCode.ERR_BadTypeArgument, "{i}").WithArguments("int*").WithLocation(6, 11),
// (6,14): error CS0306: The type 'S' may not be used as a type argument
// _ = $"{i}{s}";
Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(6, 5 + expression.Length)
);
}
[Theory]
[InlineData(@"$""{b switch { true => 1, false => null }}{(!b ? null : 2)}{default}{null}""")]
[InlineData(@"$""{b switch { true => 1, false => null }}"" + $""{(!b ? null : 2)}"" + $""{default}"" + $""{null}""")]
public void TargetTypedInterpolationHoles(string expression)
{
var source = @"
bool b = true;
System.Console.WriteLine(" + expression + @");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
value:1
value:2
value:
value:");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 81 (0x51)
.maxstack 3
.locals init (bool V_0, //b
object V_1,
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_2
IL_0004: ldc.i4.0
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0017
IL_000e: ldc.i4.1
IL_000f: box ""int""
IL_0014: stloc.1
IL_0015: br.s IL_0019
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: ldloca.s V_2
IL_001b: ldloc.1
IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)""
IL_0021: ldloca.s V_2
IL_0023: ldloc.0
IL_0024: brfalse.s IL_002e
IL_0026: ldc.i4.2
IL_0027: box ""int""
IL_002c: br.s IL_002f
IL_002e: ldnull
IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)""
IL_0034: ldloca.s V_2
IL_0036: ldnull
IL_0037: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_003c: ldloca.s V_2
IL_003e: ldnull
IL_003f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0044: ldloca.s V_2
IL_0046: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_004b: call ""void System.Console.WriteLine(string)""
IL_0050: ret
}
");
}
[Theory]
[InlineData(@"$""{(null, default)}{new()}""")]
[InlineData(@"$""{(null, default)}"" + $""{new()}""")]
public void TargetTypedInterpolationHoles_Errors(string expression)
{
var source = @"System.Console.WriteLine(" + expression + @");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,29): error CS1503: Argument 1: cannot convert from '(<null>, default)' to 'object'
// System.Console.WriteLine($"{(null, default)}{new()}");
Diagnostic(ErrorCode.ERR_BadArgType, "(null, default)").WithArguments("1", "(<null>, default)", "object").WithLocation(1, 29),
// (1,29): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// System.Console.WriteLine($"{(null, default)}{new()}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(null, default)").WithArguments("interpolated string handlers", "10.0").WithLocation(1, 29),
// (1,46): error CS1729: 'string' does not contain a constructor that takes 0 arguments
// System.Console.WriteLine($"{(null, default)}{new()}");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(1, 19 + expression.Length)
);
}
[Fact]
public void RefTernary()
{
var source = @"
bool b = true;
int i = 1;
System.Console.WriteLine($""{(!b ? ref i : ref i)}"");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1");
}
[Fact]
public void NestedInterpolatedStrings_01()
{
var source = @"
int i = 1;
System.Console.WriteLine($""{$""{i}""}"");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (int V_0, //i
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.0
IL_0005: ldc.i4.1
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldloc.0
IL_000e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0013: ldloca.s V_1
IL_0015: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_001a: call ""void System.Console.WriteLine(string)""
IL_001f: ret
}
");
}
[Theory]
[InlineData(@"$""{$""{i1}""}{$""{i2}""}""")]
[InlineData(@"$""{$""{i1}""}"" + $""{$""{i2}""}""")]
public void NestedInterpolatedStrings_02(string expression)
{
var source = @"
int i1 = 1;
int i2 = 2;
System.Console.WriteLine(" + expression + @");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
value:1
value:2");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 63 (0x3f)
.maxstack 4
.locals init (int V_0, //i1
int V_1, //i2
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldloca.s V_2
IL_0006: ldc.i4.0
IL_0007: ldc.i4.1
IL_0008: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000d: ldloca.s V_2
IL_000f: ldloc.0
IL_0010: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0015: ldloca.s V_2
IL_0017: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_001c: ldloca.s V_2
IL_001e: ldc.i4.0
IL_001f: ldc.i4.1
IL_0020: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0025: ldloca.s V_2
IL_0027: ldloc.1
IL_0028: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_002d: ldloca.s V_2
IL_002f: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0034: call ""string string.Concat(string, string)""
IL_0039: call ""void System.Console.WriteLine(string)""
IL_003e: ret
}
");
}
[Fact]
public void ExceptionFilter_01()
{
var source = @"
using System;
int i = 1;
try
{
Console.WriteLine(""Starting try"");
throw new MyException { Prop = i };
}
// Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace
catch (MyException e) when (e.ToString() == $""{i}"".Trim())
{
Console.WriteLine(""Caught"");
}
class MyException : Exception
{
public int Prop { get; set; }
public override string ToString() => ""value:"" + Prop.ToString();
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
Starting try
Caught");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 95 (0x5f)
.maxstack 4
.locals init (int V_0, //i
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
.try
{
IL_0002: ldstr ""Starting try""
IL_0007: call ""void System.Console.WriteLine(string)""
IL_000c: newobj ""MyException..ctor()""
IL_0011: dup
IL_0012: ldloc.0
IL_0013: callvirt ""void MyException.Prop.set""
IL_0018: throw
}
filter
{
IL_0019: isinst ""MyException""
IL_001e: dup
IL_001f: brtrue.s IL_0025
IL_0021: pop
IL_0022: ldc.i4.0
IL_0023: br.s IL_004f
IL_0025: callvirt ""string object.ToString()""
IL_002a: ldloca.s V_1
IL_002c: ldc.i4.0
IL_002d: ldc.i4.1
IL_002e: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0033: ldloca.s V_1
IL_0035: ldloc.0
IL_0036: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_003b: ldloca.s V_1
IL_003d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0042: callvirt ""string string.Trim()""
IL_0047: call ""bool string.op_Equality(string, string)""
IL_004c: ldc.i4.0
IL_004d: cgt.un
IL_004f: endfilter
} // end filter
{ // handler
IL_0051: pop
IL_0052: ldstr ""Caught""
IL_0057: call ""void System.Console.WriteLine(string)""
IL_005c: leave.s IL_005e
}
IL_005e: ret
}
");
}
[ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))]
public void ExceptionFilter_02()
{
var source = @"
using System;
ReadOnlySpan<char> s = new char[] { 'i' };
try
{
Console.WriteLine(""Starting try"");
throw new MyException { Prop = s.ToString() };
}
// Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace
catch (MyException e) when (e.ToString() == $""{s}"".Trim())
{
Console.WriteLine(""Caught"");
}
class MyException : Exception
{
public string Prop { get; set; }
public override string ToString() => ""value:"" + Prop.ToString();
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp, expectedOutput: @"
Starting try
Caught");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 122 (0x7a)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //s
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: newarr ""char""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.s 105
IL_000a: stelem.i2
IL_000b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(char[])""
IL_0010: stloc.0
.try
{
IL_0011: ldstr ""Starting try""
IL_0016: call ""void System.Console.WriteLine(string)""
IL_001b: newobj ""MyException..ctor()""
IL_0020: dup
IL_0021: ldloca.s V_0
IL_0023: constrained. ""System.ReadOnlySpan<char>""
IL_0029: callvirt ""string object.ToString()""
IL_002e: callvirt ""void MyException.Prop.set""
IL_0033: throw
}
filter
{
IL_0034: isinst ""MyException""
IL_0039: dup
IL_003a: brtrue.s IL_0040
IL_003c: pop
IL_003d: ldc.i4.0
IL_003e: br.s IL_006a
IL_0040: callvirt ""string object.ToString()""
IL_0045: ldloca.s V_1
IL_0047: ldc.i4.0
IL_0048: ldc.i4.1
IL_0049: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_004e: ldloca.s V_1
IL_0050: ldloc.0
IL_0051: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_0056: ldloca.s V_1
IL_0058: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005d: callvirt ""string string.Trim()""
IL_0062: call ""bool string.op_Equality(string, string)""
IL_0067: ldc.i4.0
IL_0068: cgt.un
IL_006a: endfilter
} // end filter
{ // handler
IL_006c: pop
IL_006d: ldstr ""Caught""
IL_0072: call ""void System.Console.WriteLine(string)""
IL_0077: leave.s IL_0079
}
IL_0079: ret
}
");
}
[ConditionalTheory(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))]
[InlineData(@"$""{s}{c}""")]
[InlineData(@"$""{s}"" + $""{c}""")]
public void ImplicitUserDefinedConversionInHole(string expression)
{
var source = @"
using System;
S s = default;
C c = new C();
Console.WriteLine(" + expression + @");
ref struct S
{
public static implicit operator ReadOnlySpan<char>(S s) => ""S converted"";
}
class C
{
public static implicit operator ReadOnlySpan<char>(C s) => ""C converted"";
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder },
targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:S converted
value:C");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 57 (0x39)
.maxstack 3
.locals init (S V_0, //s
C V_1, //c
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: newobj ""C..ctor()""
IL_000d: stloc.1
IL_000e: ldloca.s V_2
IL_0010: ldc.i4.0
IL_0011: ldc.i4.2
IL_0012: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0017: ldloca.s V_2
IL_0019: ldloc.0
IL_001a: call ""System.ReadOnlySpan<char> S.op_Implicit(S)""
IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_0024: ldloca.s V_2
IL_0026: ldloc.1
IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<C>(C)""
IL_002c: ldloca.s V_2
IL_002e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0033: call ""void System.Console.WriteLine(string)""
IL_0038: ret
}
");
}
[Fact]
public void ExplicitUserDefinedConversionInHole()
{
var source = @"
using System;
S s = default;
Console.WriteLine($""{s}"");
ref struct S
{
public static explicit operator ReadOnlySpan<char>(S s) => ""S converted"";
}
";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (5,21): error CS0306: The type 'S' may not be used as a type argument
// Console.WriteLine($"{s}");
Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(5, 21)
);
}
[Theory]
[InlineData(@"$""Text{1}""")]
[InlineData(@"$""Text"" + $""{1}""")]
public void ImplicitUserDefinedConversionInLiteral(string expression)
{
var source = @"
using System;
Console.WriteLine(" + expression + @");
public struct CustomStruct
{
public static implicit operator CustomStruct(string s) => new CustomStruct { S = s };
public string S { get; set; }
public override string ToString() => ""literal:"" + S;
}
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString());
public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString());
}
}";
var verifier = CompileAndVerify(source, expectedOutput: @"
literal:Text
value:1");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 52 (0x34)
.maxstack 3
.locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.1
IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldstr ""Text""
IL_0010: call ""CustomStruct CustomStruct.op_Implicit(string)""
IL_0015: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(CustomStruct)""
IL_001a: ldloca.s V_0
IL_001c: ldc.i4.1
IL_001d: box ""int""
IL_0022: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)""
IL_0027: ldloca.s V_0
IL_0029: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: ret
}
");
}
[Theory]
[InlineData(@"$""Text{1}""")]
[InlineData(@"$""Text"" + $""{1}""")]
public void ExplicitUserDefinedConversionInLiteral(string expression)
{
var source = @"
using System;
Console.WriteLine(" + expression + @");
public struct CustomStruct
{
public static explicit operator CustomStruct(string s) => new CustomStruct { S = s };
public string S { get; set; }
public override string ToString() => ""literal:"" + S;
}
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString());
public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,21): error CS1503: Argument 1: cannot convert from 'string' to 'CustomStruct'
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_BadArgType, "Text").WithArguments("1", "string", "CustomStruct").WithLocation(4, 21)
);
}
[Theory]
[InlineData(@"$""Text{1}""")]
[InlineData(@"$""Text"" + $""{1}""")]
public void InvalidBuilderReturnType(string expression)
{
var source = @"
using System;
Console.WriteLine(" + expression + @");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public int AppendLiteral(string s) => 0;
public int AppendFormatted(object o) => 0;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,21): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is malformed. It does not return 'void' or 'bool'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)").WithLocation(4, 21),
// (4,25): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' is malformed. It does not return 'void' or 'bool'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)").WithLocation(4, 15 + expression.Length)
);
}
[Theory]
[InlineData(@"$""Text{1}""", @"$""{1}Text""")]
[InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")]
public void MixedBuilderReturnTypes_01(string expression1, string expression2)
{
var source = @"
using System;
Console.WriteLine(" + expression1 + @");
Console.WriteLine(" + expression2 + @");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public bool AppendLiteral(string s) => true;
public void AppendFormatted(object o) { }
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'bool'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "bool").WithLocation(4, 15 + expression1.Length),
// (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'void'.
// Console.WriteLine($"{1}Text");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "void").WithLocation(5, 14 + expression2.Length)
);
}
[Theory]
[InlineData(@"$""Text{1}""", @"$""{1}Text""")]
[InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")]
public void MixedBuilderReturnTypes_02(string expression1, string expression2)
{
var source = @"
using System;
Console.WriteLine(" + expression1 + @");
Console.WriteLine(" + expression2 + @");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public void AppendLiteral(string s) { }
public bool AppendFormatted(object o) => true;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'void'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "void").WithLocation(4, 15 + expression1.Length),
// (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'bool'.
// Console.WriteLine($"{1}Text");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "bool").WithLocation(5, 14 + expression2.Length)
);
}
[Fact]
public void MixedBuilderReturnTypes_03()
{
var source = @"
using System;
Console.WriteLine($""{1}"");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public bool AppendLiteral(string s) => true;
public void AppendFormatted(object o)
{
_builder.AppendLine(""value:"" + o.ToString());
}
}
}";
CompileAndVerify(source, expectedOutput: "value:1");
}
[Fact]
public void MixedBuilderReturnTypes_04()
{
var source = @"
using System;
using System.Text;
using System.Runtime.CompilerServices;
Console.WriteLine((CustomHandler)$""l"");
[InterpolatedStringHandler]
public class CustomHandler
{
private readonly StringBuilder _builder;
public CustomHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public override string ToString() => _builder.ToString();
public bool AppendFormatted(object o) => true;
public void AppendLiteral(string s)
{
_builder.AppendLine(""literal:"" + s.ToString());
}
}
";
CompileAndVerify(new[] { source, InterpolatedStringHandlerAttribute }, expectedOutput: "literal:l");
}
private static void VerifyInterpolatedStringExpression(CSharpCompilation comp, string handlerType = "CustomHandler")
{
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var descendentNodes = tree.GetRoot().DescendantNodes();
var interpolatedString =
(ExpressionSyntax)descendentNodes.OfType<BinaryExpressionSyntax>()
.Where(b => b.DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().Any())
.FirstOrDefault()
?? descendentNodes.OfType<InterpolatedStringExpressionSyntax>().Single();
var semanticInfo = model.GetSemanticInfoSummary(interpolatedString);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
Assert.Equal(handlerType, semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.InterpolatedStringHandler, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.ImplicitConversion.Exists);
Assert.True(semanticInfo.ImplicitConversion.IsValid);
Assert.True(semanticInfo.ImplicitConversion.IsInterpolatedStringHandler);
Assert.Null(semanticInfo.ImplicitConversion.Method);
if (interpolatedString is BinaryExpressionSyntax)
{
Assert.False(semanticInfo.ConstantValue.HasValue);
AssertEx.Equal("System.String System.String.op_Addition(System.String left, System.String right)", semanticInfo.Symbol.ToTestDisplayString());
}
// https://github.com/dotnet/roslyn/issues/54505 Assert IConversionOperation.IsImplicit when IOperation is implemented for interpolated strings.
}
private CompilationVerifier CompileAndVerifyOnCorrectPlatforms(CSharpCompilation compilation, string expectedOutput)
=> CompileAndVerify(
compilation,
expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null,
verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped);
[Theory]
[CombinatorialData]
public void CustomHandlerLocal([CombinatorialValues("class", "struct")] string type, bool useBoolReturns,
[CombinatorialValues(@"$""Literal{1,2:f}""", @"$""Literal"" + $""{1,2:f}""")] string expression)
{
var code = @"
CustomHandler builder = " + expression + @";
System.Console.WriteLine(builder.ToString());";
var builder = GetInterpolatedStringCustomHandlerType("CustomHandler", type, useBoolReturns);
var comp = CreateCompilation(new[] { code, builder });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
literal:Literal
value:1
alignment:2
format:f");
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (type, useBoolReturns) switch
{
(type: "struct", useBoolReturns: true) => @"
{
// Code size 67 (0x43)
.maxstack 4
.locals init (CustomHandler V_0, //builder
CustomHandler V_1)
IL_0000: ldloca.s V_1
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_1
IL_000b: ldstr ""Literal""
IL_0010: call ""bool CustomHandler.AppendLiteral(string)""
IL_0015: brfalse.s IL_002c
IL_0017: ldloca.s V_1
IL_0019: ldc.i4.1
IL_001a: box ""int""
IL_001f: ldc.i4.2
IL_0020: ldstr ""f""
IL_0025: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_002a: br.s IL_002d
IL_002c: ldc.i4.0
IL_002d: pop
IL_002e: ldloc.1
IL_002f: stloc.0
IL_0030: ldloca.s V_0
IL_0032: constrained. ""CustomHandler""
IL_0038: callvirt ""string object.ToString()""
IL_003d: call ""void System.Console.WriteLine(string)""
IL_0042: ret
}
",
(type: "struct", useBoolReturns: false) => @"
{
// Code size 61 (0x3d)
.maxstack 4
.locals init (CustomHandler V_0, //builder
CustomHandler V_1)
IL_0000: ldloca.s V_1
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_1
IL_000b: ldstr ""Literal""
IL_0010: call ""void CustomHandler.AppendLiteral(string)""
IL_0015: ldloca.s V_1
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: ldc.i4.2
IL_001e: ldstr ""f""
IL_0023: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0028: ldloc.1
IL_0029: stloc.0
IL_002a: ldloca.s V_0
IL_002c: constrained. ""CustomHandler""
IL_0032: callvirt ""string object.ToString()""
IL_0037: call ""void System.Console.WriteLine(string)""
IL_003c: ret
}
",
(type: "class", useBoolReturns: true) => @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""Literal""
IL_000e: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0013: brfalse.s IL_0029
IL_0015: ldloc.0
IL_0016: ldc.i4.1
IL_0017: box ""int""
IL_001c: ldc.i4.2
IL_001d: ldstr ""f""
IL_0022: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: callvirt ""string object.ToString()""
IL_0031: call ""void System.Console.WriteLine(string)""
IL_0036: ret
}
",
(type: "class", useBoolReturns: false) => @"
{
// Code size 47 (0x2f)
.maxstack 5
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldstr ""Literal""
IL_000d: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0012: dup
IL_0013: ldc.i4.1
IL_0014: box ""int""
IL_0019: ldc.i4.2
IL_001a: ldstr ""f""
IL_001f: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0024: callvirt ""string object.ToString()""
IL_0029: call ""void System.Console.WriteLine(string)""
IL_002e: ret
}
",
_ => throw ExceptionUtilities.Unreachable
};
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void CustomHandlerMethodArgument(string expression)
{
var code = @"
M(" + expression + @");
void M(CustomHandler b)
{
System.Console.WriteLine(b.ToString());
}";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", @"
{
// Code size 50 (0x32)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_0031: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"($""{1,2:f}"" + $""Literal"")")]
public void ExplicitHandlerCast_InCode(string expression)
{
var code = @"System.Console.WriteLine((CustomHandler)" + expression + @");";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) });
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
SyntaxNode syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single();
var semanticInfo = model.GetSemanticInfoSummary(syntax);
Assert.Equal("CustomHandler", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(SpecialType.System_Object, semanticInfo.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
syntax = ((CastExpressionSyntax)syntax).Expression;
Assert.Equal(expression, syntax.ToString());
semanticInfo = model.GetSemanticInfoSummary(syntax);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
Assert.Equal(SpecialType.System_String, semanticInfo.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
// https://github.com/dotnet/roslyn/issues/54505 Assert cast is explicit after IOperation is implemented
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 42 (0x2a)
.maxstack 5
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldc.i4.1
IL_0009: box ""int""
IL_000e: ldc.i4.2
IL_000f: ldstr ""f""
IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0019: dup
IL_001a: ldstr ""Literal""
IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0024: call ""void System.Console.WriteLine(object)""
IL_0029: ret
}
");
}
[Theory, WorkItem(55345, "https://github.com/dotnet/roslyn/issues/55345")]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void HandlerConversionPreferredOverStringForNonConstant(string expression)
{
var code = @"
CultureInfoNormalizer.Normalize();
C.M(" + expression + @");
class C
{
public static void M(CustomHandler b)
{
System.Console.WriteLine(b.ToString());
}
public static void M(string s)
{
System.Console.WriteLine(s);
}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.7
IL_0006: ldc.i4.1
IL_0007: newobj ""CustomHandler..ctor(int, int)""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldc.i4.1
IL_000f: box ""int""
IL_0014: ldc.i4.2
IL_0015: ldstr ""f""
IL_001a: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001f: brfalse.s IL_002e
IL_0021: ldloc.0
IL_0022: ldstr ""Literal""
IL_0027: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_002c: br.s IL_002f
IL_002e: ldc.i4.0
IL_002f: pop
IL_0030: ldloc.0
IL_0031: call ""void C.M(CustomHandler)""
IL_0036: ret
}
");
comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular9);
verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", expression.Contains('+') ? @"
{
// Code size 37 (0x25)
.maxstack 2
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldstr ""{0,2:f}""
IL_000a: ldc.i4.1
IL_000b: box ""int""
IL_0010: call ""string string.Format(string, object)""
IL_0015: ldstr ""Literal""
IL_001a: call ""string string.Concat(string, string)""
IL_001f: call ""void C.M(string)""
IL_0024: ret
}
"
: @"
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldstr ""{0,2:f}Literal""
IL_000a: ldc.i4.1
IL_000b: box ""int""
IL_0010: call ""string string.Format(string, object)""
IL_0015: call ""void C.M(string)""
IL_001a: ret
}
");
}
[Theory]
[InlineData(@"$""{""Literal""}""")]
[InlineData(@"$""{""Lit""}"" + $""{""eral""}""")]
public void StringPreferredOverHandlerConversionForConstant(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler b)
{
throw null;
}
public static void M(string s)
{
System.Console.WriteLine(s);
}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
var verifier = CompileAndVerify(comp, expectedOutput: @"Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""Literal""
IL_0005: call ""void C.M(string)""
IL_000a: ret
}
");
}
[Theory]
[InlineData(@"$""{1}{2}""")]
[InlineData(@"$""{1}"" + $""{2}""")]
public void HandlerConversionPreferredOverStringForNonConstant_AttributeConstructor(string expression)
{
var code = @"
using System;
[Attr(" + expression + @")]
class Attr : Attribute
{
public Attr(string s) {}
public Attr(CustomHandler c) {}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
comp.VerifyDiagnostics(
// (4,2): error CS0181: Attribute constructor parameter 'c' has type 'CustomHandler', which is not a valid attribute parameter type
// [Attr($"{1}{2}")]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("c", "CustomHandler").WithLocation(4, 2)
);
VerifyInterpolatedStringExpression(comp);
var attr = comp.SourceAssembly.SourceModule.GlobalNamespace.GetTypeMember("Attr");
Assert.Equal("Attr..ctor(CustomHandler c)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString());
}
[Theory]
[InlineData(@"$""{""Literal""}""")]
[InlineData(@"$""{""Lit""}"" + $""{""eral""}""")]
public void StringPreferredOverHandlerConversionForConstant_AttributeConstructor(string expression)
{
var code = @"
using System;
[Attr(" + expression + @")]
class Attr : Attribute
{
public Attr(string s) {}
public Attr(CustomHandler c) {}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate);
void validate(ModuleSymbol m)
{
var attr = m.GlobalNamespace.GetTypeMember("Attr");
Assert.Equal("Attr..ctor(System.String s)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString());
}
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void MultipleBuilderTypes(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler1 c) => throw null;
public static void M(CustomHandler2 c) => throw null;
}";
var comp = CreateCompilation(new[]
{
code,
GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false),
GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false)
});
comp.VerifyDiagnostics(
// (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(CustomHandler1)' and 'C.M(CustomHandler2)'
// C.M($"");
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(CustomHandler1)", "C.M(CustomHandler2)").WithLocation(2, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericOverloadResolution_01(string expression)
{
var code = @"
using System;
C.M(" + expression + @");
class C
{
public static void M<T>(T t) => throw null;
public static void M(CustomHandler c) => Console.WriteLine(c);
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 50 (0x32)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: call ""void C.M(CustomHandler)""
IL_0031: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericOverloadResolution_02(string expression)
{
var code = @"
using System;
C.M(" + expression + @");
class C
{
public static void M<T>(T t) where T : CustomHandler => throw null;
public static void M(CustomHandler c) => Console.WriteLine(c);
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 50 (0x32)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: call ""void C.M(CustomHandler)""
IL_0031: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericOverloadResolution_03(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M<T>(T t) where T : CustomHandler => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
comp.VerifyDiagnostics(
// (2,3): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(T)'. There is no implicit reference conversion from 'string' to 'CustomHandler'.
// C.M($"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(T)", "CustomHandler", "T", "string").WithLocation(2, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_01(string expression)
{
var code = @"
C.M(" + expression + @", default(CustomHandler));
C.M(default(CustomHandler), " + expression + @");
class C
{
public static void M<T>(T t1, T t2) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (2,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// C.M($"{1,2:f}Literal", default(CustomHandler));
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(2, 3),
// (3,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// C.M(default(CustomHandler), $"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_02(string expression)
{
var code = @"
using System;
C.M(default(CustomHandler), () => " + expression + @");
class C
{
public static void M<T>(T t1, Func<T> t2) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
comp.VerifyDiagnostics(
// (3,3): error CS0411: The type arguments for method 'C.M<T>(T, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// C.M(default(CustomHandler), () => $"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, System.Func<T>)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_03(string expression)
{
var code = @"
using System;
C.M(" + expression + @", default(CustomHandler));
class C
{
public static void M<T>(T t1, T t2) => Console.WriteLine(t1);
}
partial class CustomHandler
{
public static implicit operator CustomHandler(string s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 51 (0x33)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: ldnull
IL_002d: call ""void C.M<CustomHandler>(CustomHandler, CustomHandler)""
IL_0032: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_04(string expression)
{
var code = @"
using System;
C.M(default(CustomHandler), () => " + expression + @");
class C
{
public static void M<T>(T t1, Func<T> t2) => Console.WriteLine(t2());
}
partial class CustomHandler
{
public static implicit operator CustomHandler(string s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<Program>$.<>c.<<Main>$>b__0_0()", @"
{
// Code size 45 (0x2d)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_01(string expression)
{
var code = @"
using System;
Func<CustomHandler> f = () => " + expression + @";
Console.WriteLine(f());
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @"
{
// Code size 45 (0x2d)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_02(string expression)
{
var code = @"
using System;
CultureInfoNormalizer.Normalize();
C.M(() => " + expression + @");
class C
{
public static void M(Func<string> f) => Console.WriteLine(f());
public static void M(Func<CustomHandler> f) => throw null;
}
";
// Interpolated string handler conversions are not considered when determining the natural type of an expression: the natural return type of this lambda is string,
// so we don't even consider that there is a conversion from interpolated string expression to CustomHandler here (Sections 12.6.3.13 and 12.6.3.15 of the spec).
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
var verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal");
// No DefaultInterpolatedStringHandler was included in the compilation, so it falls back to string.Format
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", !expression.Contains('+') ? @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldstr ""{0,2:f}Literal""
IL_0005: ldc.i4.1
IL_0006: box ""int""
IL_000b: call ""string string.Format(string, object)""
IL_0010: ret
}
"
: @"
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: ldstr ""{0,2:f}""
IL_0005: ldc.i4.1
IL_0006: box ""int""
IL_000b: call ""string string.Format(string, object)""
IL_0010: ldstr ""Literal""
IL_0015: call ""string string.Concat(string, string)""
IL_001a: ret
}
");
}
[Theory]
[InlineData(@"$""{new S { Field = ""Field"" }}""")]
[InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")]
public void LambdaReturnInference_03(string expression)
{
// Same as 2, but using a type that isn't allowed in an interpolated string. There is an implicit conversion error on the ref struct
// when converting to a string, because S cannot be a component of an interpolated string. This conversion error causes the lambda to
// fail to bind as Func<string>, even though the natural return type is string, and the only successful bind is Func<CustomHandler>.
var code = @"
using System;
C.M(() => " + expression + @");
static class C
{
public static void M(Func<string> f) => throw null;
public static void M(Func<CustomHandler> f) => Console.WriteLine(f());
}
public partial class CustomHandler
{
public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field);
}
public ref struct S
{
public string Field { get; set; }
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field");
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @"
{
// Code size 35 (0x23)
.maxstack 4
.locals init (S V_0)
IL_0000: ldc.i4.0
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldloca.s V_0
IL_000a: initobj ""S""
IL_0010: ldloca.s V_0
IL_0012: ldstr ""Field""
IL_0017: call ""void S.Field.set""
IL_001c: ldloc.0
IL_001d: callvirt ""void CustomHandler.AppendFormatted(S)""
IL_0022: ret
}
");
}
[Theory]
[InlineData(@"$""{new S { Field = ""Field"" }}""")]
[InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")]
public void LambdaReturnInference_04(string expression)
{
// Same as 3, but with S added to DefaultInterpolatedStringHandler (which then allows the lambda to be bound as Func<string>, matching the natural return type)
var code = @"
using System;
C.M(() => " + expression + @");
static class C
{
public static void M(Func<string> f) => Console.WriteLine(f());
public static void M(Func<CustomHandler> f) => throw null;
}
public partial class CustomHandler
{
public void AppendFormatted(S value) => throw null;
}
public ref struct S
{
public string Field { get; set; }
}
namespace System.Runtime.CompilerServices
{
public ref partial struct DefaultInterpolatedStringHandler
{
public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field);
}
}
";
string[] source = new[] {
code,
GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false),
GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: true, useBoolReturns: false)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (3,11): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// C.M(() => $"{new S { Field = "Field" }}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, expression).WithArguments("interpolated string handlers", "10.0").WithLocation(3, 11),
// (3,14): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// C.M(() => $"{new S { Field = "Field" }}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"new S { Field = ""Field"" }").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 14)
);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field");
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0,
S V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldloca.s V_1
IL_000d: initobj ""S""
IL_0013: ldloca.s V_1
IL_0015: ldstr ""Field""
IL_001a: call ""void S.Field.set""
IL_001f: ldloc.1
IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(S)""
IL_0025: ldloca.s V_0
IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_05(string expression)
{
var code = @"
using System;
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => throw null;
public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false));
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0(bool)", @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_06(string expression)
{
// Same as 5, but with an implicit conversion from the builder type to string. This implicit conversion
// means that a best common type can be inferred for all branches of the lambda expression (Section 12.6.3.15 of the spec)
// and because there is a best common type, the inferred return type of the lambda is string. Since the inferred return type
// has an identity conversion to the return type of Func<bool, string>, that is preferred.
var code = @"
using System;
CultureInfoNormalizer.Normalize();
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => Console.WriteLine(f(false));
public static void M(Func<bool, CustomHandler> f) => throw null;
}
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0(bool)", !expression.Contains('+') ? @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0012
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0011: ret
IL_0012: ldstr ""{0,2:f}Literal""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: ret
}
"
: @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0012
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0011: ret
IL_0012: ldstr ""{0,2:f}""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: ldstr ""Literal""
IL_0027: call ""string string.Concat(string, string)""
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_07(string expression)
{
// Same as 5, but with an implicit conversion from string to the builder type.
var code = @"
using System;
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => Console.WriteLine(f(false));
public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false));
}
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0(bool)", @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_08(string expression)
{
// Same as 5, but with an implicit conversion from the builder type to string and from string to the builder type.
var code = @"
using System;
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => Console.WriteLine(f(false));
public static void M(Func<bool, CustomHandler> f) => throw null;
}
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
public static implicit operator CustomHandler(string c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Func<bool, string>)' and 'C.M(Func<bool, CustomHandler>)'
// C.M(b =>
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Func<bool, string>)", "C.M(System.Func<bool, CustomHandler>)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1}""")]
[InlineData(@"$""{1}"" + $""{2}""")]
public void LambdaInference_AmbiguousInOlderLangVersions(string expression)
{
var code = @"
using System;
C.M(param =>
{
param = " + expression + @";
});
static class C
{
public static void M(Action<string> f) => throw null;
public static void M(Action<CustomHandler> f) => throw null;
}
";
var source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) };
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
// This successful emit is being caused by https://github.com/dotnet/roslyn/issues/53761, along with the duplicate diagnostics in LambdaReturnInference_04
// We should not be changing binding behavior based on LangVersion.
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Action<string>)' and 'C.M(Action<CustomHandler>)'
// C.M(param =>
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Action<string>)", "C.M(System.Action<CustomHandler>)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_01(string expression)
{
var code = @"
using System;
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brtrue.s IL_0038
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: br.s IL_0041
IL_0038: ldloca.s V_0
IL_003a: initobj ""CustomHandler""
IL_0040: ldloc.0
IL_0041: box ""CustomHandler""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_02(string expression)
{
// Same as 01, but with a conversion from CustomHandler to string. The rules here are similar to LambdaReturnInference_06
var code = @"
using System;
CultureInfoNormalizer.Normalize();
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @"
{
// Code size 56 (0x38)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brtrue.s IL_0024
IL_0012: ldstr ""{0,2:f}Literal""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: br.s IL_0032
IL_0024: ldloca.s V_0
IL_0026: initobj ""CustomHandler""
IL_002c: ldloc.0
IL_002d: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0032: call ""void System.Console.WriteLine(string)""
IL_0037: ret
}
"
: @"
{
// Code size 66 (0x42)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brtrue.s IL_002e
IL_0012: ldstr ""{0,2:f}""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: ldstr ""Literal""
IL_0027: call ""string string.Concat(string, string)""
IL_002c: br.s IL_003c
IL_002e: ldloca.s V_0
IL_0030: initobj ""CustomHandler""
IL_0036: ldloc.0
IL_0037: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_003c: call ""void System.Console.WriteLine(string)""
IL_0041: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_03(string expression)
{
// Same as 02, but with a target-type
var code = @"
using System;
CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler'
// CustomHandler x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("string", "CustomHandler").WithLocation(4, 19)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_04(string expression)
{
// Same 01, but with a conversion from string to CustomHandler. The rules here are similar to LambdaReturnInference_07
var code = @"
using System;
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brtrue.s IL_0038
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: br.s IL_0041
IL_0038: ldloca.s V_0
IL_003a: initobj ""CustomHandler""
IL_0040: ldloc.0
IL_0041: box ""CustomHandler""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_05(string expression)
{
// Same 01, but with a conversion from string to CustomHandler and CustomHandler to string.
var code = @"
using System;
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,9): error CS0172: Type of conditional expression cannot be determined because 'CustomHandler' and 'string' implicitly convert to one another
// var x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal";
Diagnostic(ErrorCode.ERR_AmbigQM, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("CustomHandler", "string").WithLocation(4, 9)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_06(string expression)
{
// Same 05, but with a target type
var code = @"
using System;
CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => c.ToString();
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brtrue.s IL_0038
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: br.s IL_0041
IL_0038: ldloca.s V_0
IL_003a: initobj ""CustomHandler""
IL_0040: ldloc.0
IL_0041: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0046: call ""void System.Console.WriteLine(string)""
IL_004b: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_01(string expression)
{
// Switch expressions infer a best type based on _types_, not based on expressions (section 12.6.3.15 of the spec). Because this is based on types
// and not on expression conversions, no best type can be found for this switch expression.
var code = @"
using System;
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,29): error CS8506: No best type was found for the switch expression.
// var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_02(string expression)
{
// Same as 01, but with a conversion from CustomHandler. This allows the switch expression to infer a best-common type, which is string.
var code = @"
using System;
CultureInfoNormalizer.Normalize();
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @"
{
// Code size 59 (0x3b)
.maxstack 2
.locals init (string V_0,
CustomHandler V_1)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brfalse.s IL_0023
IL_0012: ldloca.s V_1
IL_0014: initobj ""CustomHandler""
IL_001a: ldloc.1
IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0020: stloc.0
IL_0021: br.s IL_0034
IL_0023: ldstr ""{0,2:f}Literal""
IL_0028: ldc.i4.1
IL_0029: box ""int""
IL_002e: call ""string string.Format(string, object)""
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: call ""void System.Console.WriteLine(string)""
IL_003a: ret
}
"
: @"
{
// Code size 69 (0x45)
.maxstack 2
.locals init (string V_0,
CustomHandler V_1)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brfalse.s IL_0023
IL_0012: ldloca.s V_1
IL_0014: initobj ""CustomHandler""
IL_001a: ldloc.1
IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0020: stloc.0
IL_0021: br.s IL_003e
IL_0023: ldstr ""{0,2:f}""
IL_0028: ldc.i4.1
IL_0029: box ""int""
IL_002e: call ""string string.Format(string, object)""
IL_0033: ldstr ""Literal""
IL_0038: call ""string string.Concat(string, string)""
IL_003d: stloc.0
IL_003e: ldloc.0
IL_003f: call ""void System.Console.WriteLine(string)""
IL_0044: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_03(string expression)
{
// Same 02, but with a target-type. The natural type will fail to compile, so the switch will use a target type (unlike TernaryTypes_03, which fails to compile).
var code = @"
using System;
CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => c.ToString();
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (CustomHandler V_0,
CustomHandler V_1)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brfalse.s IL_0019
IL_000d: ldloca.s V_1
IL_000f: initobj ""CustomHandler""
IL_0015: ldloc.1
IL_0016: stloc.0
IL_0017: br.s IL_0043
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.7
IL_001c: ldc.i4.1
IL_001d: call ""CustomHandler..ctor(int, int)""
IL_0022: ldloca.s V_1
IL_0024: ldc.i4.1
IL_0025: box ""int""
IL_002a: ldc.i4.2
IL_002b: ldstr ""f""
IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldstr ""Literal""
IL_003c: call ""void CustomHandler.AppendLiteral(string)""
IL_0041: ldloc.1
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0049: call ""void System.Console.WriteLine(string)""
IL_004e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_04(string expression)
{
// Same as 01, but with a conversion to CustomHandler. This allows the switch expression to infer a best-common type, which is CustomHandler.
var code = @"
using System;
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (CustomHandler V_0,
CustomHandler V_1)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brfalse.s IL_0019
IL_000d: ldloca.s V_1
IL_000f: initobj ""CustomHandler""
IL_0015: ldloc.1
IL_0016: stloc.0
IL_0017: br.s IL_0043
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.7
IL_001c: ldc.i4.1
IL_001d: call ""CustomHandler..ctor(int, int)""
IL_0022: ldloca.s V_1
IL_0024: ldc.i4.1
IL_0025: box ""int""
IL_002a: ldc.i4.2
IL_002b: ldstr ""f""
IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldstr ""Literal""
IL_003c: call ""void CustomHandler.AppendLiteral(string)""
IL_0041: ldloc.1
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: box ""CustomHandler""
IL_0049: call ""void System.Console.WriteLine(object)""
IL_004e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_05(string expression)
{
// Same as 01, but with conversions in both directions. No best common type can be found.
var code = @"
using System;
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,29): error CS8506: No best type was found for the switch expression.
// var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_06(string expression)
{
// Same as 05, but with a target type.
var code = @"
using System;
CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => c.ToString();
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (CustomHandler V_0,
CustomHandler V_1)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brfalse.s IL_0019
IL_000d: ldloca.s V_1
IL_000f: initobj ""CustomHandler""
IL_0015: ldloc.1
IL_0016: stloc.0
IL_0017: br.s IL_0043
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.7
IL_001c: ldc.i4.1
IL_001d: call ""CustomHandler..ctor(int, int)""
IL_0022: ldloca.s V_1
IL_0024: ldc.i4.1
IL_0025: box ""int""
IL_002a: ldc.i4.2
IL_002b: ldstr ""f""
IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldstr ""Literal""
IL_003c: call ""void CustomHandler.AppendLiteral(string)""
IL_0041: ldloc.1
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0049: call ""void System.Console.WriteLine(string)""
IL_004e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_01(string expression)
{
var code = @"
M(" + expression + @");
void M(ref CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 48 (0x30)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_0
IL_002a: call ""void <Program>$.<<Main>$>g__M|0_0(ref CustomHandler)""
IL_002f: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_02(string expression)
{
var code = @"
M(" + expression + @");
M(ref " + expression + @");
void M(ref CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (2,3): error CS1620: Argument 1 must be passed with the 'ref' keyword
// M($"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("1", "ref").WithLocation(2, 3),
// (3,7): error CS1510: A ref or out value must be an assignable variable
// M(ref $"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_RefLvalueExpected, expression).WithLocation(3, 7)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_03(string expression)
{
var code = @"
M(" + expression + @");
void M(in CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 45 (0x2d)
.maxstack 5
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldc.i4.1
IL_0009: box ""int""
IL_000e: ldc.i4.2
IL_000f: ldstr ""f""
IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0019: dup
IL_001a: ldstr ""Literal""
IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0024: stloc.0
IL_0025: ldloca.s V_0
IL_0027: call ""void <Program>$.<<Main>$>g__M|0_0(in CustomHandler)""
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_04(string expression)
{
var code = @"
M(" + expression + @");
void M(in CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 48 (0x30)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_0
IL_002a: call ""void <Program>$.<<Main>$>g__M|0_0(in CustomHandler)""
IL_002f: ret
}
");
}
[Theory]
[CombinatorialData]
public void RefOverloadResolution_Struct([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler c) => System.Console.WriteLine(c);
public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c);
}";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 47 (0x2f)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloc.0
IL_0029: call ""void C.M(CustomHandler)""
IL_002e: ret
}
");
}
[Theory]
[CombinatorialData]
public void RefOverloadResolution_Class([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler c) => System.Console.WriteLine(c);
public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c);
}";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 47 (0x2f)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloc.0
IL_0029: call ""void C.M(CustomHandler)""
IL_002e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void RefOverloadResolution_MultipleBuilderTypes(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler1 c) => System.Console.WriteLine(c);
public static void M(ref CustomHandler2 c) => throw null;
}";
var comp = CreateCompilation(new[]
{
code,
GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false),
GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false)
});
VerifyInterpolatedStringExpression(comp, "CustomHandler1");
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 47 (0x2f)
.maxstack 4
.locals init (CustomHandler1 V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler1..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler1.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler1.AppendLiteral(string)""
IL_0028: ldloc.0
IL_0029: call ""void C.M(CustomHandler1)""
IL_002e: ret
}
");
}
private const string InterpolatedStringHandlerAttributesVB = @"
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=False, Inherited:=False)>
Public NotInheritable Class InterpolatedStringHandlerAttribute
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=False, Inherited:=False)>
Public NotInheritable Class InterpolatedStringHandlerArgumentAttribute
Inherits Attribute
Public Sub New(argument As String)
Arguments = { argument }
End Sub
Public Sub New(ParamArray arguments() as String)
Me.Arguments = arguments
End Sub
Public ReadOnly Property Arguments As String()
End Class
End Namespace
";
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute });
comp.VerifyDiagnostics(
// (8,27): error CS8946: 'string' is not an interpolated string handler type.
// public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {}
Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("string").WithLocation(8, 27)
);
var sParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(sParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType_Metadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i as Integer, <InterpolatedStringHandlerArgument(""i"")> c As String)
End Sub
End Class
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
// Note: there is no compilation error here because the natural type of a string is still string, and
// we just bind to that method without checking the handler attribute.
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics();
var sParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(sParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_InvalidArgument(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (8,70): error CS1503: Argument 1: cannot convert from 'int' to 'string'
// public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(8, 70)
);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""NonExistant"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5),
// (8,27): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(CustomHandler)'.
// public static void M([InterpolatedStringHandlerArgumentAttribute("NonExistant")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant"")").WithArguments("NonExistant", "C.M(CustomHandler)").WithLocation(8, 27)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(""NonExistant"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(int, CustomHandler)'.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("i", "NonExistant")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")").WithArguments("NonExistant", "C.M(int, CustomHandler)").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""i"", ""NonExistant"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8945: 'NonExistant1' is not a valid parameter name from 'C.M(int, CustomHandler)'.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant1", "C.M(int, CustomHandler)").WithLocation(8, 34),
// (8,34): error CS8945: 'NonExistant2' is not a valid parameter name from 'C.M(int, CustomHandler)'.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant2", "C.M(int, CustomHandler)").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""NonExistant1"", ""NonExistant2"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ReferenceSelf(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""c"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8948: InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("c")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, @"InterpolatedStringHandlerArgumentAttribute(""c"")").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_ReferencesSelf_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(""c"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8943: null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, "InterpolatedStringHandlerArgumentAttribute(new string[] { null })").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_01()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing })> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_02()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing, ""i"" })> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_03()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(CStr(Nothing))> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5),
// (8,27): error CS8944: 'C.M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// public static void M([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.M(CustomHandler)").WithLocation(8, 27)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"{""""}")]
[InlineData(@"""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod_FromMetadata(string arg)
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
_ = new C(" + expression + @");
class C
{
public C([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// _ = new C($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 11),
// (8,15): error CS8944: 'C.C(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// public C([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.C(CustomHandler)").WithLocation(8, 15)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod(".ctor").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"{""""}")]
[InlineData(@"""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor_FromMetadata(string arg)
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Sub New(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"_ = new C($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// _ = new C($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 11),
// (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// _ = new C($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 11),
// (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// _ = new C($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 11)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod(".ctor").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerAttributeArgumentError_SubstitutedTypeSymbol(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C<CustomHandler>.M(" + expression + @");
public class C<T>
{
public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { }
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler });
comp.VerifyDiagnostics(
// (4,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 20),
// (8,27): error CS8946: 'T' is not an interpolated string handler type.
// public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { }
Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("T").WithLocation(8, 27)
);
var c = comp.SourceModule.GlobalNamespace.GetTypeMember("C");
var handler = comp.SourceModule.GlobalNamespace.GetTypeMember("CustomHandler");
var substitutedC = c.WithTypeArguments(ImmutableArray.Create(TypeWithAnnotations.Create(handler)));
var cParam = substitutedC.GetMethod("M").Parameters.Single();
Assert.IsType<SubstitutedParameterSymbol>(cParam);
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_SubstitutedTypeSymbol_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C(Of T)
Public Shared Sub M(<InterpolatedStringHandlerArgument()> c As T)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C<CustomHandler>.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 20),
// (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 20),
// (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 20)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C`1").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""text""", @"$""text"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
public class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var goodCode = @"
int i = 10;
C.M(i: i, c: " + expression + @");
";
var comp = CreateCompilation(new[] { code, goodCode, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"
i:10
literal:text
");
verifier.VerifyDiagnostics(
// (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller
// to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString());
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27)
);
verifyIL(verifier);
var badCode = @"C.M(" + expression + @", 1);";
comp = CreateCompilation(new[] { code, badCode, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (1,10): error CS8950: Parameter 'i' is an argument to the interpolated string handler conversion on parameter 'c', but is specified after the interpolated string constant. Reorder the arguments to move 'i' before 'c'.
// C.M($"", 1);
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, "1").WithArguments("i", "c").WithLocation(1, 7 + expression.Length),
// (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller
// to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString());
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27)
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.First();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
void verifyIL(CompilationVerifier verifier)
{
verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == ""
? @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init (int V_0,
int V_1,
CustomHandler V_2)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ldloca.s V_2
IL_0007: ldc.i4.4
IL_0008: ldc.i4.0
IL_0009: ldloc.0
IL_000a: call ""CustomHandler..ctor(int, int, int)""
IL_000f: ldloca.s V_2
IL_0011: ldstr ""text""
IL_0016: call ""bool CustomHandler.AppendLiteral(string)""
IL_001b: pop
IL_001c: ldloc.2
IL_001d: ldloc.1
IL_001e: call ""void C.M(CustomHandler, int)""
IL_0023: ret
}
"
: @"
{
// Code size 43 (0x2b)
.maxstack 4
.locals init (int V_0,
int V_1,
CustomHandler V_2,
bool V_3)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ldc.i4.4
IL_0006: ldc.i4.0
IL_0007: ldloc.0
IL_0008: ldloca.s V_3
IL_000a: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000f: stloc.2
IL_0010: ldloc.3
IL_0011: brfalse.s IL_0021
IL_0013: ldloca.s V_2
IL_0015: ldstr ""text""
IL_001a: call ""bool CustomHandler.AppendLiteral(string)""
IL_001f: br.s IL_0022
IL_0021: ldc.i4.0
IL_0022: pop
IL_0023: ldloc.2
IL_0024: ldloc.1
IL_0025: call ""void C.M(CustomHandler, int)""
IL_002a: ret
}
");
}
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(""i"")> c As CustomHandler, i As Integer)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation("", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics();
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.First();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_OptionalNotSpecifiedAtCallsite(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
public class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i = 0) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount)
{
}
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler });
comp.VerifyDiagnostics(
// (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5),
// (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { }
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ParamsNotSpecifiedAtCallsite(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
public class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, params int[] i) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int[] i) : this(literalLength, formattedCount)
{
}
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler });
comp.VerifyDiagnostics(
// (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5),
// (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { }
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MissingConstructor(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate).VerifyDiagnostics();
CreateCompilation(@"C.M(1, " + expression + @");", new[] { comp.ToMetadataReference() }).VerifyDiagnostics(
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8)
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_InaccessibleConstructor_01(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {}
}
public partial struct CustomHandler
{
private CustomHandler(int literalLength, int formattedCount, int i) : this() {}
static void InCustomHandler()
{
C.M(1, " + expression + @");
}
}
";
var executableCode = @"C.M(1, " + expression + @");";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8)
);
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics();
comp = CreateCompilation(executableCode, new[] { dependency.EmitToImageReference() });
comp.VerifyDiagnostics(
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
comp = CreateCompilation(executableCode, new[] { dependency.ToMetadataReference() });
comp.VerifyDiagnostics(
// (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8)
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
}
private void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes(string mRef, string customHandlerRef, string expression, params DiagnosticDescription[] expectedDiagnostics)
{
var code = @"
using System.Runtime.CompilerServices;
int i = 0;
C.M(" + mRef + @" i, " + expression + @");
public class C
{
public static void M(" + mRef + @" int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) { " + (mRef == "out" ? "i = 0;" : "") + @" }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, " + customHandlerRef + @" int i) : this() { " + (customHandlerRef == "out" ? "i = 0;" : "") + @" }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(expectedDiagnostics);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefNone(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "", expression,
// (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword
// C.M(ref i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefOut(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "out", expression,
// (5,9): error CS1620: Argument 3 must be passed with the 'out' keyword
// C.M(ref i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefIn(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "in", expression,
// (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword
// C.M(ref i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InNone(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "", expression,
// (5,8): error CS1615: Argument 3 may not be passed with the 'in' keyword
// C.M(in i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "in").WithLocation(5, 8));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InOut(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "out", expression,
// (5,8): error CS1620: Argument 3 must be passed with the 'out' keyword
// C.M(in i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 8));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InRef(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "ref", expression,
// (5,8): error CS1620: Argument 3 must be passed with the 'ref' keyword
// C.M(in i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 8));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutNone(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "", expression,
// (5,9): error CS1615: Argument 3 may not be passed with the 'out' keyword
// C.M(out i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "out").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutRef(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "ref", expression,
// (5,9): error CS1620: Argument 3 must be passed with the 'ref' keyword
// C.M(out i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneRef(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "ref", expression,
// (5,6): error CS1620: Argument 3 must be passed with the 'ref' keyword
// C.M( i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 6));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneOut(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "out", expression,
// (5,6): error CS1620: Argument 3 must be passed with the 'out' keyword
// C.M( i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 6));
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedType([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s" + extraConstructorArg + @") : this()
{
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var executableCode = @"C.M(1, " + expression + @");";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var expectedDiagnostics = extraConstructorArg == ""
? new DiagnosticDescription[]
{
// (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string'
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5)
}
: new DiagnosticDescription[]
{
// (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string'
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5),
// (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, string, out bool)'
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, string, out bool)").WithLocation(1, 8)
};
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(expectedDiagnostics);
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics();
foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() })
{
comp = CreateCompilation(executableCode, new[] { d });
comp.VerifyDiagnostics(expectedDiagnostics);
}
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_SingleArg([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""2""", @"$""2"" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static string M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) => c.ToString();
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var executableCode = @"
using System;
int i = 10;
Console.WriteLine(C.M(i, " + expression + @"));
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i:10
literal:2");
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() })
{
verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: @"
i:10
literal:2");
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
}
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
static void verifyIL(string extraConstructorArg, CompilationVerifier verifier)
{
verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == ""
? @"
{
// Code size 39 (0x27)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldloca.s V_1
IL_0006: ldc.i4.1
IL_0007: ldc.i4.0
IL_0008: ldloc.0
IL_0009: call ""CustomHandler..ctor(int, int, int)""
IL_000e: ldloca.s V_1
IL_0010: ldstr ""2""
IL_0015: call ""bool CustomHandler.AppendLiteral(string)""
IL_001a: pop
IL_001b: ldloc.1
IL_001c: call ""string C.M(int, CustomHandler)""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: ret
}
"
: @"
{
// Code size 46 (0x2e)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.1
IL_0005: ldc.i4.0
IL_0006: ldloc.0
IL_0007: ldloca.s V_2
IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000e: stloc.1
IL_000f: ldloc.2
IL_0010: brfalse.s IL_0020
IL_0012: ldloca.s V_1
IL_0014: ldstr ""2""
IL_0019: call ""bool CustomHandler.AppendLiteral(string)""
IL_001e: br.s IL_0021
IL_0020: ldc.i4.0
IL_0021: pop
IL_0022: ldloc.1
IL_0023: call ""string C.M(int, CustomHandler)""
IL_0028: call ""void System.Console.WriteLine(string)""
IL_002d: ret
}
");
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_MultipleArgs([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var executableCode = @"
int i = 10;
string s = ""arg"";
C.M(i, s, " + expression + @");
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
string expectedOutput = @"
i:10
s:arg
literal:literal
";
var verifier = base.CompileAndVerify((Compilation)comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() })
{
verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
}
static void validator(ModuleSymbol verifier)
{
var cParam = verifier.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
static void verifyIL(string extraConstructorArg, CompilationVerifier verifier)
{
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 44 (0x2c)
.maxstack 7
.locals init (string V_0, //s
int V_1,
string V_2,
CustomHandler V_3)
IL_0000: ldc.i4.s 10
IL_0002: ldstr ""arg""
IL_0007: stloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloc.0
IL_000b: stloc.2
IL_000c: ldloc.2
IL_000d: ldloca.s V_3
IL_000f: ldc.i4.7
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: ldloc.2
IL_0013: call ""CustomHandler..ctor(int, int, int, string)""
IL_0018: ldloca.s V_3
IL_001a: ldstr ""literal""
IL_001f: call ""bool CustomHandler.AppendLiteral(string)""
IL_0024: pop
IL_0025: ldloc.3
IL_0026: call ""void C.M(int, string, CustomHandler)""
IL_002b: ret
}
"
: @"
{
// Code size 52 (0x34)
.maxstack 7
.locals init (string V_0, //s
int V_1,
string V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.s 10
IL_0002: ldstr ""arg""
IL_0007: stloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloc.0
IL_000b: stloc.2
IL_000c: ldloc.2
IL_000d: ldc.i4.7
IL_000e: ldc.i4.0
IL_000f: ldloc.1
IL_0010: ldloc.2
IL_0011: ldloca.s V_4
IL_0013: newobj ""CustomHandler..ctor(int, int, int, string, out bool)""
IL_0018: stloc.3
IL_0019: ldloc.s V_4
IL_001b: brfalse.s IL_002b
IL_001d: ldloca.s V_3
IL_001f: ldstr ""literal""
IL_0024: call ""bool CustomHandler.AppendLiteral(string)""
IL_0029: br.s IL_002c
IL_002b: ldc.i4.0
IL_002c: pop
IL_002d: ldloc.3
IL_002e: call ""void C.M(int, string, CustomHandler)""
IL_0033: ret
}
");
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_RefKindsMatch([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 1;
string s = null;
object o;
C.M(i, ref s, out o, " + expression + @");
Console.WriteLine(s);
Console.WriteLine(o);
public class C
{
public static void M(in int i, ref string s, out object o, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"", ""o"")] CustomHandler c)
{
Console.WriteLine(s);
o = ""o in M"";
s = ""s in M"";
Console.Write(c.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, in int i, ref string s, out object o" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
o = null;
s = ""s in constructor"";
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
s in constructor
i:1
literal:literal
s in M
o in M
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 67 (0x43)
.maxstack 8
.locals init (int V_0, //i
string V_1, //s
object V_2, //o
int& V_3,
string& V_4,
object& V_5,
CustomHandler V_6)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: stloc.3
IL_0007: ldloc.3
IL_0008: ldloca.s V_1
IL_000a: stloc.s V_4
IL_000c: ldloc.s V_4
IL_000e: ldloca.s V_2
IL_0010: stloc.s V_5
IL_0012: ldloc.s V_5
IL_0014: ldc.i4.7
IL_0015: ldc.i4.0
IL_0016: ldloc.3
IL_0017: ldloc.s V_4
IL_0019: ldloc.s V_5
IL_001b: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object)""
IL_0020: stloc.s V_6
IL_0022: ldloca.s V_6
IL_0024: ldstr ""literal""
IL_0029: call ""bool CustomHandler.AppendLiteral(string)""
IL_002e: pop
IL_002f: ldloc.s V_6
IL_0031: call ""void C.M(in int, ref string, out object, CustomHandler)""
IL_0036: ldloc.1
IL_0037: call ""void System.Console.WriteLine(string)""
IL_003c: ldloc.2
IL_003d: call ""void System.Console.WriteLine(object)""
IL_0042: ret
}
"
: @"
{
// Code size 76 (0x4c)
.maxstack 9
.locals init (int V_0, //i
string V_1, //s
object V_2, //o
int& V_3,
string& V_4,
object& V_5,
CustomHandler V_6,
bool V_7)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: stloc.3
IL_0007: ldloc.3
IL_0008: ldloca.s V_1
IL_000a: stloc.s V_4
IL_000c: ldloc.s V_4
IL_000e: ldloca.s V_2
IL_0010: stloc.s V_5
IL_0012: ldloc.s V_5
IL_0014: ldc.i4.7
IL_0015: ldc.i4.0
IL_0016: ldloc.3
IL_0017: ldloc.s V_4
IL_0019: ldloc.s V_5
IL_001b: ldloca.s V_7
IL_001d: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object, out bool)""
IL_0022: stloc.s V_6
IL_0024: ldloc.s V_7
IL_0026: brfalse.s IL_0036
IL_0028: ldloca.s V_6
IL_002a: ldstr ""literal""
IL_002f: call ""bool CustomHandler.AppendLiteral(string)""
IL_0034: br.s IL_0037
IL_0036: ldc.i4.0
IL_0037: pop
IL_0038: ldloc.s V_6
IL_003a: call ""void C.M(in int, ref string, out object, CustomHandler)""
IL_003f: ldloc.1
IL_0040: call ""void System.Console.WriteLine(string)""
IL_0045: ldloc.2
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(3).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1, 2 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_ReorderedAttributePositions([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(GetInt(), GetString(), " + expression + @");
int GetInt()
{
Console.WriteLine(""GetInt"");
return 10;
}
string GetString()
{
Console.WriteLine(""GetString"");
return ""str"";
}
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""s:"" + s);
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
GetInt
GetString
s:str
i:10
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 45 (0x2d)
.maxstack 7
.locals init (string V_0,
int V_1,
CustomHandler V_2)
IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_1()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldloca.s V_2
IL_0010: ldc.i4.7
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: call ""CustomHandler..ctor(int, int, string, int)""
IL_0019: ldloca.s V_2
IL_001b: ldstr ""literal""
IL_0020: call ""bool CustomHandler.AppendLiteral(string)""
IL_0025: pop
IL_0026: ldloc.2
IL_0027: call ""void C.M(int, string, CustomHandler)""
IL_002c: ret
}
"
: @"
{
// Code size 52 (0x34)
.maxstack 7
.locals init (string V_0,
int V_1,
CustomHandler V_2,
bool V_3)
IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_1()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldc.i4.7
IL_000f: ldc.i4.0
IL_0010: ldloc.0
IL_0011: ldloc.1
IL_0012: ldloca.s V_3
IL_0014: newobj ""CustomHandler..ctor(int, int, string, int, out bool)""
IL_0019: stloc.2
IL_001a: ldloc.3
IL_001b: brfalse.s IL_002b
IL_001d: ldloca.s V_2
IL_001f: ldstr ""literal""
IL_0024: call ""bool CustomHandler.AppendLiteral(string)""
IL_0029: br.s IL_002c
IL_002b: ldc.i4.0
IL_002c: pop
IL_002d: ldloc.2
IL_002e: call ""void C.M(int, string, CustomHandler)""
IL_0033: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_ParametersReordered([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
GetC().M(s: GetString(), i: GetInt(), c: " + expression + @");
C GetC()
{
Console.WriteLine(""GetC"");
return new C { Field = 5 };
}
int GetInt()
{
Console.WriteLine(""GetInt"");
return 10;
}
string GetString()
{
Console.WriteLine(""GetString"");
return ""str"";
}
public class C
{
public int Field;
public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", """", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s, C c, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""s:"" + s);
_builder.AppendLine(""c.Field:"" + c.Field.ToString());
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
GetC
GetString
GetInt
s:str
c.Field:5
i:10
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 56 (0x38)
.maxstack 9
.locals init (string V_0,
C V_1,
int V_2,
string V_3,
CustomHandler V_4)
IL_0000: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_2()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.3
IL_000f: call ""int <Program>$.<<Main>$>g__GetInt|0_1()""
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldloc.3
IL_0017: ldloca.s V_4
IL_0019: ldc.i4.7
IL_001a: ldc.i4.0
IL_001b: ldloc.0
IL_001c: ldloc.1
IL_001d: ldloc.2
IL_001e: call ""CustomHandler..ctor(int, int, string, C, int)""
IL_0023: ldloca.s V_4
IL_0025: ldstr ""literal""
IL_002a: call ""bool CustomHandler.AppendLiteral(string)""
IL_002f: pop
IL_0030: ldloc.s V_4
IL_0032: callvirt ""void C.M(int, string, CustomHandler)""
IL_0037: ret
}
"
: @"
{
// Code size 65 (0x41)
.maxstack 9
.locals init (string V_0,
C V_1,
int V_2,
string V_3,
CustomHandler V_4,
bool V_5)
IL_0000: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_2()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.3
IL_000f: call ""int <Program>$.<<Main>$>g__GetInt|0_1()""
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldloc.3
IL_0017: ldc.i4.7
IL_0018: ldc.i4.0
IL_0019: ldloc.0
IL_001a: ldloc.1
IL_001b: ldloc.2
IL_001c: ldloca.s V_5
IL_001e: newobj ""CustomHandler..ctor(int, int, string, C, int, out bool)""
IL_0023: stloc.s V_4
IL_0025: ldloc.s V_5
IL_0027: brfalse.s IL_0037
IL_0029: ldloca.s V_4
IL_002b: ldstr ""literal""
IL_0030: call ""bool CustomHandler.AppendLiteral(string)""
IL_0035: br.s IL_0038
IL_0037: ldc.i4.0
IL_0038: pop
IL_0039: ldloc.s V_4
IL_003b: callvirt ""void C.M(int, string, CustomHandler)""
IL_0040: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 1, -1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_Duplicated([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(GetInt(), """", " + expression + @");
int GetInt()
{
Console.WriteLine(""GetInt"");
return 10;
}
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, int i2" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""i2:"" + i2.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
GetInt
i1:10
i2:10
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 43 (0x2b)
.maxstack 7
.locals init (int V_0,
CustomHandler V_1)
IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr """"
IL_000c: ldloca.s V_1
IL_000e: ldc.i4.7
IL_000f: ldc.i4.0
IL_0010: ldloc.0
IL_0011: ldloc.0
IL_0012: call ""CustomHandler..ctor(int, int, int, int)""
IL_0017: ldloca.s V_1
IL_0019: ldstr ""literal""
IL_001e: call ""bool CustomHandler.AppendLiteral(string)""
IL_0023: pop
IL_0024: ldloc.1
IL_0025: call ""void C.M(int, string, CustomHandler)""
IL_002a: ret
}
"
: @"
{
// Code size 50 (0x32)
.maxstack 7
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr """"
IL_000c: ldc.i4.7
IL_000d: ldc.i4.0
IL_000e: ldloc.0
IL_000f: ldloc.0
IL_0010: ldloca.s V_2
IL_0012: newobj ""CustomHandler..ctor(int, int, int, int, out bool)""
IL_0017: stloc.1
IL_0018: ldloc.2
IL_0019: brfalse.s IL_0029
IL_001b: ldloca.s V_1
IL_001d: ldstr ""literal""
IL_0022: call ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.1
IL_002c: call ""void C.M(int, string, CustomHandler)""
IL_0031: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_EmptyWithMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, """", " + expression + @");
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) => Console.WriteLine(c.ToString());
}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount" + extraConstructorArg + @")
{
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: "CustomHandler").VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 19 (0x13)
.maxstack 4
IL_0000: ldc.i4.1
IL_0001: ldstr """"
IL_0006: ldc.i4.0
IL_0007: ldc.i4.0
IL_0008: newobj ""CustomHandler..ctor(int, int)""
IL_000d: call ""void C.M(int, string, CustomHandler)""
IL_0012: ret
}
"
: @"
{
// Code size 21 (0x15)
.maxstack 5
.locals init (bool V_0)
IL_0000: ldc.i4.1
IL_0001: ldstr """"
IL_0006: ldc.i4.0
IL_0007: ldc.i4.0
IL_0008: ldloca.s V_0
IL_000a: newobj ""CustomHandler..ctor(int, int, out bool)""
IL_000f: call ""void C.M(int, string, CustomHandler)""
IL_0014: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_EmptyWithoutMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) { }
}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @")
{
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute });
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics();
CreateCompilation(@"C.M(1, """", " + expression + @");", new[] { comp.EmitToImageReference() }).VerifyDiagnostics(
(extraConstructorArg == "")
? new[]
{
// (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int)'
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 12),
// (1,12): error CS1615: Argument 3 may not be passed with the 'out' keyword
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "out").WithLocation(1, 12)
}
: new[]
{
// (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int, out bool)'
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12),
// (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, int, out bool)'
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12)
}
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_OnIndexerRvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
var c = new C();
Console.WriteLine(c[10, ""str"", " + expression + @"]);
public class C
{
public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { get => c.ToString(); }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i1:10
s:str
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 52 (0x34)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldloca.s V_2
IL_0012: ldc.i4.7
IL_0013: ldc.i4.0
IL_0014: ldloc.0
IL_0015: ldloc.1
IL_0016: call ""CustomHandler..ctor(int, int, int, string)""
IL_001b: ldloca.s V_2
IL_001d: ldstr ""literal""
IL_0022: call ""bool CustomHandler.AppendLiteral(string)""
IL_0027: pop
IL_0028: ldloc.2
IL_0029: callvirt ""string C.this[int, string, CustomHandler].get""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: ret
}
"
: @"
{
// Code size 59 (0x3b)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2,
bool V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldc.i4.7
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: callvirt ""string C.this[int, string, CustomHandler].get""
IL_0035: call ""void System.Console.WriteLine(string)""
IL_003a: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_OnIndexerLvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
var c = new C();
c[10, ""str"", " + expression + @"] = """";
public class C
{
public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { set => Console.WriteLine(c.ToString()); }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i1:10
s:str
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 52 (0x34)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldloca.s V_2
IL_0012: ldc.i4.7
IL_0013: ldc.i4.0
IL_0014: ldloc.0
IL_0015: ldloc.1
IL_0016: call ""CustomHandler..ctor(int, int, int, string)""
IL_001b: ldloca.s V_2
IL_001d: ldstr ""literal""
IL_0022: call ""bool CustomHandler.AppendLiteral(string)""
IL_0027: pop
IL_0028: ldloc.2
IL_0029: ldstr """"
IL_002e: callvirt ""void C.this[int, string, CustomHandler].set""
IL_0033: ret
}
"
: @"
{
// Code size 59 (0x3b)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2,
bool V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldc.i4.7
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: ldstr """"
IL_0035: callvirt ""void C.this[int, string, CustomHandler].set""
IL_003a: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_ThisParameter([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
(new C(5)).M((int)10, ""str"", " + expression + @");
public class C
{
public int Prop { get; }
public C(int i) => Prop = i;
public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", """", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, C c, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""c.Prop:"" + c.Prop.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i1:10
c.Prop:5
s:str
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 51 (0x33)
.maxstack 9
.locals init (int V_0,
C V_1,
string V_2,
CustomHandler V_3)
IL_0000: ldc.i4.5
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.s 10
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldstr ""str""
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: ldloca.s V_3
IL_0015: ldc.i4.7
IL_0016: ldc.i4.0
IL_0017: ldloc.0
IL_0018: ldloc.1
IL_0019: ldloc.2
IL_001a: call ""CustomHandler..ctor(int, int, int, C, string)""
IL_001f: ldloca.s V_3
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: pop
IL_002c: ldloc.3
IL_002d: callvirt ""void C.M(int, string, CustomHandler)""
IL_0032: ret
}
"
: @"
{
// Code size 59 (0x3b)
.maxstack 9
.locals init (int V_0,
C V_1,
string V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.5
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.s 10
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldstr ""str""
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: ldc.i4.7
IL_0014: ldc.i4.0
IL_0015: ldloc.0
IL_0016: ldloc.1
IL_0017: ldloc.2
IL_0018: ldloca.s V_4
IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, string, out bool)""
IL_001f: stloc.3
IL_0020: ldloc.s V_4
IL_0022: brfalse.s IL_0032
IL_0024: ldloca.s V_3
IL_0026: ldstr ""literal""
IL_002b: call ""bool CustomHandler.AppendLiteral(string)""
IL_0030: br.s IL_0033
IL_0032: ldc.i4.0
IL_0033: pop
IL_0034: ldloc.3
IL_0035: callvirt ""void C.M(int, string, CustomHandler)""
IL_003a: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, -1, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void InterpolatedStringHandlerArgumentAttribute_OnConstructor(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
_ = new C(5, " + expression + @");
public class C
{
public int Prop { get; }
public C(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")]CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
i:5
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 34 (0x22)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.5
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldloca.s V_1
IL_0005: ldc.i4.7
IL_0006: ldc.i4.0
IL_0007: ldloc.0
IL_0008: call ""CustomHandler..ctor(int, int, int)""
IL_000d: ldloca.s V_1
IL_000f: ldstr ""literal""
IL_0014: call ""bool CustomHandler.AppendLiteral(string)""
IL_0019: pop
IL_001a: ldloc.1
IL_001b: newobj ""C..ctor(int, CustomHandler)""
IL_0020: pop
IL_0021: ret
}
");
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_Success([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C c = new C(1);
GetC(ref c).M(" + expression + @");
Console.WriteLine(c.I);
ref C GetC(ref C c)
{
Console.WriteLine(""GetC"");
return ref c;
}
public class C
{
public int I;
public C(int i)
{
I = i;
}
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
c = new C(2);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @"
GetC
literal:literal
2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldind.ref
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)""
IL_0019: stloc.2
IL_001a: ldloca.s V_2
IL_001c: ldstr ""literal""
IL_0021: call ""bool CustomHandler.AppendLiteral(string)""
IL_0026: pop
IL_0027: ldloc.2
IL_0028: callvirt ""void C.M(CustomHandler)""
IL_002d: ldloc.0
IL_002e: ldfld ""int C.I""
IL_0033: call ""void System.Console.WriteLine(int)""
IL_0038: ret
}
"
: @"
{
// Code size 65 (0x41)
.maxstack 5
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2,
bool V_3)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldind.ref
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: callvirt ""void C.M(CustomHandler)""
IL_0035: ldloc.0
IL_0036: ldfld ""int C.I""
IL_003b: call ""void System.Console.WriteLine(int)""
IL_0040: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_Success_StructReceiver([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C c = new C(1);
GetC(ref c).M(" + expression + @");
Console.WriteLine(c.I);
ref C GetC(ref C c)
{
Console.WriteLine(""GetC"");
return ref c;
}
public struct C
{
public int I;
public C(int i)
{
I = i;
}
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
c = new C(2);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @"
GetC
literal:literal
2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""C..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)""
IL_0019: stloc.2
IL_001a: ldloca.s V_2
IL_001c: ldstr ""literal""
IL_0021: call ""bool CustomHandler.AppendLiteral(string)""
IL_0026: pop
IL_0027: ldloc.2
IL_0028: call ""void C.M(CustomHandler)""
IL_002d: ldloc.0
IL_002e: ldfld ""int C.I""
IL_0033: call ""void System.Console.WriteLine(int)""
IL_0038: ret
}
"
: @"
{
// Code size 65 (0x41)
.maxstack 5
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2,
bool V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""C..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: call ""void C.M(CustomHandler)""
IL_0035: ldloc.0
IL_0036: ldfld ""int C.I""
IL_003b: call ""void System.Console.WriteLine(int)""
IL_0040: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_MismatchedRefness_01([CombinatorialValues("ref readonly", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C c = new C(1);
GetC().M(" + expression + @");
" + refness + @" C GetC() => throw null;
public class C
{
public C(int i) { }
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref C c) : this(literalLength, formattedCount) { }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (5,10): error CS1620: Argument 3 must be passed with the 'ref' keyword
// GetC().M($"literal");
Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(5, 10)
);
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_MismatchedRefness_02([CombinatorialValues("in", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C c = new C(1);
GetC(ref c).M(" + expression + @");
ref C GetC(ref C c) => ref c;
public class C
{
public C(int i) { }
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount," + refness + @" C c) : this(literalLength, formattedCount) { }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (5,15): error CS1615: Argument 3 may not be passed with the 'ref' keyword
// GetC(ref c).M($"literal");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "ref").WithLocation(5, 15)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructReceiver_Rvalue(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s1 = new S { I = 1 };
S s2 = new S { I = 2 };
s1.M(s2, " + expression + @");
public struct S
{
public int I;
public void M(S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler)
{
Console.WriteLine(""s1.I:"" + this.I.ToString());
Console.WriteLine(""s2.I:"" + s2.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, S s1, S s2) : this(literalLength, formattedCount)
{
s1.I = 3;
s2.I = 4;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
s1.I:1
s2.I:2");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 56 (0x38)
.maxstack 6
.locals init (S V_0, //s2
S V_1,
S V_2)
IL_0000: ldloca.s V_1
IL_0002: initobj ""S""
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.I""
IL_0010: ldloc.1
IL_0011: ldloca.s V_1
IL_0013: initobj ""S""
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.2
IL_001c: stfld ""int S.I""
IL_0021: ldloc.1
IL_0022: stloc.0
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: ldloc.0
IL_0027: stloc.2
IL_0028: ldloc.2
IL_0029: ldc.i4.0
IL_002a: ldc.i4.0
IL_002b: ldloc.1
IL_002c: ldloc.2
IL_002d: newobj ""CustomHandler..ctor(int, int, S, S)""
IL_0032: call ""void S.M(S, CustomHandler)""
IL_0037: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructReceiver_Lvalue(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s1 = new S { I = 1 };
S s2 = new S { I = 2 };
s1.M(ref s2, " + expression + @");
public struct S
{
public int I;
public void M(ref S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler)
{
Console.WriteLine(""s1.I:"" + this.I.ToString());
Console.WriteLine(""s2.I:"" + s2.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref S s1, ref S s2) : this(literalLength, formattedCount)
{
s1.I = 3;
s2.I = 4;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (8,14): error CS1620: Argument 3 must be passed with the 'ref' keyword
// s1.M(ref s2, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(8, 14)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructParameter_ByVal(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s = new S { I = 1 };
S.M(s, " + expression + @");
public struct S
{
public int I;
public static void M(S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler)
{
Console.WriteLine(""s.I:"" + s.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, S s) : this(literalLength, formattedCount)
{
s.I = 2;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 33 (0x21)
.maxstack 4
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.I""
IL_0010: ldloc.0
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: ldc.i4.0
IL_0014: ldc.i4.0
IL_0015: ldloc.0
IL_0016: newobj ""CustomHandler..ctor(int, int, S)""
IL_001b: call ""void S.M(S, CustomHandler)""
IL_0020: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructParameter_ByRef(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s = new S { I = 1 };
S.M(ref s, " + expression + @");
public struct S
{
public int I;
public static void M(ref S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler)
{
Console.WriteLine(""s.I:"" + s.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref S s) : this(literalLength, formattedCount)
{
s.I = 2;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:2");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init (S V_0, //s
S V_1,
S& V_2)
IL_0000: ldloca.s V_1
IL_0002: initobj ""S""
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.I""
IL_0010: ldloc.1
IL_0011: stloc.0
IL_0012: ldloca.s V_0
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldc.i4.0
IL_0017: ldc.i4.0
IL_0018: ldloc.2
IL_0019: newobj ""CustomHandler..ctor(int, int, ref S)""
IL_001e: call ""void S.M(ref S, CustomHandler)""
IL_0023: ret
}
");
}
[Theory]
[CombinatorialData]
public void SideEffects(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal""", @"$"""" + $""literal""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
GetReceiver().M(
GetArg(""Unrelated parameter 1""),
GetArg(""Second value""),
GetArg(""Unrelated parameter 2""),
GetArg(""First value""),
" + expression + @",
GetArg(""Unrelated parameter 4""));
C GetReceiver()
{
Console.WriteLine(""GetReceiver"");
return new C() { Prop = ""Prop"" };
}
string GetArg(string s)
{
Console.WriteLine(s);
return s;
}
public class C
{
public string Prop { get; set; }
public void M(string param1, string param2, string param3, string param4, [InterpolatedStringHandlerArgument(""param4"", """", ""param2"")] CustomHandler c, string param6)
=> Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s1, C c, string s2" + (validityParameter ? ", out bool success" : "") + @")
: this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""s1:"" + s1);
_builder.AppendLine(""c.Prop:"" + c.Prop);
_builder.AppendLine(""s2:"" + s2);
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns);
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: @"
GetReceiver
Unrelated parameter 1
Second value
Unrelated parameter 2
First value
Handler constructor
Unrelated parameter 4
s1:First value
c.Prop:Prop
s2:Second value
literal:literal
");
verifier.VerifyDiagnostics();
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$""literal"" + $""""")]
public void InterpolatedStringHandlerArgumentsAttribute_ConversionFromArgumentType(string expression)
{
var code = @"
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
int i = 1;
C.M(i, " + expression + @");
public class C
{
public static implicit operator C(int i) => throw null;
public static implicit operator C(double d)
{
Console.WriteLine(d.ToString(""G"", CultureInfo.InvariantCulture));
return new C();
}
public override string ToString() => ""C"";
public static void M(double d, [InterpolatedStringHandlerArgument(""d"")] CustomHandler handler) => Console.WriteLine(handler.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
1
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 39 (0x27)
.maxstack 5
.locals init (double V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: conv.r8
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldloca.s V_1
IL_0006: ldc.i4.7
IL_0007: ldc.i4.0
IL_0008: ldloc.0
IL_0009: call ""C C.op_Implicit(double)""
IL_000e: call ""CustomHandler..ctor(int, int, C)""
IL_0013: ldloca.s V_1
IL_0015: ldstr ""literal""
IL_001a: call ""bool CustomHandler.AppendLiteral(string)""
IL_001f: pop
IL_0020: ldloc.1
IL_0021: call ""void C.M(double, CustomHandler)""
IL_0026: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_01(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 3;
GetC()[GetInt(1), " + expression + @"] += GetInt(2);
static C GetC()
{
Console.WriteLine(""GetC"");
return new C() { Prop = 2 };
}
static int GetInt(int i)
{
Console.WriteLine(""GetInt"" + i.ToString());
return 1;
}
public class C
{
public int Prop { get; set; }
public int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c]
{
get
{
Console.WriteLine(""Indexer getter"");
return 0;
}
set
{
Console.WriteLine(""Indexer setter"");
Console.WriteLine(c.ToString());
}
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""arg1:"" + arg1);
_builder.AppendLine(""C.Prop:"" + c.Prop.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
GetC
GetInt1
Handler constructor
Indexer getter
GetInt2
Indexer setter
arg1:1
C.Prop:2
literal:literal
value:3
alignment:0
format:
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 85 (0x55)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldloca.s V_5
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_5
IL_001e: ldstr ""literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_5
IL_002a: ldloc.0
IL_002b: box ""int""
IL_0030: ldc.i4.0
IL_0031: ldnull
IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0037: ldloc.s V_5
IL_0039: stloc.s V_4
IL_003b: ldloc.2
IL_003c: ldloc.3
IL_003d: ldloc.s V_4
IL_003f: ldloc.2
IL_0040: ldloc.3
IL_0041: ldloc.s V_4
IL_0043: callvirt ""int C.this[int, CustomHandler].get""
IL_0048: ldc.i4.2
IL_0049: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_004e: add
IL_004f: callvirt ""void C.this[int, CustomHandler].set""
IL_0054: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 96 (0x60)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5,
bool V_6)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_6
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.s V_5
IL_001e: ldloc.s V_6
IL_0020: brfalse.s IL_0040
IL_0022: ldloca.s V_5
IL_0024: ldstr ""literal""
IL_0029: call ""void CustomHandler.AppendLiteral(string)""
IL_002e: ldloca.s V_5
IL_0030: ldloc.0
IL_0031: box ""int""
IL_0036: ldc.i4.0
IL_0037: ldnull
IL_0038: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003d: ldc.i4.1
IL_003e: br.s IL_0041
IL_0040: ldc.i4.0
IL_0041: pop
IL_0042: ldloc.s V_5
IL_0044: stloc.s V_4
IL_0046: ldloc.2
IL_0047: ldloc.3
IL_0048: ldloc.s V_4
IL_004a: ldloc.2
IL_004b: ldloc.3
IL_004c: ldloc.s V_4
IL_004e: callvirt ""int C.this[int, CustomHandler].get""
IL_0053: ldc.i4.2
IL_0054: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_0059: add
IL_005a: callvirt ""void C.this[int, CustomHandler].set""
IL_005f: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 91 (0x5b)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldloca.s V_5
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_5
IL_001e: ldstr ""literal""
IL_0023: call ""bool CustomHandler.AppendLiteral(string)""
IL_0028: brfalse.s IL_003b
IL_002a: ldloca.s V_5
IL_002c: ldloc.0
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.s V_5
IL_003f: stloc.s V_4
IL_0041: ldloc.2
IL_0042: ldloc.3
IL_0043: ldloc.s V_4
IL_0045: ldloc.2
IL_0046: ldloc.3
IL_0047: ldloc.s V_4
IL_0049: callvirt ""int C.this[int, CustomHandler].get""
IL_004e: ldc.i4.2
IL_004f: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_0054: add
IL_0055: callvirt ""void C.this[int, CustomHandler].set""
IL_005a: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 97 (0x61)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5,
bool V_6)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_6
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.s V_5
IL_001e: ldloc.s V_6
IL_0020: brfalse.s IL_0041
IL_0022: ldloca.s V_5
IL_0024: ldstr ""literal""
IL_0029: call ""bool CustomHandler.AppendLiteral(string)""
IL_002e: brfalse.s IL_0041
IL_0030: ldloca.s V_5
IL_0032: ldloc.0
IL_0033: box ""int""
IL_0038: ldc.i4.0
IL_0039: ldnull
IL_003a: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_003f: br.s IL_0042
IL_0041: ldc.i4.0
IL_0042: pop
IL_0043: ldloc.s V_5
IL_0045: stloc.s V_4
IL_0047: ldloc.2
IL_0048: ldloc.3
IL_0049: ldloc.s V_4
IL_004b: ldloc.2
IL_004c: ldloc.3
IL_004d: ldloc.s V_4
IL_004f: callvirt ""int C.this[int, CustomHandler].get""
IL_0054: ldc.i4.2
IL_0055: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_005a: add
IL_005b: callvirt ""void C.this[int, CustomHandler].set""
IL_0060: ret
}
",
};
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_02(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 3;
GetC()[GetInt(1), " + expression + @"] += GetInt(2);
static C GetC()
{
Console.WriteLine(""GetC"");
return new C() { Prop = 2 };
}
static int GetInt(int i)
{
Console.WriteLine(""GetInt"" + i.ToString());
return 1;
}
public class C
{
private int field;
public int Prop { get; set; }
public ref int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c]
{
get
{
Console.WriteLine(""Indexer getter"");
Console.WriteLine(c.ToString());
return ref field;
}
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""arg1:"" + arg1);
_builder.AppendLine(""C.Prop:"" + c.Prop.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
GetC
GetInt1
Handler constructor
Indexer getter
arg1:1
C.Prop:2
literal:literal
value:3
alignment:0
format:
GetInt2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 72 (0x48)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_3
IL_002a: ldloc.0
IL_002b: box ""int""
IL_0030: ldc.i4.0
IL_0031: ldnull
IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0037: ldloc.3
IL_0038: callvirt ""ref int C.this[int, CustomHandler].get""
IL_003d: dup
IL_003e: ldind.i4
IL_003f: ldc.i4.2
IL_0040: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_0045: add
IL_0046: stind.i4
IL_0047: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 82 (0x52)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_003f
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""void CustomHandler.AppendLiteral(string)""
IL_002d: ldloca.s V_3
IL_002f: ldloc.0
IL_0030: box ""int""
IL_0035: ldc.i4.0
IL_0036: ldnull
IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003c: ldc.i4.1
IL_003d: br.s IL_0040
IL_003f: ldc.i4.0
IL_0040: pop
IL_0041: ldloc.3
IL_0042: callvirt ""ref int C.this[int, CustomHandler].get""
IL_0047: dup
IL_0048: ldind.i4
IL_0049: ldc.i4.2
IL_004a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_004f: add
IL_0050: stind.i4
IL_0051: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 78 (0x4e)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""bool CustomHandler.AppendLiteral(string)""
IL_0028: brfalse.s IL_003b
IL_002a: ldloca.s V_3
IL_002c: ldloc.0
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.3
IL_003e: callvirt ""ref int C.this[int, CustomHandler].get""
IL_0043: dup
IL_0044: ldind.i4
IL_0045: ldc.i4.2
IL_0046: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_004b: add
IL_004c: stind.i4
IL_004d: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 83 (0x53)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_0040
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""bool CustomHandler.AppendLiteral(string)""
IL_002d: brfalse.s IL_0040
IL_002f: ldloca.s V_3
IL_0031: ldloc.0
IL_0032: box ""int""
IL_0037: ldc.i4.0
IL_0038: ldnull
IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_003e: br.s IL_0041
IL_0040: ldc.i4.0
IL_0041: pop
IL_0042: ldloc.3
IL_0043: callvirt ""ref int C.this[int, CustomHandler].get""
IL_0048: dup
IL_0049: ldind.i4
IL_004a: ldc.i4.2
IL_004b: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_0050: add
IL_0051: stind.i4
IL_0052: ret
}
",
};
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_RefReturningMethod(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 3;
GetC().M(GetInt(1), " + expression + @") += GetInt(2);
static C GetC()
{
Console.WriteLine(""GetC"");
return new C() { Prop = 2 };
}
static int GetInt(int i)
{
Console.WriteLine(""GetInt"" + i.ToString());
return 1;
}
public class C
{
private int field;
public int Prop { get; set; }
public ref int M(int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c)
{
Console.WriteLine(""M"");
Console.WriteLine(c.ToString());
return ref field;
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""arg1:"" + arg1);
_builder.AppendLine(""C.Prop:"" + c.Prop.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
GetC
GetInt1
Handler constructor
M
arg1:1
C.Prop:2
literal:literal
value:3
alignment:0
format:
GetInt2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 72 (0x48)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_3
IL_002a: ldloc.0
IL_002b: box ""int""
IL_0030: ldc.i4.0
IL_0031: ldnull
IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0037: ldloc.3
IL_0038: callvirt ""ref int C.M(int, CustomHandler)""
IL_003d: dup
IL_003e: ldind.i4
IL_003f: ldc.i4.2
IL_0040: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_0045: add
IL_0046: stind.i4
IL_0047: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 82 (0x52)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_003f
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""void CustomHandler.AppendLiteral(string)""
IL_002d: ldloca.s V_3
IL_002f: ldloc.0
IL_0030: box ""int""
IL_0035: ldc.i4.0
IL_0036: ldnull
IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003c: ldc.i4.1
IL_003d: br.s IL_0040
IL_003f: ldc.i4.0
IL_0040: pop
IL_0041: ldloc.3
IL_0042: callvirt ""ref int C.M(int, CustomHandler)""
IL_0047: dup
IL_0048: ldind.i4
IL_0049: ldc.i4.2
IL_004a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_004f: add
IL_0050: stind.i4
IL_0051: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 78 (0x4e)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""bool CustomHandler.AppendLiteral(string)""
IL_0028: brfalse.s IL_003b
IL_002a: ldloca.s V_3
IL_002c: ldloc.0
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.3
IL_003e: callvirt ""ref int C.M(int, CustomHandler)""
IL_0043: dup
IL_0044: ldind.i4
IL_0045: ldc.i4.2
IL_0046: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_004b: add
IL_004c: stind.i4
IL_004d: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 83 (0x53)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_0040
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""bool CustomHandler.AppendLiteral(string)""
IL_002d: brfalse.s IL_0040
IL_002f: ldloca.s V_3
IL_0031: ldloc.0
IL_0032: box ""int""
IL_0037: ldc.i4.0
IL_0038: ldnull
IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_003e: br.s IL_0041
IL_0040: ldc.i4.0
IL_0041: pop
IL_0042: ldloc.3
IL_0043: callvirt ""ref int C.M(int, CustomHandler)""
IL_0048: dup
IL_0049: ldind.i4
IL_004a: ldc.i4.2
IL_004b: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_0050: add
IL_0051: stind.i4
IL_0052: ret
}
",
};
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void InterpolatedStringHandlerArgumentsAttribute_CollectionInitializerAdd(string expression)
{
var code = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
_ = new C(1) { " + expression + @" };
public class C : IEnumerable<int>
{
public int Field;
public C(int i)
{
Field = i;
}
public void Add([InterpolatedStringHandlerArgument("""")] CustomHandler c)
{
Console.WriteLine(c.ToString());
}
public IEnumerator<int> GetEnumerator() => throw null;
IEnumerator IEnumerable.GetEnumerator() => throw null;
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount)
{
_builder.AppendLine(""c.Field:"" + c.Field.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
c.Field:1
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 37 (0x25)
.maxstack 5
.locals init (C V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.7
IL_000b: ldc.i4.0
IL_000c: ldloc.0
IL_000d: call ""CustomHandler..ctor(int, int, C)""
IL_0012: ldloca.s V_1
IL_0014: ldstr ""literal""
IL_0019: call ""void CustomHandler.AppendLiteral(string)""
IL_001e: ldloc.1
IL_001f: callvirt ""void C.Add(CustomHandler)""
IL_0024: ret
}
");
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_AttributeOnAppendFormatCall(bool useBoolReturns, bool validityParameter,
[CombinatorialValues(@"$""{$""Inner string""}{2}""", @"$""{$""Inner string""}"" + $""{2}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler handler)
{
Console.WriteLine(handler.ToString());
}
}
public partial class CustomHandler
{
private int I = 0;
public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""int constructor"");
I = i;
" + (validityParameter ? "success = true;" : "") + @"
}
public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""CustomHandler constructor"");
_builder.AppendLine(""c.I:"" + c.I.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted([InterpolatedStringHandlerArgument("""")]CustomHandler c)
{
_builder.AppendLine(""CustomHandler AppendFormatted"");
_builder.Append(c.ToString());
" + (useBoolReturns ? "return true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
int constructor
CustomHandler constructor
CustomHandler AppendFormatted
c.I:1
literal:Inner string
value:2
alignment:0
format:
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 59 (0x3b)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: dup
IL_000c: stloc.1
IL_000d: ldloc.1
IL_000e: ldc.i4.s 12
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0017: dup
IL_0018: ldstr ""Inner string""
IL_001d: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0022: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)""
IL_0027: dup
IL_0028: ldc.i4.2
IL_0029: box ""int""
IL_002e: ldc.i4.0
IL_002f: ldnull
IL_0030: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: call ""void C.M(int, CustomHandler)""
IL_003a: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 87 (0x57)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2,
CustomHandler V_3,
CustomHandler V_4,
bool V_5)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.2
IL_000f: brfalse.s IL_004e
IL_0011: ldloc.1
IL_0012: stloc.3
IL_0013: ldloc.3
IL_0014: ldc.i4.s 12
IL_0016: ldc.i4.0
IL_0017: ldloc.3
IL_0018: ldloca.s V_5
IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_001f: stloc.s V_4
IL_0021: ldloc.s V_5
IL_0023: brfalse.s IL_0034
IL_0025: ldloc.s V_4
IL_0027: ldstr ""Inner string""
IL_002c: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0031: ldc.i4.1
IL_0032: br.s IL_0035
IL_0034: ldc.i4.0
IL_0035: pop
IL_0036: ldloc.s V_4
IL_0038: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)""
IL_003d: ldloc.1
IL_003e: ldc.i4.2
IL_003f: box ""int""
IL_0044: ldc.i4.0
IL_0045: ldnull
IL_0046: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_004b: ldc.i4.1
IL_004c: br.s IL_004f
IL_004e: ldc.i4.0
IL_004f: pop
IL_0050: ldloc.1
IL_0051: call ""void C.M(int, CustomHandler)""
IL_0056: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 68 (0x44)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1,
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: stloc.2
IL_000e: ldloc.2
IL_000f: ldc.i4.s 12
IL_0011: ldc.i4.0
IL_0012: ldloc.2
IL_0013: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0018: dup
IL_0019: ldstr ""Inner string""
IL_001e: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0023: pop
IL_0024: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)""
IL_0029: brfalse.s IL_003b
IL_002b: ldloc.1
IL_002c: ldc.i4.2
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.1
IL_003e: call ""void C.M(int, CustomHandler)""
IL_0043: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 87 (0x57)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2,
CustomHandler V_3,
CustomHandler V_4,
bool V_5)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.2
IL_000f: brfalse.s IL_004e
IL_0011: ldloc.1
IL_0012: stloc.3
IL_0013: ldloc.3
IL_0014: ldc.i4.s 12
IL_0016: ldc.i4.0
IL_0017: ldloc.3
IL_0018: ldloca.s V_5
IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_001f: stloc.s V_4
IL_0021: ldloc.s V_5
IL_0023: brfalse.s IL_0033
IL_0025: ldloc.s V_4
IL_0027: ldstr ""Inner string""
IL_002c: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0031: br.s IL_0034
IL_0033: ldc.i4.0
IL_0034: pop
IL_0035: ldloc.s V_4
IL_0037: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)""
IL_003c: brfalse.s IL_004e
IL_003e: ldloc.1
IL_003f: ldc.i4.2
IL_0040: box ""int""
IL_0045: ldc.i4.0
IL_0046: ldnull
IL_0047: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_004c: br.s IL_004f
IL_004e: ldc.i4.0
IL_004f: pop
IL_0050: ldloc.1
IL_0051: call ""void C.M(int, CustomHandler)""
IL_0056: ret
}
",
};
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void DiscardsUsedAsParameters(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(out _, " + expression + @");
public class C
{
public static void M(out int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c)
{
i = 0;
Console.WriteLine(c.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, out int i) : this(literalLength, formattedCount)
{
i = 1;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"literal:literal");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 31 (0x1f)
.maxstack 4
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.0
IL_0004: ldloca.s V_0
IL_0006: newobj ""CustomHandler..ctor(int, int, out int)""
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: ldstr ""literal""
IL_0013: call ""void CustomHandler.AppendLiteral(string)""
IL_0018: ldloc.1
IL_0019: call ""void C.M(out int, CustomHandler)""
IL_001e: ret
}
");
}
[Fact]
public void DiscardsUsedAsParameters_DefinedInVB()
{
var vb = @"
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
Public Shared Sub M(<Out> ByRef i As Integer, <InterpolatedStringHandlerArgument(""i"")>c As CustomHandler)
Console.WriteLine(i)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
Public Sub New(literalLength As Integer, formattedCount As Integer, <Out> ByRef i As Integer)
i = 1
End Sub
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vb, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var code = @"C.M(out _, $"""");";
var comp = CreateCompilation(code, new[] { vbComp.EmitToImageReference() });
var verifier = CompileAndVerify(comp, expectedOutput: @"1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 17 (0x11)
.maxstack 4
.locals init (int V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: ldloca.s V_0
IL_0006: newobj ""CustomHandler..ctor(int, int, out int)""
IL_000b: call ""void C.M(out int, CustomHandler)""
IL_0010: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DisallowedInExpressionTrees(string expression)
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<CustomHandler>> expr = () => " + expression + @";
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, handler });
comp.VerifyDiagnostics(
// (5,46): error CS8952: An expression tree may not contain an interpolated string handler conversion.
// Expression<Func<CustomHandler>> expr = () => $"";
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, expression).WithLocation(5, 46)
);
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_01()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<string, string>> e = o => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 127 (0x7f)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: pop
IL_007e: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_02()
{
var code = @"
using System.Linq.Expressions;
Expression e = (string o) => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 127 (0x7f)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: pop
IL_007e: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_03()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<Func<string, string>>> e = () => o => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 137 (0x89)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()""
IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_0087: pop
IL_0088: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_04()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression e = Func<string, string> () => (string o) => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 137 (0x89)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()""
IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_0087: pop
IL_0088: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_05()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<string, string>> e = o => $""{o.Length}"" + $""literal"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 167 (0xa7)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldstr ""literal""
IL_0073: ldtoken ""string""
IL_0078: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_007d: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0082: ldtoken ""string string.Concat(string, string)""
IL_0087: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_008c: castclass ""System.Reflection.MethodInfo""
IL_0091: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0096: ldc.i4.1
IL_0097: newarr ""System.Linq.Expressions.ParameterExpression""
IL_009c: dup
IL_009d: ldc.i4.0
IL_009e: ldloc.0
IL_009f: stelem.ref
IL_00a0: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_00a5: pop
IL_00a6: ret
}
");
}
[Theory]
[CombinatorialData]
public void CustomHandlerUsedAsArgumentToCustomHandler(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, " + expression + @", " + expression + @");
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c1, [InterpolatedStringHandlerArgument(""c1"")] CustomHandler c2) => Console.WriteLine(c2.ToString());
}
public partial class CustomHandler
{
private int i;
public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
this.i = i;
" + (validityParameter ? "success = true;" : "") + @"
}
public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""c.i:"" + c.i.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: "c.i:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 27 (0x1b)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.0
IL_000e: ldc.i4.0
IL_000f: ldloc.1
IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001a: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 31 (0x1f)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: ldc.i4.0
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: ldloca.s V_2
IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001e: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 27 (0x1b)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.0
IL_000e: ldc.i4.0
IL_000f: ldloc.1
IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001a: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 31 (0x1f)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: ldc.i4.0
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: ldloca.s V_2
IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001e: ret
}
",
};
}
[Theory]
[CombinatorialData]
public void DefiniteAssignment_01(bool useBoolReturns, bool trailingOutParameter,
[CombinatorialValues(@"$""{i = 1}{M(out var o)}{s = o.ToString()}""", @"$""{i = 1}"" + $""{M(out var o)}"" + $""{s = o.ToString()}""")] string expression)
{
var code = @"
int i;
string s;
CustomHandler c = " + expression + @";
_ = i.ToString();
_ = o.ToString();
_ = s.ToString();
string M(out object o)
{
o = null;
return null;
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter);
var comp = CreateCompilation(new[] { code, customHandler });
if (trailingOutParameter)
{
comp.VerifyDiagnostics(
// (6,5): error CS0165: Use of unassigned local variable 'i'
// _ = i.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 5),
// (7,5): error CS0165: Use of unassigned local variable 'o'
// _ = o.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5),
// (8,5): error CS0165: Use of unassigned local variable 's'
// _ = s.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5)
);
}
else if (useBoolReturns)
{
comp.VerifyDiagnostics(
// (7,5): error CS0165: Use of unassigned local variable 'o'
// _ = o.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5),
// (8,5): error CS0165: Use of unassigned local variable 's'
// _ = s.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5)
);
}
else
{
comp.VerifyDiagnostics();
}
}
[Theory]
[CombinatorialData]
public void DefiniteAssignment_02(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}""", @"$"""" + $""{i = 1}""", @"$""{i = 1}"" + $""""")] string expression)
{
var code = @"
int i;
CustomHandler c = " + expression + @";
_ = i.ToString();
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter);
var comp = CreateCompilation(new[] { code, customHandler });
if (trailingOutParameter)
{
comp.VerifyDiagnostics(
// (5,5): error CS0165: Use of unassigned local variable 'i'
// _ = i.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(5, 5)
);
}
else
{
comp.VerifyDiagnostics();
}
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_01(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
dynamic d = 1;
M(d, " + expression + @");
void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute });
comp.VerifyDiagnostics(
// (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'.
// M(d, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_02(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
int i = 1;
M(i, " + expression + @");
void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute });
comp.VerifyDiagnostics(
// (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'.
// M(d, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_03(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 1;
M(i, " + expression + @");
void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) {}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, dynamic d) : this(literalLength, formattedCount)
{
Console.WriteLine(""d:"" + d.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false, includeOneTimeHelpers: false);
var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "d:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 22 (0x16)
.maxstack 4
.locals init (int V_0)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: box ""int""
IL_000b: newobj ""CustomHandler..ctor(int, int, dynamic)""
IL_0010: call ""void <Program>$.<<Main>$>g__M|0_0(int, CustomHandler)""
IL_0015: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_04(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(dynamic literalLength, int formattedCount)
{
Console.WriteLine(""ctor"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "ctor");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: box ""int""
IL_0006: ldc.i4.0
IL_0007: newobj ""CustomHandler..ctor(dynamic, int)""
IL_000c: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_0011: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_05(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
Console.WriteLine(""ctor"");
}
public CustomHandler(dynamic literalLength, int formattedCount)
{
throw null;
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "ctor");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_000c: ret
}
");
}
[Theory]
[InlineData(@"$""Literal""")]
[InlineData(@"$"""" + $""Literal""")]
public void DynamicConstruction_06(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public void AppendLiteral(dynamic d)
{
Console.WriteLine(""AppendLiteral"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "AppendLiteral");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 28 (0x1c)
.maxstack 3
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.0
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldstr ""Literal""
IL_0010: call ""void CustomHandler.AppendLiteral(dynamic)""
IL_0015: ldloc.0
IL_0016: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_001b: ret
}
");
}
[Theory]
[InlineData(@"$""{1}""")]
[InlineData(@"$""{1}"" + $""""")]
public void DynamicConstruction_07(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public void AppendFormatted(dynamic d)
{
Console.WriteLine(""AppendFormatted"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "AppendFormatted");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: call ""void CustomHandler.AppendFormatted(dynamic)""
IL_0016: ldloc.0
IL_0017: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_001c: ret
}
");
}
[Theory]
[InlineData(@"$""literal{d}""")]
[InlineData(@"$""literal"" + $""{d}""")]
public void DynamicConstruction_08(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
dynamic d = 1;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public void AppendLiteral(dynamic d)
{
Console.WriteLine(""AppendLiteral"");
}
public void AppendFormatted(dynamic d)
{
Console.WriteLine(""AppendFormatted"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
AppendLiteral
AppendFormatted");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 128 (0x80)
.maxstack 9
.locals init (object V_0, //d
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldloca.s V_1
IL_0009: ldc.i4.7
IL_000a: ldc.i4.1
IL_000b: call ""CustomHandler..ctor(int, int)""
IL_0010: ldloca.s V_1
IL_0012: ldstr ""literal""
IL_0017: call ""void CustomHandler.AppendLiteral(dynamic)""
IL_001c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0""
IL_0021: brtrue.s IL_0062
IL_0023: ldc.i4 0x100
IL_0028: ldstr ""AppendFormatted""
IL_002d: ldnull
IL_002e: ldtoken ""<Program>$""
IL_0033: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0038: ldc.i4.2
IL_0039: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_003e: dup
IL_003f: ldc.i4.0
IL_0040: ldc.i4.s 9
IL_0042: ldnull
IL_0043: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0048: stelem.ref
IL_0049: dup
IL_004a: ldc.i4.1
IL_004b: ldc.i4.0
IL_004c: ldnull
IL_004d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0052: stelem.ref
IL_0053: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0058: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_005d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0""
IL_0062: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0""
IL_0067: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Target""
IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0""
IL_0071: ldloca.s V_1
IL_0073: ldloc.0
IL_0074: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)""
IL_0079: ldloc.1
IL_007a: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_007f: ret
}
");
}
[Theory]
[InlineData(@"$""literal{d}""")]
[InlineData(@"$""literal"" + $""{d}""")]
public void DynamicConstruction_09(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
dynamic d = 1;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public bool AppendLiteral(dynamic d)
{
Console.WriteLine(""AppendLiteral"");
return true;
}
public bool AppendFormatted(dynamic d)
{
Console.WriteLine(""AppendFormatted"");
return true;
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
AppendLiteral
AppendFormatted");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 196 (0xc4)
.maxstack 11
.locals init (object V_0, //d
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldloca.s V_1
IL_0009: ldc.i4.7
IL_000a: ldc.i4.1
IL_000b: call ""CustomHandler..ctor(int, int)""
IL_0010: ldloca.s V_1
IL_0012: ldstr ""literal""
IL_0017: call ""bool CustomHandler.AppendLiteral(dynamic)""
IL_001c: brfalse IL_00bb
IL_0021: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1""
IL_0026: brtrue.s IL_004c
IL_0028: ldc.i4.0
IL_0029: ldtoken ""bool""
IL_002e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0033: ldtoken ""<Program>$""
IL_0038: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_0042: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0047: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1""
IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1""
IL_0051: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target""
IL_0056: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1""
IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0""
IL_0060: brtrue.s IL_009d
IL_0062: ldc.i4.0
IL_0063: ldstr ""AppendFormatted""
IL_0068: ldnull
IL_0069: ldtoken ""<Program>$""
IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0073: ldc.i4.2
IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0079: dup
IL_007a: ldc.i4.0
IL_007b: ldc.i4.s 9
IL_007d: ldnull
IL_007e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0083: stelem.ref
IL_0084: dup
IL_0085: ldc.i4.1
IL_0086: ldc.i4.0
IL_0087: ldnull
IL_0088: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_008d: stelem.ref
IL_008e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0093: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0""
IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0""
IL_00a2: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Target""
IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0""
IL_00ac: ldloca.s V_1
IL_00ae: ldloc.0
IL_00af: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)""
IL_00b4: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_00b9: br.s IL_00bc
IL_00bb: ldc.i4.0
IL_00bc: pop
IL_00bd: ldloc.1
IL_00be: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_00c3: ret
}
");
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_01(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount) : this() {}
public void AppendFormatted(Span<char> s) => this.s = s;
public static CustomHandler M()
{
Span<char> s = stackalloc char[10];
return " + expression + @";
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,19): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope
// return $"{s}";
Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 19)
);
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_02(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount) : this() {}
public void AppendFormatted(Span<char> s) => this.s = s;
public static ref CustomHandler M()
{
Span<char> s = stackalloc char[10];
return " + expression + @";
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,9): error CS8150: By-value returns may only be used in methods that return by value
// return $"{s}";
Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(17, 9)
);
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_03(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount) : this() {}
public void AppendFormatted(Span<char> s) => this.s = s;
public static ref CustomHandler M()
{
Span<char> s = stackalloc char[10];
return ref " + expression + @";
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// return ref $"{s}";
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, expression).WithLocation(17, 20)
);
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_04(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
S1 s1;
public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { this.s1 = s1; }
public void AppendFormatted(Span<char> s) => this.s1.s = s;
public static void M(ref S1 s1)
{
Span<char> s = stackalloc char[10];
M2(ref s1, " + expression + @");
}
public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] ref CustomHandler handler) {}
}
public ref struct S1
{
public Span<char> s;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, ref CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope
// M2(ref s1, $"{s}");
Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, " + expression + @")").WithArguments("CustomHandler.M2(ref S1, ref CustomHandler)", "handler").WithLocation(17, 9),
// (17,23): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope
// M2(ref s1, $"{s}");
Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 23)
);
}
[Theory]
[InlineData(@"$""{s1}""")]
[InlineData(@"$""{s1}"" + $""""")]
public void RefEscape_05(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; }
public void AppendFormatted(S1 s1) => s1.s = this.s;
public static void M(ref S1 s1)
{
Span<char> s = stackalloc char[10];
M2(ref s, " + expression + @");
}
public static void M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler handler) {}
}
public ref struct S1
{
public Span<char> s;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics();
}
[Theory]
[InlineData(@"$""{s2}""")]
[InlineData(@"$""{s2}"" + $""""")]
public void RefEscape_06(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
Span<char> s = stackalloc char[5];
Span<char> s2 = stackalloc char[10];
s.TryWrite(" + expression + @");
public static class MemoryExtensions
{
public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] CustomHandler builder) => true;
}
[InterpolatedStringHandler]
public ref struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { }
public bool AppendFormatted(Span<char> s) => true;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics();
}
[Theory]
[InlineData(@"$""{s2}""")]
[InlineData(@"$""{s2}"" + $""""")]
public void RefEscape_07(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
Span<char> s = stackalloc char[5];
Span<char> s2 = stackalloc char[10];
s.TryWrite(" + expression + @");
public static class MemoryExtensions
{
public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] ref CustomHandler builder) => true;
}
[InterpolatedStringHandler]
public ref struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { }
public bool AppendFormatted(Span<char> s) => true;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics();
}
[Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")]
[InlineData(@"$""{{ {i} }}""")]
[InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")]
public void BracesAreEscaped_01(string expression)
{
var code = @"
int i = 1;
System.Console.WriteLine(" + expression + @");";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
{
value:1
}");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 56 (0x38)
.maxstack 3
.locals init (int V_0, //i
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.1
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""{ ""
IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_1
IL_0019: ldloc.0
IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_001f: ldloca.s V_1
IL_0021: ldstr "" }""
IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_002b: ldloca.s V_1
IL_002d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0032: call ""void System.Console.WriteLine(string)""
IL_0037: ret
}
");
}
[Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")]
[InlineData(@"$""{{ {i} }}""")]
[InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")]
public void BracesAreEscaped_02(string expression)
{
var code = @"
int i = 1;
CustomHandler c = " + expression + @";
System.Console.WriteLine(c.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
literal:{
value:1
alignment:0
format:
literal: }");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 71 (0x47)
.maxstack 4
.locals init (int V_0, //i
CustomHandler V_1, //c
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_2
IL_0004: ldc.i4.4
IL_0005: ldc.i4.1
IL_0006: call ""CustomHandler..ctor(int, int)""
IL_000b: ldloca.s V_2
IL_000d: ldstr ""{ ""
IL_0012: call ""void CustomHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_2
IL_0019: ldloc.0
IL_001a: box ""int""
IL_001f: ldc.i4.0
IL_0020: ldnull
IL_0021: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0026: ldloca.s V_2
IL_0028: ldstr "" }""
IL_002d: call ""void CustomHandler.AppendLiteral(string)""
IL_0032: ldloc.2
IL_0033: stloc.1
IL_0034: ldloca.s V_1
IL_0036: constrained. ""CustomHandler""
IL_003c: callvirt ""string object.ToString()""
IL_0041: call ""void System.Console.WriteLine(string)""
IL_0046: ret
}
");
}
[Fact]
public void InterpolatedStringsAddedUnderObjectAddition()
{
var code = @"
int i1 = 1;
int i2 = 2;
int i3 = 3;
int i4 = 4;
System.Console.WriteLine($""{i1}"" + $""{i2}"" + $""{i3}"" + i4);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
value:2
value:3
4
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 66 (0x42)
.maxstack 3
.locals init (int V_0, //i1
int V_1, //i2
int V_2, //i3
int V_3, //i4
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_4)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: ldc.i4.4
IL_0007: stloc.3
IL_0008: ldloca.s V_4
IL_000a: ldc.i4.0
IL_000b: ldc.i4.3
IL_000c: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0011: ldloca.s V_4
IL_0013: ldloc.0
IL_0014: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0019: ldloca.s V_4
IL_001b: ldloc.1
IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0021: ldloca.s V_4
IL_0023: ldloc.2
IL_0024: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0029: ldloca.s V_4
IL_002b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0030: ldloca.s V_3
IL_0032: call ""string int.ToString()""
IL_0037: call ""string string.Concat(string, string)""
IL_003c: call ""void System.Console.WriteLine(string)""
IL_0041: ret
}
");
}
[Fact]
public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment()
{
var code = @"
object o1;
object o2;
object o3;
_ = $""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1;
o1.ToString();
o2.ToString();
o3.ToString();
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) });
comp.VerifyDiagnostics(
// (7,1): error CS0165: Use of unassigned local variable 'o2'
// o2.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o2").WithArguments("o2").WithLocation(7, 1),
// (8,1): error CS0165: Use of unassigned local variable 'o3'
// o3.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o3").WithArguments("o3").WithLocation(8, 1)
);
}
[Fact]
public void ParenthesizedAdditiveExpression_01()
{
var code = @"
int i1 = 1;
int i2 = 2;
int i3 = 3;
CustomHandler c = ($""{i1}"" + $""{i2}"") + $""{i3}"";
System.Console.WriteLine(c.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:0
format:
value:2
alignment:0
format:
value:3
alignment:0
format:
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 82 (0x52)
.maxstack 4
.locals init (int V_0, //i1
int V_1, //i2
int V_2, //i3
CustomHandler V_3, //c
CustomHandler V_4)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: ldloca.s V_4
IL_0008: ldc.i4.0
IL_0009: ldc.i4.3
IL_000a: call ""CustomHandler..ctor(int, int)""
IL_000f: ldloca.s V_4
IL_0011: ldloc.0
IL_0012: box ""int""
IL_0017: ldc.i4.0
IL_0018: ldnull
IL_0019: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001e: ldloca.s V_4
IL_0020: ldloc.1
IL_0021: box ""int""
IL_0026: ldc.i4.0
IL_0027: ldnull
IL_0028: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_002d: ldloca.s V_4
IL_002f: ldloc.2
IL_0030: box ""int""
IL_0035: ldc.i4.0
IL_0036: ldnull
IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003c: ldloc.s V_4
IL_003e: stloc.3
IL_003f: ldloca.s V_3
IL_0041: constrained. ""CustomHandler""
IL_0047: callvirt ""string object.ToString()""
IL_004c: call ""void System.Console.WriteLine(string)""
IL_0051: ret
}");
}
[Fact]
public void ParenthesizedAdditiveExpression_02()
{
var code = @"
int i1 = 1;
int i2 = 2;
int i3 = 3;
CustomHandler c = $""{i1}"" + ($""{i2}"" + $""{i3}"");
System.Console.WriteLine(c.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (6,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler'
// CustomHandler c = $"{i1}" + ($"{i2}" + $"{i3}");
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{i1}"" + ($""{i2}"" + $""{i3}"")").WithArguments("string", "CustomHandler").WithLocation(6, 19)
);
}
[Theory]
[InlineData(@"$""{1}"", $""{2}""")]
[InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")]
public void TupleDeclaration_01(string initializer)
{
var code = @"
(CustomHandler c1, CustomHandler c2) = (" + initializer + @");
System.Console.Write(c1.ToString());
System.Console.WriteLine(c2.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:0
format:
value:2
alignment:0
format:
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 91 (0x5b)
.maxstack 4
.locals init (CustomHandler V_0, //c1
CustomHandler V_1, //c2
CustomHandler V_2,
CustomHandler V_3)
IL_0000: ldloca.s V_3
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_3
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.0
IL_0012: ldnull
IL_0013: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0018: ldloc.3
IL_0019: stloc.2
IL_001a: ldloca.s V_3
IL_001c: ldc.i4.0
IL_001d: ldc.i4.1
IL_001e: call ""CustomHandler..ctor(int, int)""
IL_0023: ldloca.s V_3
IL_0025: ldc.i4.2
IL_0026: box ""int""
IL_002b: ldc.i4.0
IL_002c: ldnull
IL_002d: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0032: ldloc.3
IL_0033: ldloc.2
IL_0034: stloc.0
IL_0035: stloc.1
IL_0036: ldloca.s V_0
IL_0038: constrained. ""CustomHandler""
IL_003e: callvirt ""string object.ToString()""
IL_0043: call ""void System.Console.Write(string)""
IL_0048: ldloca.s V_1
IL_004a: constrained. ""CustomHandler""
IL_0050: callvirt ""string object.ToString()""
IL_0055: call ""void System.Console.WriteLine(string)""
IL_005a: ret
}
");
}
[Theory]
[InlineData(@"$""{1}"", $""{2}""")]
[InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")]
public void TupleDeclaration_02(string initializer)
{
var code = @"
(CustomHandler c1, CustomHandler c2) t = (" + initializer + @");
System.Console.Write(t.c1.ToString());
System.Console.WriteLine(t.c2.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:0
format:
value:2
alignment:0
format:
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 104 (0x68)
.maxstack 6
.locals init (System.ValueTuple<CustomHandler, CustomHandler> V_0, //t
CustomHandler V_1)
IL_0000: ldloca.s V_0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.0
IL_0005: ldc.i4.1
IL_0006: call ""CustomHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.1
IL_000e: box ""int""
IL_0013: ldc.i4.0
IL_0014: ldnull
IL_0015: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001a: ldloc.1
IL_001b: ldloca.s V_1
IL_001d: ldc.i4.0
IL_001e: ldc.i4.1
IL_001f: call ""CustomHandler..ctor(int, int)""
IL_0024: ldloca.s V_1
IL_0026: ldc.i4.2
IL_0027: box ""int""
IL_002c: ldc.i4.0
IL_002d: ldnull
IL_002e: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0033: ldloc.1
IL_0034: call ""System.ValueTuple<CustomHandler, CustomHandler>..ctor(CustomHandler, CustomHandler)""
IL_0039: ldloca.s V_0
IL_003b: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item1""
IL_0040: constrained. ""CustomHandler""
IL_0046: callvirt ""string object.ToString()""
IL_004b: call ""void System.Console.Write(string)""
IL_0050: ldloca.s V_0
IL_0052: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item2""
IL_0057: constrained. ""CustomHandler""
IL_005d: callvirt ""string object.ToString()""
IL_0062: call ""void System.Console.WriteLine(string)""
IL_0067: ret
}
");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using System.Collections.Immutable;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class InterpolationTests : CompilingTestBase
{
[Fact]
public void TestSimpleInterp()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""Jenny don\'t change your number { number }."");
Console.WriteLine($""Jenny don\'t change your number { number , -12 }."");
Console.WriteLine($""Jenny don\'t change your number { number , 12 }."");
Console.WriteLine($""Jenny don\'t change your number { number :###-####}."");
Console.WriteLine($""Jenny don\'t change your number { number , -12 :###-####}."");
Console.WriteLine($""Jenny don\'t change your number { number , 12 :###-####}."");
Console.WriteLine($""{number}"");
}
}";
string expectedOutput =
@"Jenny don't change your number 8675309.
Jenny don't change your number 8675309 .
Jenny don't change your number 8675309.
Jenny don't change your number 867-5309.
Jenny don't change your number 867-5309 .
Jenny don't change your number 867-5309.
8675309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestOnlyInterp()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""{number}"");
}
}";
string expectedOutput =
@"8675309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestDoubleInterp01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""{number}{number}"");
}
}";
string expectedOutput =
@"86753098675309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestDoubleInterp02()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""Jenny don\'t change your number { number :###-####} { number :###-####}."");
}
}";
string expectedOutput =
@"Jenny don't change your number 867-5309 867-5309.";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestEmptyInterp()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { /*trash*/ }."");
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,73): error CS1733: Expected expression
// Console.WriteLine("Jenny don\'t change your number \{ /*trash*/ }.");
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(5, 73)
);
}
[Fact]
public void TestHalfOpenInterp01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { "");
}
}";
// too many diagnostics perhaps, but it starts the right way.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,63): error CS1010: Newline in constant
// Console.WriteLine($"Jenny don\'t change your number { ");
Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(5, 63),
// (5,66): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string
// Console.WriteLine($"Jenny don\'t change your number { ");
Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 66),
// (6,6): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6),
// (6,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2));
}
[Fact]
public void TestHalfOpenInterp02()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { 8675309 // "");
}
}";
// too many diagnostics perhaps, but it starts the right way.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,71): error CS8077: A single-line comment may not be used in an interpolated string.
// Console.WriteLine($"Jenny don\'t change your number { 8675309 // ");
Diagnostic(ErrorCode.ERR_SingleLineCommentInExpressionHole, "//").WithLocation(5, 71),
// (6,6): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6),
// (6,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2));
}
[Fact]
public void TestHalfOpenInterp03()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { 8675309 /* "");
}
}";
// too many diagnostics perhaps, but it starts the right way.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,71): error CS1035: End-of-file found, '*/' expected
// Console.WriteLine($"Jenny don\'t change your number { 8675309 /* ");
Diagnostic(ErrorCode.ERR_OpenEndedComment, "").WithLocation(5, 71),
// (5,77): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string
// Console.WriteLine($"Jenny don\'t change your number { 8675309 /* ");
Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 77),
// (7,2): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 2),
// (7,2): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 2),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2));
}
[Fact]
public void LambdaInInterp()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
//Console.WriteLine(""jenny {0:(408) ###-####}"", new object[] { ((Func<int>)(() => { return number; })).Invoke() });
Console.WriteLine($""jenny { ((Func<int>)(() => { return number; })).Invoke() :(408) ###-####}"");
}
static int number = 8675309;
}
";
string expectedOutput = @"jenny (408) 867-5309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void OneLiteral()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""Hello"" );
}
}";
string expectedOutput = @"Hello";
var verifier = CompileAndVerify(source, expectedOutput: expectedOutput);
verifier.VerifyIL("Program.Main", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""Hello""
IL_0005: call ""void System.Console.WriteLine(string)""
IL_000a: ret
}
");
}
[Fact]
public void OneInsert()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var hello = $""Hello"";
Console.WriteLine( $""{hello}"" );
}
}";
string expectedOutput = @"Hello";
var verifier = CompileAndVerify(source, expectedOutput: expectedOutput);
verifier.VerifyIL("Program.Main", @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldstr ""Hello""
IL_0005: dup
IL_0006: brtrue.s IL_000e
IL_0008: pop
IL_0009: ldstr """"
IL_000e: call ""void System.Console.WriteLine(string)""
IL_0013: ret
}
");
}
[Fact]
public void TwoInserts()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var hello = $""Hello"";
var world = $""world"" ;
Console.WriteLine( $""{hello}, { world }."" );
}
}";
string expectedOutput = @"Hello, world.";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TwoInserts02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var hello = $""Hello"";
var world = $""world"" ;
Console.WriteLine( $@""{
hello
},
{
world }."" );
}
}";
string expectedOutput = @"Hello,
world.";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact, WorkItem(306, "https://github.com/dotnet/roslyn/issues/306"), WorkItem(308, "https://github.com/dotnet/roslyn/issues/308")]
public void DynamicInterpolation()
{
string source =
@"using System;
using System.Linq.Expressions;
class Program
{
static void Main(string[] args)
{
dynamic nil = null;
dynamic a = new string[] {""Hello"", ""world""};
Console.WriteLine($""<{nil}>"");
Console.WriteLine($""<{a}>"");
}
Expression<Func<string>> M(dynamic d) {
return () => $""Dynamic: {d}"";
}
}";
string expectedOutput = @"<>
<System.String[]>";
var verifier = CompileAndVerify(source, new[] { CSharpRef }, expectedOutput: expectedOutput).VerifyDiagnostics();
}
[Fact]
public void UnclosedInterpolation01()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,31): error CS1010: Newline in constant
// Console.WriteLine( $"{" );
Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(6, 31),
// (6,35): error CS8958: Newlines are not allowed inside a non-verbatim interpolated string
// Console.WriteLine( $"{" );
Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(6, 35),
// (7,6): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 6),
// (7,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 6),
// (8,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 2));
}
[Fact]
public void UnclosedInterpolation02()
{
string source =
@"class Program
{
static void Main(string[] args)
{
var x = $"";";
// The precise error messages are not important, but this must be an error.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,19): error CS1010: Newline in constant
// var x = $";
Diagnostic(ErrorCode.ERR_NewlineInConst, ";").WithLocation(5, 19),
// (5,20): error CS1002: ; expected
// var x = $";
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 20),
// (5,20): error CS1513: } expected
// var x = $";
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20),
// (5,20): error CS1513: } expected
// var x = $";
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20)
);
}
[Fact]
public void EmptyFormatSpecifier()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{3:}"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,32): error CS8089: Empty format specifier.
// Console.WriteLine( $"{3:}" );
Diagnostic(ErrorCode.ERR_EmptyFormatSpecifier, ":").WithLocation(6, 32)
);
}
[Fact]
public void TrailingSpaceInFormatSpecifier()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{3:d }"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,32): error CS8088: A format specifier may not contain trailing whitespace.
// Console.WriteLine( $"{3:d }" );
Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ":d ").WithLocation(6, 32)
);
}
[Fact]
public void TrailingSpaceInFormatSpecifier02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $@""{3:d
}"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,33): error CS8088: A format specifier may not contain trailing whitespace.
// Console.WriteLine( $@"{3:d
Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, @":d
").WithLocation(6, 33)
);
}
[Fact]
public void MissingInterpolationExpression01()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{ }"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,32): error CS1733: Expected expression
// Console.WriteLine( $"{ }" );
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 32)
);
}
[Fact]
public void MissingInterpolationExpression02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $@""{ }"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,33): error CS1733: Expected expression
// Console.WriteLine( $@"{ }" );
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 33)
);
}
[Fact]
public void MissingInterpolationExpression03()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( ";
var normal = "$\"";
var verbat = "$@\"";
// ensure reparsing of interpolated string token is precise in error scenarios (assertions do not fail)
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void MisplacedNewline01()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var s = $""{ @""
"" }
"";
}
}";
// The precise error messages are not important, but this must be an error.
Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void MisplacedNewline02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var s = $""{ @""
""}
"";
}
}";
// The precise error messages are not important, but this must be an error.
Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void PreprocessorInsideInterpolation()
{
string source =
@"class Program
{
static void Main()
{
var s = $@""{
#region :
#endregion
0
}"";
}
}";
// The precise error messages are not important, but this must be an error.
Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void EscapedCurly()
{
string source =
@"class Program
{
static void Main()
{
var s1 = $"" \u007B "";
var s2 = $"" \u007D"";
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,21): error CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string.
// var s1 = $" \u007B ";
Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007B").WithArguments("{").WithLocation(5, 21),
// (6,21): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string.
// var s2 = $" \u007D";
Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007D").WithArguments("}").WithLocation(6, 21)
);
}
[Fact, WorkItem(1119878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119878")]
public void NoFillIns01()
{
string source =
@"class Program
{
static void Main()
{
System.Console.Write($""{{ x }}"");
System.Console.WriteLine($@""This is a test"");
}
}";
string expectedOutput = @"{ x }This is a test";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void BadAlignment()
{
string source =
@"class Program
{
static void Main()
{
var s = $""{1,1E10}"";
var t = $""{1,(int)1E10}"";
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,22): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
// var s = $"{1,1E10}";
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1E10").WithArguments("double", "int").WithLocation(5, 22),
// (5,22): error CS0150: A constant value is expected
// var s = $"{1,1E10}";
Diagnostic(ErrorCode.ERR_ConstantExpected, "1E10").WithLocation(5, 22),
// (6,22): error CS0221: Constant value '10000000000' cannot be converted to a 'int' (use 'unchecked' syntax to override)
// var t = $"{1,(int)1E10}";
Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)1E10").WithArguments("10000000000", "int").WithLocation(6, 22),
// (6,22): error CS0150: A constant value is expected
// var t = $"{1,(int)1E10}";
Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)1E10").WithLocation(6, 22)
);
}
[Fact]
public void NestedInterpolatedVerbatim()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var s = $@""{$@""{1}""}"";
Console.WriteLine(s);
}
}";
string expectedOutput = @"1";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
// Since the platform type System.FormattableString is not yet in our platforms (at the
// time of writing), we explicitly include the required platform types into the sources under test.
private const string formattableString = @"
/*============================================================
**
** Class: FormattableString
**
**
** Purpose: implementation of the FormattableString
** class.
**
===========================================================*/
namespace System
{
/// <summary>
/// A composite format string along with the arguments to be formatted. An instance of this
/// type may result from the use of the C# or VB language primitive ""interpolated string"".
/// </summary>
public abstract class FormattableString : IFormattable
{
/// <summary>
/// The composite format string.
/// </summary>
public abstract string Format { get; }
/// <summary>
/// Returns an object array that contains zero or more objects to format. Clients should not
/// mutate the contents of the array.
/// </summary>
public abstract object[] GetArguments();
/// <summary>
/// The number of arguments to be formatted.
/// </summary>
public abstract int ArgumentCount { get; }
/// <summary>
/// Returns one argument to be formatted from argument position <paramref name=""index""/>.
/// </summary>
public abstract object GetArgument(int index);
/// <summary>
/// Format to a string using the given culture.
/// </summary>
public abstract string ToString(IFormatProvider formatProvider);
string IFormattable.ToString(string ignored, IFormatProvider formatProvider)
{
return ToString(formatProvider);
}
/// <summary>
/// Format the given object in the invariant culture. This static method may be
/// imported in C# by
/// <code>
/// using static System.FormattableString;
/// </code>.
/// Within the scope
/// of that import directive an interpolated string may be formatted in the
/// invariant culture by writing, for example,
/// <code>
/// Invariant($""{{ lat = {latitude}; lon = {longitude} }}"")
/// </code>
/// </summary>
public static string Invariant(FormattableString formattable)
{
if (formattable == null)
{
throw new ArgumentNullException(""formattable"");
}
return formattable.ToString(Globalization.CultureInfo.InvariantCulture);
}
public override string ToString()
{
return ToString(Globalization.CultureInfo.CurrentCulture);
}
}
}
/*============================================================
**
** Class: FormattableStringFactory
**
**
** Purpose: implementation of the FormattableStringFactory
** class.
**
===========================================================*/
namespace System.Runtime.CompilerServices
{
/// <summary>
/// A factory type used by compilers to create instances of the type <see cref=""FormattableString""/>.
/// </summary>
public static class FormattableStringFactory
{
/// <summary>
/// Create a <see cref=""FormattableString""/> from a composite format string and object
/// array containing zero or more objects to format.
/// </summary>
public static FormattableString Create(string format, params object[] arguments)
{
if (format == null)
{
throw new ArgumentNullException(""format"");
}
if (arguments == null)
{
throw new ArgumentNullException(""arguments"");
}
return new ConcreteFormattableString(format, arguments);
}
private sealed class ConcreteFormattableString : FormattableString
{
private readonly string _format;
private readonly object[] _arguments;
internal ConcreteFormattableString(string format, object[] arguments)
{
_format = format;
_arguments = arguments;
}
public override string Format { get { return _format; } }
public override object[] GetArguments() { return _arguments; }
public override int ArgumentCount { get { return _arguments.Length; } }
public override object GetArgument(int index) { return _arguments[index]; }
public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, Format, _arguments); }
}
}
}
";
[Fact]
public void TargetType01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
IFormattable f = $""test"";
Console.Write(f is System.FormattableString);
}
}";
CompileAndVerify(source + formattableString, expectedOutput: "True");
}
[Fact]
public void TargetType02()
{
string source =
@"using System;
interface I1 { void M(String s); }
interface I2 { void M(FormattableString s); }
interface I3 { void M(IFormattable s); }
interface I4 : I1, I2 {}
interface I5 : I1, I3 {}
interface I6 : I2, I3 {}
interface I7 : I1, I2, I3 {}
class C : I1, I2, I3, I4, I5, I6, I7
{
public void M(String s) { Console.Write(1); }
public void M(FormattableString s) { Console.Write(2); }
public void M(IFormattable s) { Console.Write(3); }
}
class Program {
public static void Main(string[] args)
{
C c = new C();
((I1)c).M($"""");
((I2)c).M($"""");
((I3)c).M($"""");
((I4)c).M($"""");
((I5)c).M($"""");
((I6)c).M($"""");
((I7)c).M($"""");
((C)c).M($"""");
}
}";
CompileAndVerify(source + formattableString, expectedOutput: "12311211");
}
[Fact]
public void MissingHelper()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
IFormattable f = $""test"";
}
}";
CreateCompilationWithMscorlib40(source).VerifyEmitDiagnostics(
// (5,26): error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported
// IFormattable f = $"test";
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""test""").WithArguments("System.Runtime.CompilerServices.FormattableStringFactory").WithLocation(5, 26)
);
}
[Fact]
public void AsyncInterp()
{
string source =
@"using System;
using System.Threading.Tasks;
class Program {
public static void Main(string[] args)
{
Task<string> hello = Task.FromResult(""Hello"");
Task<string> world = Task.FromResult(""world"");
M(hello, world).Wait();
}
public static async Task M(Task<string> hello, Task<string> world)
{
Console.WriteLine($""{ await hello }, { await world }!"");
}
}";
CompileAndVerify(
source, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }, expectedOutput: "Hello, world!", targetFramework: TargetFramework.Empty);
}
[Fact]
public void AlignmentExpression()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { 123 , -(3+4) }."");
}
}";
CompileAndVerify(source + formattableString, expectedOutput: "X = 123 .");
}
[Fact]
public void AlignmentMagnitude()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { 123 , (32768) }."");
Console.WriteLine($""X = { 123 , -(32768) }."");
Console.WriteLine($""X = { 123 , (32767) }."");
Console.WriteLine($""X = { 123 , -(32767) }."");
Console.WriteLine($""X = { 123 , int.MaxValue }."");
Console.WriteLine($""X = { 123 , int.MinValue }."");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,42): warning CS8094: Alignment value 32768 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , (32768) }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "32768").WithArguments("32768", "32767").WithLocation(5, 42),
// (6,41): warning CS8094: Alignment value -32768 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , -(32768) }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "-(32768)").WithArguments("-32768", "32767").WithLocation(6, 41),
// (9,41): warning CS8094: Alignment value 2147483647 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , int.MaxValue }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MaxValue").WithArguments("2147483647", "32767").WithLocation(9, 41),
// (10,41): warning CS8094: Alignment value -2147483648 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , int.MinValue }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MinValue").WithArguments("-2147483648", "32767").WithLocation(10, 41)
);
}
[WorkItem(1097388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097388")]
[Fact]
public void InterpolationExpressionMustBeValue01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { String }."");
Console.WriteLine($""X = { null }."");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,35): error CS0119: 'string' is a type, which is not valid in the given context
// Console.WriteLine($"X = { String }.");
Diagnostic(ErrorCode.ERR_BadSKunknown, "String").WithArguments("string", "type").WithLocation(5, 35)
);
}
[Fact]
public void InterpolationExpressionMustBeValue02()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { x=>3 }."");
Console.WriteLine($""X = { Program.Main }."");
Console.WriteLine($""X = { Program.Main(null) }."");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,35): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type
// Console.WriteLine($"X = { x=>3 }.");
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x=>3").WithArguments("lambda expression", "object").WithLocation(5, 35),
// (6,43): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method?
// Console.WriteLine($"X = { Program.Main }.");
Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 43),
// (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object'
// Console.WriteLine($"X = { Program.Main(null) }.");
Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35)
);
}
[WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")]
[Fact]
public void BadCorelib01()
{
var text =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } }
public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } }
public struct Char { }
public class String { }
internal class Program
{
public static void Main()
{
var s = $""X = { 1 } "";
}
}
}";
CreateEmptyCompilation(text, options: TestOptions.DebugExe)
.VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"),
// (15,21): error CS0117: 'string' does not contain a definition for 'Format'
// var s = $"X = { 1 } ";
Diagnostic(ErrorCode.ERR_NoSuchMember, @"$""X = { 1 } """).WithArguments("string", "Format").WithLocation(15, 21)
);
}
[WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")]
[Fact]
public void BadCorelib02()
{
var text =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } }
public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } }
public struct Char { }
public class String {
public static Boolean Format(string format, int arg) { return true; }
}
internal class Program
{
public static void Main()
{
var s = $""X = { 1 } "";
}
}
}";
CreateEmptyCompilation(text, options: TestOptions.DebugExe)
.VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"),
// (17,21): error CS0029: Cannot implicitly convert type 'bool' to 'string'
// var s = $"X = { 1 } ";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""X = { 1 } """).WithArguments("bool", "string").WithLocation(17, 21)
);
}
[Fact]
public void SillyCoreLib01()
{
var text =
@"namespace System
{
interface IFormattable { }
namespace Runtime.CompilerServices {
public static class FormattableStringFactory {
public static Bozo Create(string format, int arg) { return new Bozo(); }
}
}
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } }
public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } }
public struct Char { }
public class String {
public static Bozo Format(string format, int arg) { return new Bozo(); }
}
public class FormattableString {
}
public class Bozo {
public static implicit operator string(Bozo bozo) { return ""zz""; }
public static implicit operator FormattableString(Bozo bozo) { return new FormattableString(); }
}
internal class Program
{
public static void Main()
{
var s1 = $""X = { 1 } "";
FormattableString s2 = $""X = { 1 } "";
}
}
}";
var comp = CreateEmptyCompilation(text, options: Test.Utilities.TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
var compilation = CompileAndVerify(comp, verify: Verification.Fails);
compilation.VerifyIL("System.Program.Main",
@"{
// Code size 35 (0x23)
.maxstack 2
IL_0000: ldstr ""X = {0} ""
IL_0005: ldc.i4.1
IL_0006: call ""System.Bozo string.Format(string, int)""
IL_000b: call ""string System.Bozo.op_Implicit(System.Bozo)""
IL_0010: pop
IL_0011: ldstr ""X = {0} ""
IL_0016: ldc.i4.1
IL_0017: call ""System.Bozo System.Runtime.CompilerServices.FormattableStringFactory.Create(string, int)""
IL_001c: call ""System.FormattableString System.Bozo.op_Implicit(System.Bozo)""
IL_0021: pop
IL_0022: ret
}");
}
[WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")]
[Fact]
public void Syntax01()
{
var text =
@"using System;
class Program
{
static void Main(string[] args)
{
var x = $""{ Math.Abs(value: 1):\}"";
var y = x;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,40): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string.
// var x = $"{ Math.Abs(value: 1):\}";
Diagnostic(ErrorCode.ERR_EscapedCurly, @"\").WithArguments("}").WithLocation(6, 40),
// (6,40): error CS1009: Unrecognized escape sequence
// var x = $"{ Math.Abs(value: 1):\}";
Diagnostic(ErrorCode.ERR_IllegalEscape, @"\}").WithLocation(6, 40)
);
}
[WorkItem(1097941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097941")]
[Fact]
public void Syntax02()
{
var text =
@"using S = System;
class C
{
void M()
{
var x = $""{ (S:
}
}";
// the precise diagnostics do not matter, as long as it is an error and not a crash.
Assert.True(SyntaxFactory.ParseSyntaxTree(text).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")]
[Fact]
public void Syntax03()
{
var text =
@"using System;
class Program
{
static void Main(string[] args)
{
var x = $""{ Math.Abs(value: 1):}}"";
var y = x;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,18): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'.
// var x = $"{ Math.Abs(value: 1):}}";
Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, @"""{").WithLocation(6, 18)
);
}
[WorkItem(1099105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099105")]
[Fact]
public void NoUnexpandedForm()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
string[] arr1 = new string[] { ""xyzzy"" };
object[] arr2 = arr1;
Console.WriteLine($""-{null}-"");
Console.WriteLine($""-{arr1}-"");
Console.WriteLine($""-{arr2}-"");
}
}";
CompileAndVerify(source + formattableString, expectedOutput:
@"--
-System.String[]-
-System.String[]-");
}
[WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")]
[Fact]
public void Dynamic01()
{
var text =
@"class C
{
const dynamic a = a;
string s = $""{0,a}"";
}";
CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (3,19): error CS0110: The evaluation of the constant value for 'C.a' involves a circular definition
// const dynamic a = a;
Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("C.a").WithLocation(3, 19),
// (3,23): error CS0134: 'C.a' is of type 'dynamic'. A const field of a reference type other than string can only be initialized with null.
// const dynamic a = a;
Diagnostic(ErrorCode.ERR_NotNullConstRefField, "a").WithArguments("C.a", "dynamic").WithLocation(3, 23),
// (4,21): error CS0150: A constant value is expected
// string s = $"{0,a}";
Diagnostic(ErrorCode.ERR_ConstantExpected, "a").WithLocation(4, 21)
);
}
[WorkItem(1099238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099238")]
[Fact]
public void Syntax04()
{
var text =
@"using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<string>> e = () => $""\u1{0:\u2}"";
Console.WriteLine(e);
}
}";
CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,46): error CS1009: Unrecognized escape sequence
// Expression<Func<string>> e = () => $"\u1{0:\u2}";
Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u1").WithLocation(8, 46),
// (8,52): error CS1009: Unrecognized escape sequence
// Expression<Func<string>> e = () => $"\u1{0:\u2}";
Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u2").WithLocation(8, 52)
);
}
[Fact, WorkItem(1098612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098612")]
public void MissingConversionFromFormattableStringToIFormattable()
{
var text =
@"namespace System.Runtime.CompilerServices
{
public static class FormattableStringFactory
{
public static FormattableString Create(string format, params object[] arguments)
{
return null;
}
}
}
namespace System
{
public abstract class FormattableString
{
}
}
static class C
{
static void Main()
{
System.IFormattable i = $""{""""}"";
}
}";
CreateCompilationWithMscorlib40AndSystemCore(text).VerifyEmitDiagnostics(
// (23,33): error CS0029: Cannot implicitly convert type 'FormattableString' to 'IFormattable'
// System.IFormattable i = $"{""}";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{""""}""").WithArguments("System.FormattableString", "System.IFormattable").WithLocation(23, 33)
);
}
[Theory, WorkItem(54702, "https://github.com/dotnet/roslyn/issues/54702")]
[InlineData(@"$""{s1}{s2}""", @"$""{s1}{s2}{s3}""", @"$""{s1}{s2}{s3}{s4}""", @"$""{s1}{s2}{s3}{s4}{s5}""")]
[InlineData(@"$""{s1}"" + $""{s2}""", @"$""{s1}"" + $""{s2}"" + $""{s3}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}"" + $""{s5}""")]
public void InterpolatedStringHandler_ConcatPreferencesForAllStringElements(string twoComponents, string threeComponents, string fourComponents, string fiveComponents)
{
var code = @"
using System;
Console.WriteLine(TwoComponents());
Console.WriteLine(ThreeComponents());
Console.WriteLine(FourComponents());
Console.WriteLine(FiveComponents());
string TwoComponents()
{
string s1 = ""1"";
string s2 = ""2"";
return " + twoComponents + @";
}
string ThreeComponents()
{
string s1 = ""1"";
string s2 = ""2"";
string s3 = ""3"";
return " + threeComponents + @";
}
string FourComponents()
{
string s1 = ""1"";
string s2 = ""2"";
string s3 = ""3"";
string s4 = ""4"";
return " + fourComponents + @";
}
string FiveComponents()
{
string s1 = ""1"";
string s2 = ""2"";
string s3 = ""3"";
string s4 = ""4"";
string s5 = ""5"";
return " + fiveComponents + @";
}
";
var handler = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { code, handler }, expectedOutput: @"
12
123
1234
value:1
value:2
value:3
value:4
value:5
");
verifier.VerifyIL("<Program>$.<<Main>$>g__TwoComponents|0_0()", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (string V_0) //s2
IL_0000: ldstr ""1""
IL_0005: ldstr ""2""
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: call ""string string.Concat(string, string)""
IL_0011: ret
}
");
verifier.VerifyIL("<Program>$.<<Main>$>g__ThreeComponents|0_1()", @"
{
// Code size 25 (0x19)
.maxstack 3
.locals init (string V_0, //s2
string V_1) //s3
IL_0000: ldstr ""1""
IL_0005: ldstr ""2""
IL_000a: stloc.0
IL_000b: ldstr ""3""
IL_0010: stloc.1
IL_0011: ldloc.0
IL_0012: ldloc.1
IL_0013: call ""string string.Concat(string, string, string)""
IL_0018: ret
}
");
verifier.VerifyIL("<Program>$.<<Main>$>g__FourComponents|0_2()", @"
{
// Code size 32 (0x20)
.maxstack 4
.locals init (string V_0, //s2
string V_1, //s3
string V_2) //s4
IL_0000: ldstr ""1""
IL_0005: ldstr ""2""
IL_000a: stloc.0
IL_000b: ldstr ""3""
IL_0010: stloc.1
IL_0011: ldstr ""4""
IL_0016: stloc.2
IL_0017: ldloc.0
IL_0018: ldloc.1
IL_0019: ldloc.2
IL_001a: call ""string string.Concat(string, string, string, string)""
IL_001f: ret
}
");
verifier.VerifyIL("<Program>$.<<Main>$>g__FiveComponents|0_3()", @"
{
// Code size 89 (0x59)
.maxstack 3
.locals init (string V_0, //s1
string V_1, //s2
string V_2, //s3
string V_3, //s4
string V_4, //s5
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_5)
IL_0000: ldstr ""1""
IL_0005: stloc.0
IL_0006: ldstr ""2""
IL_000b: stloc.1
IL_000c: ldstr ""3""
IL_0011: stloc.2
IL_0012: ldstr ""4""
IL_0017: stloc.3
IL_0018: ldstr ""5""
IL_001d: stloc.s V_4
IL_001f: ldloca.s V_5
IL_0021: ldc.i4.0
IL_0022: ldc.i4.5
IL_0023: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0028: ldloca.s V_5
IL_002a: ldloc.0
IL_002b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0030: ldloca.s V_5
IL_0032: ldloc.1
IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0038: ldloca.s V_5
IL_003a: ldloc.2
IL_003b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0040: ldloca.s V_5
IL_0042: ldloc.3
IL_0043: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0048: ldloca.s V_5
IL_004a: ldloc.s V_4
IL_004c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0051: ldloca.s V_5
IL_0053: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0058: ret
}
");
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandler_OverloadsAndBoolReturns(
bool useDefaultParameters,
bool useBoolReturns,
bool constructorBoolArg,
[CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression)
{
var source =
@"int a = 1;
System.Console.WriteLine(" + expression + @");";
string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg);
string expectedOutput = useDefaultParameters ?
@"base
value:1,alignment:0:format:
value:1,alignment:1:format:
value:1,alignment:0:format:X
value:1,alignment:2:format:Y" :
@"base
value:1
value:1,alignment:1
value:1:format:X
value:1,alignment:2:format:Y";
string expectedIl = getIl();
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
var comp1 = CreateCompilation(interpolatedStringBuilder);
foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() })
{
var comp2 = CreateCompilation(source, new[] { reference });
verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
}
string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch
{
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 80 (0x50)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_1
IL_0019: ldloc.0
IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_001f: ldloca.s V_1
IL_0021: ldloc.0
IL_0022: ldc.i4.1
IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_0028: ldloca.s V_1
IL_002a: ldloc.0
IL_002b: ldstr ""X""
IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldloc.0
IL_0038: ldc.i4.2
IL_0039: ldstr ""Y""
IL_003e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0043: ldloca.s V_1
IL_0045: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_004a: call ""void System.Console.WriteLine(string)""
IL_004f: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 84 (0x54)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_1
IL_0019: ldloc.0
IL_001a: ldc.i4.0
IL_001b: ldnull
IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0021: ldloca.s V_1
IL_0023: ldloc.0
IL_0024: ldc.i4.1
IL_0025: ldnull
IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_002b: ldloca.s V_1
IL_002d: ldloc.0
IL_002e: ldc.i4.0
IL_002f: ldstr ""X""
IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0039: ldloca.s V_1
IL_003b: ldloc.0
IL_003c: ldc.i4.2
IL_003d: ldstr ""Y""
IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0047: ldloca.s V_1
IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_004e: call ""void System.Console.WriteLine(string)""
IL_0053: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 92 (0x5c)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: brfalse.s IL_004d
IL_0019: ldloca.s V_1
IL_001b: ldloc.0
IL_001c: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0021: brfalse.s IL_004d
IL_0023: ldloca.s V_1
IL_0025: ldloc.0
IL_0026: ldc.i4.1
IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_002c: brfalse.s IL_004d
IL_002e: ldloca.s V_1
IL_0030: ldloc.0
IL_0031: ldstr ""X""
IL_0036: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_003b: brfalse.s IL_004d
IL_003d: ldloca.s V_1
IL_003f: ldloc.0
IL_0040: ldc.i4.2
IL_0041: ldstr ""Y""
IL_0046: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004b: br.s IL_004e
IL_004d: ldc.i4.0
IL_004e: pop
IL_004f: ldloca.s V_1
IL_0051: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0056: call ""void System.Console.WriteLine(string)""
IL_005b: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 96 (0x60)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: brfalse.s IL_0051
IL_0019: ldloca.s V_1
IL_001b: ldloc.0
IL_001c: ldc.i4.0
IL_001d: ldnull
IL_001e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0023: brfalse.s IL_0051
IL_0025: ldloca.s V_1
IL_0027: ldloc.0
IL_0028: ldc.i4.1
IL_0029: ldnull
IL_002a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_002f: brfalse.s IL_0051
IL_0031: ldloca.s V_1
IL_0033: ldloc.0
IL_0034: ldc.i4.0
IL_0035: ldstr ""X""
IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_003f: brfalse.s IL_0051
IL_0041: ldloca.s V_1
IL_0043: ldloc.0
IL_0044: ldc.i4.2
IL_0045: ldstr ""Y""
IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004f: br.s IL_0052
IL_0051: ldc.i4.0
IL_0052: pop
IL_0053: ldloca.s V_1
IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005a: call ""void System.Console.WriteLine(string)""
IL_005f: ret
}
",
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 89 (0x59)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_004a
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: ldloca.s V_1
IL_001d: ldloc.0
IL_001e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0023: ldloca.s V_1
IL_0025: ldloc.0
IL_0026: ldc.i4.1
IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_002c: ldloca.s V_1
IL_002e: ldloc.0
IL_002f: ldstr ""X""
IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_0039: ldloca.s V_1
IL_003b: ldloc.0
IL_003c: ldc.i4.2
IL_003d: ldstr ""Y""
IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0047: ldc.i4.1
IL_0048: br.s IL_004b
IL_004a: ldc.i4.0
IL_004b: pop
IL_004c: ldloca.s V_1
IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0053: call ""void System.Console.WriteLine(string)""
IL_0058: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 93 (0x5d)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_004e
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: ldloca.s V_1
IL_001d: ldloc.0
IL_001e: ldc.i4.0
IL_001f: ldnull
IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0025: ldloca.s V_1
IL_0027: ldloc.0
IL_0028: ldc.i4.1
IL_0029: ldnull
IL_002a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_002f: ldloca.s V_1
IL_0031: ldloc.0
IL_0032: ldc.i4.0
IL_0033: ldstr ""X""
IL_0038: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_003d: ldloca.s V_1
IL_003f: ldloc.0
IL_0040: ldc.i4.2
IL_0041: ldstr ""Y""
IL_0046: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004b: ldc.i4.1
IL_004c: br.s IL_004f
IL_004e: ldc.i4.0
IL_004f: pop
IL_0050: ldloca.s V_1
IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0057: call ""void System.Console.WriteLine(string)""
IL_005c: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 96 (0x60)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_0051
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: brfalse.s IL_0051
IL_001d: ldloca.s V_1
IL_001f: ldloc.0
IL_0020: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0025: brfalse.s IL_0051
IL_0027: ldloca.s V_1
IL_0029: ldloc.0
IL_002a: ldc.i4.1
IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_0030: brfalse.s IL_0051
IL_0032: ldloca.s V_1
IL_0034: ldloc.0
IL_0035: ldstr ""X""
IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_003f: brfalse.s IL_0051
IL_0041: ldloca.s V_1
IL_0043: ldloc.0
IL_0044: ldc.i4.2
IL_0045: ldstr ""Y""
IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004f: br.s IL_0052
IL_0051: ldc.i4.0
IL_0052: pop
IL_0053: ldloca.s V_1
IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005a: call ""void System.Console.WriteLine(string)""
IL_005f: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 100 (0x64)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_0055
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: brfalse.s IL_0055
IL_001d: ldloca.s V_1
IL_001f: ldloc.0
IL_0020: ldc.i4.0
IL_0021: ldnull
IL_0022: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0027: brfalse.s IL_0055
IL_0029: ldloca.s V_1
IL_002b: ldloc.0
IL_002c: ldc.i4.1
IL_002d: ldnull
IL_002e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0033: brfalse.s IL_0055
IL_0035: ldloca.s V_1
IL_0037: ldloc.0
IL_0038: ldc.i4.0
IL_0039: ldstr ""X""
IL_003e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0043: brfalse.s IL_0055
IL_0045: ldloca.s V_1
IL_0047: ldloc.0
IL_0048: ldc.i4.2
IL_0049: ldstr ""Y""
IL_004e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0053: br.s IL_0056
IL_0055: ldc.i4.0
IL_0056: pop
IL_0057: ldloca.s V_1
IL_0059: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005e: call ""void System.Console.WriteLine(string)""
IL_0063: ret
}
",
};
}
[Fact]
public void UseOfSpanInInterpolationHole_CSharp9()
{
var source = @"
using System;
ReadOnlySpan<char> span = stackalloc char[1];
Console.WriteLine($""{span}"");";
var comp = CreateCompilation(new[] { source, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false) }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,22): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// Console.WriteLine($"{span}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "span").WithArguments("interpolated string handlers", "10.0").WithLocation(4, 22)
);
}
[ConditionalTheory(typeof(MonoOrCoreClrOnly))]
[CombinatorialData]
public void UseOfSpanInInterpolationHole(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg,
[CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression)
{
var source =
@"
using System;
ReadOnlySpan<char> a = ""1"";
System.Console.WriteLine(" + expression + ");";
string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg);
string expectedOutput = useDefaultParameters ?
@"base
value:1,alignment:0:format:
value:1,alignment:1:format:
value:1,alignment:0:format:X
value:1,alignment:2:format:Y" :
@"base
value:1
value:1,alignment:1
value:1:format:X
value:1,alignment:2:format:Y";
string expectedIl = getIl();
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
var comp1 = CreateCompilation(interpolatedStringBuilder, targetFramework: TargetFramework.NetCoreApp);
foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() })
{
var comp2 = CreateCompilation(source, new[] { reference }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10);
verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
}
string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch
{
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 89 (0x59)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: ldloca.s V_1
IL_0022: ldloc.0
IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_0028: ldloca.s V_1
IL_002a: ldloc.0
IL_002b: ldc.i4.1
IL_002c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0031: ldloca.s V_1
IL_0033: ldloc.0
IL_0034: ldstr ""X""
IL_0039: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_003e: ldloca.s V_1
IL_0040: ldloc.0
IL_0041: ldc.i4.2
IL_0042: ldstr ""Y""
IL_0047: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_004c: ldloca.s V_1
IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0053: call ""void System.Console.WriteLine(string)""
IL_0058: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 93 (0x5d)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: ldloca.s V_1
IL_0022: ldloc.0
IL_0023: ldc.i4.0
IL_0024: ldnull
IL_0025: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_002a: ldloca.s V_1
IL_002c: ldloc.0
IL_002d: ldc.i4.1
IL_002e: ldnull
IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0034: ldloca.s V_1
IL_0036: ldloc.0
IL_0037: ldc.i4.0
IL_0038: ldstr ""X""
IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0042: ldloca.s V_1
IL_0044: ldloc.0
IL_0045: ldc.i4.2
IL_0046: ldstr ""Y""
IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0050: ldloca.s V_1
IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0057: call ""void System.Console.WriteLine(string)""
IL_005c: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 101 (0x65)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: brfalse.s IL_0056
IL_0022: ldloca.s V_1
IL_0024: ldloc.0
IL_0025: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_002a: brfalse.s IL_0056
IL_002c: ldloca.s V_1
IL_002e: ldloc.0
IL_002f: ldc.i4.1
IL_0030: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0035: brfalse.s IL_0056
IL_0037: ldloca.s V_1
IL_0039: ldloc.0
IL_003a: ldstr ""X""
IL_003f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_0044: brfalse.s IL_0056
IL_0046: ldloca.s V_1
IL_0048: ldloc.0
IL_0049: ldc.i4.2
IL_004a: ldstr ""Y""
IL_004f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0054: br.s IL_0057
IL_0056: ldc.i4.0
IL_0057: pop
IL_0058: ldloca.s V_1
IL_005a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005f: call ""void System.Console.WriteLine(string)""
IL_0064: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 105 (0x69)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: brfalse.s IL_005a
IL_0022: ldloca.s V_1
IL_0024: ldloc.0
IL_0025: ldc.i4.0
IL_0026: ldnull
IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_002c: brfalse.s IL_005a
IL_002e: ldloca.s V_1
IL_0030: ldloc.0
IL_0031: ldc.i4.1
IL_0032: ldnull
IL_0033: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0038: brfalse.s IL_005a
IL_003a: ldloca.s V_1
IL_003c: ldloc.0
IL_003d: ldc.i4.0
IL_003e: ldstr ""X""
IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0048: brfalse.s IL_005a
IL_004a: ldloca.s V_1
IL_004c: ldloc.0
IL_004d: ldc.i4.2
IL_004e: ldstr ""Y""
IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0058: br.s IL_005b
IL_005a: ldc.i4.0
IL_005b: pop
IL_005c: ldloca.s V_1
IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0063: call ""void System.Console.WriteLine(string)""
IL_0068: ret
}
",
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 98 (0x62)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_0053
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: ldloca.s V_1
IL_0026: ldloc.0
IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_002c: ldloca.s V_1
IL_002e: ldloc.0
IL_002f: ldc.i4.1
IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0035: ldloca.s V_1
IL_0037: ldloc.0
IL_0038: ldstr ""X""
IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_0042: ldloca.s V_1
IL_0044: ldloc.0
IL_0045: ldc.i4.2
IL_0046: ldstr ""Y""
IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0050: ldc.i4.1
IL_0051: br.s IL_0054
IL_0053: ldc.i4.0
IL_0054: pop
IL_0055: ldloca.s V_1
IL_0057: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005c: call ""void System.Console.WriteLine(string)""
IL_0061: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 105 (0x69)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_005a
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: brfalse.s IL_005a
IL_0026: ldloca.s V_1
IL_0028: ldloc.0
IL_0029: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_002e: brfalse.s IL_005a
IL_0030: ldloca.s V_1
IL_0032: ldloc.0
IL_0033: ldc.i4.1
IL_0034: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0039: brfalse.s IL_005a
IL_003b: ldloca.s V_1
IL_003d: ldloc.0
IL_003e: ldstr ""X""
IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_0048: brfalse.s IL_005a
IL_004a: ldloca.s V_1
IL_004c: ldloc.0
IL_004d: ldc.i4.2
IL_004e: ldstr ""Y""
IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0058: br.s IL_005b
IL_005a: ldc.i4.0
IL_005b: pop
IL_005c: ldloca.s V_1
IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0063: call ""void System.Console.WriteLine(string)""
IL_0068: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 102 (0x66)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_0057
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: ldloca.s V_1
IL_0026: ldloc.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_002e: ldloca.s V_1
IL_0030: ldloc.0
IL_0031: ldc.i4.1
IL_0032: ldnull
IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0038: ldloca.s V_1
IL_003a: ldloc.0
IL_003b: ldc.i4.0
IL_003c: ldstr ""X""
IL_0041: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0046: ldloca.s V_1
IL_0048: ldloc.0
IL_0049: ldc.i4.2
IL_004a: ldstr ""Y""
IL_004f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0054: ldc.i4.1
IL_0055: br.s IL_0058
IL_0057: ldc.i4.0
IL_0058: pop
IL_0059: ldloca.s V_1
IL_005b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0060: call ""void System.Console.WriteLine(string)""
IL_0065: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 109 (0x6d)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_005e
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: brfalse.s IL_005e
IL_0026: ldloca.s V_1
IL_0028: ldloc.0
IL_0029: ldc.i4.0
IL_002a: ldnull
IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0030: brfalse.s IL_005e
IL_0032: ldloca.s V_1
IL_0034: ldloc.0
IL_0035: ldc.i4.1
IL_0036: ldnull
IL_0037: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_003c: brfalse.s IL_005e
IL_003e: ldloca.s V_1
IL_0040: ldloc.0
IL_0041: ldc.i4.0
IL_0042: ldstr ""X""
IL_0047: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_004c: brfalse.s IL_005e
IL_004e: ldloca.s V_1
IL_0050: ldloc.0
IL_0051: ldc.i4.2
IL_0052: ldstr ""Y""
IL_0057: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_005c: br.s IL_005f
IL_005e: ldc.i4.0
IL_005f: pop
IL_0060: ldloca.s V_1
IL_0062: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0067: call ""void System.Console.WriteLine(string)""
IL_006c: ret
}
",
};
}
[Theory]
[InlineData(@"$""base{Throw()}{a = 2}""")]
[InlineData(@"$""base"" + $""{Throw()}"" + $""{a = 2}""")]
public void BoolReturns_ShortCircuit(string expression)
{
var source = @"
using System;
int a = 1;
Console.Write(" + expression + @");
Console.WriteLine(a);
string Throw() => throw new Exception();";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true, returnExpression: "false");
CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
base
1");
}
[Theory]
[CombinatorialData]
public void BoolOutParameter_ShortCircuits(bool useBoolReturns,
[CombinatorialValues(@"$""{Throw()}{a = 2}""", @"$""{Throw()}"" + $""{a = 2}""")] string expression)
{
var source = @"
using System;
int a = 1;
Console.WriteLine(a);
Console.WriteLine(" + expression + @");
Console.WriteLine(a);
string Throw() => throw new Exception();
";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: useBoolReturns, constructorBoolArg: true, constructorSuccessResult: false);
CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
1
1");
}
[Theory]
[InlineData(@"$""base{await Hole()}""")]
[InlineData(@"$""base"" + $""{await Hole()}""")]
public void AwaitInHoles_UsesFormat(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
Console.WriteLine(" + expression + @");
Task<int> Hole() => Task.FromResult(1);";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1");
verifier.VerifyIL("<Program>$.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", !expression.Contains("+") ? @"
{
// Code size 164 (0xa4)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_003e
IL_000a: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__Hole|0_0()""
IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.0
IL_0022: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_002e: ldarg.0
IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)""
IL_003c: leave.s IL_00a3
IL_003e: ldarg.0
IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_0044: stloc.2
IL_0045: ldarg.0
IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: dup
IL_0054: stloc.0
IL_0055: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_005a: ldloca.s V_2
IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0061: stloc.1
IL_0062: ldstr ""base{0}""
IL_0067: ldloc.1
IL_0068: box ""int""
IL_006d: call ""string string.Format(string, object)""
IL_0072: call ""void System.Console.WriteLine(string)""
IL_0077: leave.s IL_0090
}
catch System.Exception
{
IL_0079: stloc.3
IL_007a: ldarg.0
IL_007b: ldc.i4.s -2
IL_007d: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0082: ldarg.0
IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0088: ldloc.3
IL_0089: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_008e: leave.s IL_00a3
}
IL_0090: ldarg.0
IL_0091: ldc.i4.s -2
IL_0093: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0098: ldarg.0
IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00a3: ret
}
"
: @"
{
// Code size 174 (0xae)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_003e
IL_000a: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__Hole|0_0()""
IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.0
IL_0022: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_002e: ldarg.0
IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)""
IL_003c: leave.s IL_00ad
IL_003e: ldarg.0
IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_0044: stloc.2
IL_0045: ldarg.0
IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: dup
IL_0054: stloc.0
IL_0055: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_005a: ldloca.s V_2
IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0061: stloc.1
IL_0062: ldstr ""base""
IL_0067: ldstr ""{0}""
IL_006c: ldloc.1
IL_006d: box ""int""
IL_0072: call ""string string.Format(string, object)""
IL_0077: call ""string string.Concat(string, string)""
IL_007c: call ""void System.Console.WriteLine(string)""
IL_0081: leave.s IL_009a
}
catch System.Exception
{
IL_0083: stloc.3
IL_0084: ldarg.0
IL_0085: ldc.i4.s -2
IL_0087: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_008c: ldarg.0
IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0092: ldloc.3
IL_0093: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0098: leave.s IL_00ad
}
IL_009a: ldarg.0
IL_009b: ldc.i4.s -2
IL_009d: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_00a2: ldarg.0
IL_00a3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_00a8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00ad: ret
}");
}
[Theory]
[InlineData(@"$""base{hole}""")]
[InlineData(@"$""base"" + $""{hole}""")]
public void NoAwaitInHoles_UsesBuilder(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
var hole = await Hole();
Console.WriteLine(" + expression + @");
Task<int> Hole() => Task.FromResult(1);";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
base
value:1");
verifier.VerifyIL("<Program>$.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 185 (0xb9)
.maxstack 3
.locals init (int V_0,
int V_1, //hole
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_003e
IL_000a: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__Hole|0_0()""
IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.0
IL_0022: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_002e: ldarg.0
IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)""
IL_003c: leave.s IL_00b8
IL_003e: ldarg.0
IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_0044: stloc.2
IL_0045: ldarg.0
IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: dup
IL_0054: stloc.0
IL_0055: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_005a: ldloca.s V_2
IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0061: stloc.1
IL_0062: ldc.i4.4
IL_0063: ldc.i4.1
IL_0064: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0069: stloc.3
IL_006a: ldloca.s V_3
IL_006c: ldstr ""base""
IL_0071: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0076: ldloca.s V_3
IL_0078: ldloc.1
IL_0079: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_007e: ldloca.s V_3
IL_0080: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0085: call ""void System.Console.WriteLine(string)""
IL_008a: leave.s IL_00a5
}
catch System.Exception
{
IL_008c: stloc.s V_4
IL_008e: ldarg.0
IL_008f: ldc.i4.s -2
IL_0091: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0096: ldarg.0
IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_009c: ldloc.s V_4
IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_00a3: leave.s IL_00b8
}
IL_00a5: ldarg.0
IL_00a6: ldc.i4.s -2
IL_00a8: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_00ad: ldarg.0
IL_00ae: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_00b3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00b8: ret
}
");
}
[Theory]
[InlineData(@"$""base{hole}""")]
[InlineData(@"$""base"" + $""{hole}""")]
public void NoAwaitInHoles_AwaitInExpression_UsesBuilder(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
var hole = 2;
Test(await M(1), " + expression + @", await M(3));
void Test(int i1, string s, int i2) => Console.WriteLine(s);
Task<int> M(int i)
{
Console.WriteLine(i);
return Task.FromResult(1);
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
1
3
base
value:2");
verifier.VerifyIL("<Program>$.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 328 (0x148)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0050
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq IL_00dc
IL_0011: ldarg.0
IL_0012: ldc.i4.2
IL_0013: stfld ""int <Program>$.<<Main>$>d__0.<hole>5__2""
IL_0018: ldc.i4.1
IL_0019: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__M|0_1(int)""
IL_001e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0023: stloc.2
IL_0024: ldloca.s V_2
IL_0026: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_002b: brtrue.s IL_006c
IL_002d: ldarg.0
IL_002e: ldc.i4.0
IL_002f: dup
IL_0030: stloc.0
IL_0031: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0036: ldarg.0
IL_0037: ldloc.2
IL_0038: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_003d: ldarg.0
IL_003e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0043: ldloca.s V_2
IL_0045: ldarg.0
IL_0046: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)""
IL_004b: leave IL_0147
IL_0050: ldarg.0
IL_0051: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_0056: stloc.2
IL_0057: ldarg.0
IL_0058: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_005d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0063: ldarg.0
IL_0064: ldc.i4.m1
IL_0065: dup
IL_0066: stloc.0
IL_0067: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_006c: ldarg.0
IL_006d: ldloca.s V_2
IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0074: stfld ""int <Program>$.<<Main>$>d__0.<>7__wrap2""
IL_0079: ldarg.0
IL_007a: ldc.i4.4
IL_007b: ldc.i4.1
IL_007c: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0081: stloc.3
IL_0082: ldloca.s V_3
IL_0084: ldstr ""base""
IL_0089: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_008e: ldloca.s V_3
IL_0090: ldarg.0
IL_0091: ldfld ""int <Program>$.<<Main>$>d__0.<hole>5__2""
IL_0096: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_009b: ldloca.s V_3
IL_009d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_00a2: stfld ""string <Program>$.<<Main>$>d__0.<>7__wrap3""
IL_00a7: ldc.i4.3
IL_00a8: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__M|0_1(int)""
IL_00ad: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_00b2: stloc.2
IL_00b3: ldloca.s V_2
IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_00ba: brtrue.s IL_00f8
IL_00bc: ldarg.0
IL_00bd: ldc.i4.1
IL_00be: dup
IL_00bf: stloc.0
IL_00c0: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_00c5: ldarg.0
IL_00c6: ldloc.2
IL_00c7: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_00cc: ldarg.0
IL_00cd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_00d2: ldloca.s V_2
IL_00d4: ldarg.0
IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)""
IL_00da: leave.s IL_0147
IL_00dc: ldarg.0
IL_00dd: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_00e2: stloc.2
IL_00e3: ldarg.0
IL_00e4: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1""
IL_00e9: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_00ef: ldarg.0
IL_00f0: ldc.i4.m1
IL_00f1: dup
IL_00f2: stloc.0
IL_00f3: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_00f8: ldloca.s V_2
IL_00fa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_00ff: stloc.1
IL_0100: ldarg.0
IL_0101: ldfld ""int <Program>$.<<Main>$>d__0.<>7__wrap2""
IL_0106: ldarg.0
IL_0107: ldfld ""string <Program>$.<<Main>$>d__0.<>7__wrap3""
IL_010c: ldloc.1
IL_010d: call ""void <Program>$.<<Main>$>g__Test|0_0(int, string, int)""
IL_0112: ldarg.0
IL_0113: ldnull
IL_0114: stfld ""string <Program>$.<<Main>$>d__0.<>7__wrap3""
IL_0119: leave.s IL_0134
}
catch System.Exception
{
IL_011b: stloc.s V_4
IL_011d: ldarg.0
IL_011e: ldc.i4.s -2
IL_0120: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_0125: ldarg.0
IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_012b: ldloc.s V_4
IL_012d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0132: leave.s IL_0147
}
IL_0134: ldarg.0
IL_0135: ldc.i4.s -2
IL_0137: stfld ""int <Program>$.<<Main>$>d__0.<>1__state""
IL_013c: ldarg.0
IL_013d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder""
IL_0142: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0147: ret
}
");
}
[Fact]
public void MissingCreate_01()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public override string ToString() => throw null;
public void Dispose() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5)
);
}
[Fact]
public void MissingCreate_02()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength) => throw null;
public override string ToString() => throw null;
public void Dispose() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5)
);
}
[Fact]
public void MissingCreate_03()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(ref int literalLength, int formattedCount) => throw null;
public override string ToString() => throw null;
public void Dispose() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS1620: Argument 1 must be passed with the 'ref' keyword
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{(object)1}""").WithArguments("1", "ref").WithLocation(1, 5)
);
}
[Theory]
[InlineData(null)]
[InlineData("public string ToStringAndClear(int literalLength) => throw null;")]
[InlineData("public void ToStringAndClear() => throw null;")]
[InlineData("public static string ToStringAndClear() => throw null;")]
public void MissingWellKnownMethod_ToStringAndClear(string toStringAndClearMethod)
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
" + toStringAndClearMethod + @"
public override string ToString() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics(
// (1,5): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear'
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "ToStringAndClear").WithLocation(1, 5)
);
}
[Fact]
public void ObsoleteCreateMethod()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
[System.Obsolete(""Constructor is obsolete"", error: true)]
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
public void Dispose() => throw null;
public override string ToString() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS0619: 'DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)' is obsolete: 'Constructor is obsolete'
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)", "Constructor is obsolete").WithLocation(1, 5)
);
}
[Fact]
public void ObsoleteAppendLiteralMethod()
{
var code = @"_ = $""base{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
public void Dispose() => throw null;
public override string ToString() => throw null;
[System.Obsolete(""AppendLiteral is obsolete"", error: true)]
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,7): error CS0619: 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is obsolete: 'AppendLiteral is obsolete'
// _ = $"base{(object)1}";
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "base").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "AppendLiteral is obsolete").WithLocation(1, 7)
);
}
[Fact]
public void ObsoleteAppendFormattedMethod()
{
var code = @"_ = $""base{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
public void Dispose() => throw null;
public override string ToString() => throw null;
public void AppendLiteral(string value) => throw null;
[System.Obsolete(""AppendFormatted is obsolete"", error: true)]
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,11): error CS0619: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is obsolete: 'AppendFormatted is obsolete'
// _ = $"base{(object)1}";
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)", "AppendFormatted is obsolete").WithLocation(1, 11)
);
}
private const string UnmanagedCallersOnlyIl = @"
.class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = (
01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72
69 74 65 64 00
)
.field public class [mscorlib]System.Type[] CallConvs
.field public string EntryPoint
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Attribute::.ctor()
ret
}
}";
[Fact]
public void UnmanagedCallersOnlyAppendFormattedMethod()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
.class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = (
01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d
62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65
73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72
74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73
69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70
69 6c 65 72 2e 01 00 00
)
.pack 0
.size 1
.method public hidebysig specialname rtspecialname
instance void .ctor (
int32 literalLength,
int32 formattedCount
) cil managed
{
ldnull
throw
}
.method public hidebysig
instance void Dispose () cil managed
{
ldnull
throw
}
.method public hidebysig virtual
instance string ToString () cil managed
{
ldnull
throw
}
.method public hidebysig
instance void AppendLiteral (
string 'value'
) cil managed
{
ldnull
throw
}
.method public hidebysig
instance void AppendFormatted<T> (
!!T hole,
[opt] int32 'alignment',
[opt] string format
) cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
.param [2] = int32(0)
.param [3] = nullref
ldnull
throw
}
}
";
var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl);
comp.VerifyDiagnostics(
// (1,7): error CS0570: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is not supported by the language
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BindToBogus, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)").WithLocation(1, 7)
);
}
[Fact]
public void UnmanagedCallersOnlyToStringMethod()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
.class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = (
01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d
62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65
73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72
74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73
69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70
69 6c 65 72 2e 01 00 00
)
.pack 0
.size 1
.method public hidebysig specialname rtspecialname
instance void .ctor (
int32 literalLength,
int32 formattedCount
) cil managed
{
ldnull
throw
}
.method public hidebysig instance string ToStringAndClear () cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
}
.method public hidebysig
instance void AppendLiteral (
string 'value'
) cil managed
{
ldnull
throw
}
.method public hidebysig
instance void AppendFormatted<T> (
!!T hole,
[opt] int32 'alignment',
[opt] string format
) cil managed
{
.param [2] = int32(0)
.param [3] = nullref
ldnull
throw
}
}
";
var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl);
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics(
// (1,5): error CS0570: 'DefaultInterpolatedStringHandler.ToStringAndClear()' is not supported by the language
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BindToBogus, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()").WithLocation(1, 5)
);
}
[Theory]
[InlineData(@"$""{i}{s}""")]
[InlineData(@"$""{i}"" + $""{s}""")]
public void UnsupportedArgumentType(string expression)
{
var source = @"
unsafe
{
int* i = null;
var s = new S();
_ = " + expression + @";
}
ref struct S
{
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: true, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (6,11): error CS0306: The type 'int*' may not be used as a type argument
// _ = $"{i}{s}";
Diagnostic(ErrorCode.ERR_BadTypeArgument, "{i}").WithArguments("int*").WithLocation(6, 11),
// (6,14): error CS0306: The type 'S' may not be used as a type argument
// _ = $"{i}{s}";
Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(6, 5 + expression.Length)
);
}
[Theory]
[InlineData(@"$""{b switch { true => 1, false => null }}{(!b ? null : 2)}{default}{null}""")]
[InlineData(@"$""{b switch { true => 1, false => null }}"" + $""{(!b ? null : 2)}"" + $""{default}"" + $""{null}""")]
public void TargetTypedInterpolationHoles(string expression)
{
var source = @"
bool b = true;
System.Console.WriteLine(" + expression + @");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
value:1
value:2
value:
value:");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 81 (0x51)
.maxstack 3
.locals init (bool V_0, //b
object V_1,
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_2
IL_0004: ldc.i4.0
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0017
IL_000e: ldc.i4.1
IL_000f: box ""int""
IL_0014: stloc.1
IL_0015: br.s IL_0019
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: ldloca.s V_2
IL_001b: ldloc.1
IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)""
IL_0021: ldloca.s V_2
IL_0023: ldloc.0
IL_0024: brfalse.s IL_002e
IL_0026: ldc.i4.2
IL_0027: box ""int""
IL_002c: br.s IL_002f
IL_002e: ldnull
IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)""
IL_0034: ldloca.s V_2
IL_0036: ldnull
IL_0037: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_003c: ldloca.s V_2
IL_003e: ldnull
IL_003f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0044: ldloca.s V_2
IL_0046: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_004b: call ""void System.Console.WriteLine(string)""
IL_0050: ret
}
");
}
[Theory]
[InlineData(@"$""{(null, default)}{new()}""")]
[InlineData(@"$""{(null, default)}"" + $""{new()}""")]
public void TargetTypedInterpolationHoles_Errors(string expression)
{
var source = @"System.Console.WriteLine(" + expression + @");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,29): error CS1503: Argument 1: cannot convert from '(<null>, default)' to 'object'
// System.Console.WriteLine($"{(null, default)}{new()}");
Diagnostic(ErrorCode.ERR_BadArgType, "(null, default)").WithArguments("1", "(<null>, default)", "object").WithLocation(1, 29),
// (1,29): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// System.Console.WriteLine($"{(null, default)}{new()}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(null, default)").WithArguments("interpolated string handlers", "10.0").WithLocation(1, 29),
// (1,46): error CS1729: 'string' does not contain a constructor that takes 0 arguments
// System.Console.WriteLine($"{(null, default)}{new()}");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(1, 19 + expression.Length)
);
}
[Fact]
public void RefTernary()
{
var source = @"
bool b = true;
int i = 1;
System.Console.WriteLine($""{(!b ? ref i : ref i)}"");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1");
}
[Fact]
public void NestedInterpolatedStrings_01()
{
var source = @"
int i = 1;
System.Console.WriteLine($""{$""{i}""}"");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (int V_0, //i
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.0
IL_0005: ldc.i4.1
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldloc.0
IL_000e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0013: ldloca.s V_1
IL_0015: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_001a: call ""void System.Console.WriteLine(string)""
IL_001f: ret
}
");
}
[Theory]
[InlineData(@"$""{$""{i1}""}{$""{i2}""}""")]
[InlineData(@"$""{$""{i1}""}"" + $""{$""{i2}""}""")]
public void NestedInterpolatedStrings_02(string expression)
{
var source = @"
int i1 = 1;
int i2 = 2;
System.Console.WriteLine(" + expression + @");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
value:1
value:2");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 63 (0x3f)
.maxstack 4
.locals init (int V_0, //i1
int V_1, //i2
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldloca.s V_2
IL_0006: ldc.i4.0
IL_0007: ldc.i4.1
IL_0008: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000d: ldloca.s V_2
IL_000f: ldloc.0
IL_0010: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0015: ldloca.s V_2
IL_0017: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_001c: ldloca.s V_2
IL_001e: ldc.i4.0
IL_001f: ldc.i4.1
IL_0020: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0025: ldloca.s V_2
IL_0027: ldloc.1
IL_0028: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_002d: ldloca.s V_2
IL_002f: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0034: call ""string string.Concat(string, string)""
IL_0039: call ""void System.Console.WriteLine(string)""
IL_003e: ret
}
");
}
[Fact]
public void ExceptionFilter_01()
{
var source = @"
using System;
int i = 1;
try
{
Console.WriteLine(""Starting try"");
throw new MyException { Prop = i };
}
// Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace
catch (MyException e) when (e.ToString() == $""{i}"".Trim())
{
Console.WriteLine(""Caught"");
}
class MyException : Exception
{
public int Prop { get; set; }
public override string ToString() => ""value:"" + Prop.ToString();
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
Starting try
Caught");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 95 (0x5f)
.maxstack 4
.locals init (int V_0, //i
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
.try
{
IL_0002: ldstr ""Starting try""
IL_0007: call ""void System.Console.WriteLine(string)""
IL_000c: newobj ""MyException..ctor()""
IL_0011: dup
IL_0012: ldloc.0
IL_0013: callvirt ""void MyException.Prop.set""
IL_0018: throw
}
filter
{
IL_0019: isinst ""MyException""
IL_001e: dup
IL_001f: brtrue.s IL_0025
IL_0021: pop
IL_0022: ldc.i4.0
IL_0023: br.s IL_004f
IL_0025: callvirt ""string object.ToString()""
IL_002a: ldloca.s V_1
IL_002c: ldc.i4.0
IL_002d: ldc.i4.1
IL_002e: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0033: ldloca.s V_1
IL_0035: ldloc.0
IL_0036: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_003b: ldloca.s V_1
IL_003d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0042: callvirt ""string string.Trim()""
IL_0047: call ""bool string.op_Equality(string, string)""
IL_004c: ldc.i4.0
IL_004d: cgt.un
IL_004f: endfilter
} // end filter
{ // handler
IL_0051: pop
IL_0052: ldstr ""Caught""
IL_0057: call ""void System.Console.WriteLine(string)""
IL_005c: leave.s IL_005e
}
IL_005e: ret
}
");
}
[ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))]
public void ExceptionFilter_02()
{
var source = @"
using System;
ReadOnlySpan<char> s = new char[] { 'i' };
try
{
Console.WriteLine(""Starting try"");
throw new MyException { Prop = s.ToString() };
}
// Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace
catch (MyException e) when (e.ToString() == $""{s}"".Trim())
{
Console.WriteLine(""Caught"");
}
class MyException : Exception
{
public string Prop { get; set; }
public override string ToString() => ""value:"" + Prop.ToString();
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp, expectedOutput: @"
Starting try
Caught");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 122 (0x7a)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //s
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: newarr ""char""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.s 105
IL_000a: stelem.i2
IL_000b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(char[])""
IL_0010: stloc.0
.try
{
IL_0011: ldstr ""Starting try""
IL_0016: call ""void System.Console.WriteLine(string)""
IL_001b: newobj ""MyException..ctor()""
IL_0020: dup
IL_0021: ldloca.s V_0
IL_0023: constrained. ""System.ReadOnlySpan<char>""
IL_0029: callvirt ""string object.ToString()""
IL_002e: callvirt ""void MyException.Prop.set""
IL_0033: throw
}
filter
{
IL_0034: isinst ""MyException""
IL_0039: dup
IL_003a: brtrue.s IL_0040
IL_003c: pop
IL_003d: ldc.i4.0
IL_003e: br.s IL_006a
IL_0040: callvirt ""string object.ToString()""
IL_0045: ldloca.s V_1
IL_0047: ldc.i4.0
IL_0048: ldc.i4.1
IL_0049: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_004e: ldloca.s V_1
IL_0050: ldloc.0
IL_0051: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_0056: ldloca.s V_1
IL_0058: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005d: callvirt ""string string.Trim()""
IL_0062: call ""bool string.op_Equality(string, string)""
IL_0067: ldc.i4.0
IL_0068: cgt.un
IL_006a: endfilter
} // end filter
{ // handler
IL_006c: pop
IL_006d: ldstr ""Caught""
IL_0072: call ""void System.Console.WriteLine(string)""
IL_0077: leave.s IL_0079
}
IL_0079: ret
}
");
}
[ConditionalTheory(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))]
[InlineData(@"$""{s}{c}""")]
[InlineData(@"$""{s}"" + $""{c}""")]
public void ImplicitUserDefinedConversionInHole(string expression)
{
var source = @"
using System;
S s = default;
C c = new C();
Console.WriteLine(" + expression + @");
ref struct S
{
public static implicit operator ReadOnlySpan<char>(S s) => ""S converted"";
}
class C
{
public static implicit operator ReadOnlySpan<char>(C s) => ""C converted"";
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder },
targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:S converted
value:C");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 57 (0x39)
.maxstack 3
.locals init (S V_0, //s
C V_1, //c
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: newobj ""C..ctor()""
IL_000d: stloc.1
IL_000e: ldloca.s V_2
IL_0010: ldc.i4.0
IL_0011: ldc.i4.2
IL_0012: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0017: ldloca.s V_2
IL_0019: ldloc.0
IL_001a: call ""System.ReadOnlySpan<char> S.op_Implicit(S)""
IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_0024: ldloca.s V_2
IL_0026: ldloc.1
IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<C>(C)""
IL_002c: ldloca.s V_2
IL_002e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0033: call ""void System.Console.WriteLine(string)""
IL_0038: ret
}
");
}
[Fact]
public void ExplicitUserDefinedConversionInHole()
{
var source = @"
using System;
S s = default;
Console.WriteLine($""{s}"");
ref struct S
{
public static explicit operator ReadOnlySpan<char>(S s) => ""S converted"";
}
";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (5,21): error CS0306: The type 'S' may not be used as a type argument
// Console.WriteLine($"{s}");
Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(5, 21)
);
}
[Theory]
[InlineData(@"$""Text{1}""")]
[InlineData(@"$""Text"" + $""{1}""")]
public void ImplicitUserDefinedConversionInLiteral(string expression)
{
var source = @"
using System;
Console.WriteLine(" + expression + @");
public struct CustomStruct
{
public static implicit operator CustomStruct(string s) => new CustomStruct { S = s };
public string S { get; set; }
public override string ToString() => ""literal:"" + S;
}
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString());
public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString());
}
}";
var verifier = CompileAndVerify(source, expectedOutput: @"
literal:Text
value:1");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 52 (0x34)
.maxstack 3
.locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.1
IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldstr ""Text""
IL_0010: call ""CustomStruct CustomStruct.op_Implicit(string)""
IL_0015: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(CustomStruct)""
IL_001a: ldloca.s V_0
IL_001c: ldc.i4.1
IL_001d: box ""int""
IL_0022: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)""
IL_0027: ldloca.s V_0
IL_0029: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: ret
}
");
}
[Theory]
[InlineData(@"$""Text{1}""")]
[InlineData(@"$""Text"" + $""{1}""")]
public void ExplicitUserDefinedConversionInLiteral(string expression)
{
var source = @"
using System;
Console.WriteLine(" + expression + @");
public struct CustomStruct
{
public static explicit operator CustomStruct(string s) => new CustomStruct { S = s };
public string S { get; set; }
public override string ToString() => ""literal:"" + S;
}
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString());
public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,21): error CS1503: Argument 1: cannot convert from 'string' to 'CustomStruct'
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_BadArgType, "Text").WithArguments("1", "string", "CustomStruct").WithLocation(4, 21)
);
}
[Theory]
[InlineData(@"$""Text{1}""")]
[InlineData(@"$""Text"" + $""{1}""")]
public void InvalidBuilderReturnType(string expression)
{
var source = @"
using System;
Console.WriteLine(" + expression + @");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public int AppendLiteral(string s) => 0;
public int AppendFormatted(object o) => 0;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,21): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is malformed. It does not return 'void' or 'bool'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)").WithLocation(4, 21),
// (4,25): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' is malformed. It does not return 'void' or 'bool'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)").WithLocation(4, 15 + expression.Length)
);
}
[Theory]
[InlineData(@"$""Text{1}""", @"$""{1}Text""")]
[InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")]
public void MixedBuilderReturnTypes_01(string expression1, string expression2)
{
var source = @"
using System;
Console.WriteLine(" + expression1 + @");
Console.WriteLine(" + expression2 + @");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public bool AppendLiteral(string s) => true;
public void AppendFormatted(object o) { }
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'bool'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "bool").WithLocation(4, 15 + expression1.Length),
// (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'void'.
// Console.WriteLine($"{1}Text");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "void").WithLocation(5, 14 + expression2.Length)
);
}
[Theory]
[InlineData(@"$""Text{1}""", @"$""{1}Text""")]
[InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")]
public void MixedBuilderReturnTypes_02(string expression1, string expression2)
{
var source = @"
using System;
Console.WriteLine(" + expression1 + @");
Console.WriteLine(" + expression2 + @");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public void AppendLiteral(string s) { }
public bool AppendFormatted(object o) => true;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'void'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "void").WithLocation(4, 15 + expression1.Length),
// (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'bool'.
// Console.WriteLine($"{1}Text");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "bool").WithLocation(5, 14 + expression2.Length)
);
}
[Fact]
public void MixedBuilderReturnTypes_03()
{
var source = @"
using System;
Console.WriteLine($""{1}"");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public bool AppendLiteral(string s) => true;
public void AppendFormatted(object o)
{
_builder.AppendLine(""value:"" + o.ToString());
}
}
}";
CompileAndVerify(source, expectedOutput: "value:1");
}
[Fact]
public void MixedBuilderReturnTypes_04()
{
var source = @"
using System;
using System.Text;
using System.Runtime.CompilerServices;
Console.WriteLine((CustomHandler)$""l"");
[InterpolatedStringHandler]
public class CustomHandler
{
private readonly StringBuilder _builder;
public CustomHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public override string ToString() => _builder.ToString();
public bool AppendFormatted(object o) => true;
public void AppendLiteral(string s)
{
_builder.AppendLine(""literal:"" + s.ToString());
}
}
";
CompileAndVerify(new[] { source, InterpolatedStringHandlerAttribute }, expectedOutput: "literal:l");
}
private static void VerifyInterpolatedStringExpression(CSharpCompilation comp, string handlerType = "CustomHandler")
{
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var descendentNodes = tree.GetRoot().DescendantNodes();
var interpolatedString =
(ExpressionSyntax)descendentNodes.OfType<BinaryExpressionSyntax>()
.Where(b => b.DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().Any())
.FirstOrDefault()
?? descendentNodes.OfType<InterpolatedStringExpressionSyntax>().Single();
var semanticInfo = model.GetSemanticInfoSummary(interpolatedString);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
Assert.Equal(handlerType, semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.InterpolatedStringHandler, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.ImplicitConversion.Exists);
Assert.True(semanticInfo.ImplicitConversion.IsValid);
Assert.True(semanticInfo.ImplicitConversion.IsInterpolatedStringHandler);
Assert.Null(semanticInfo.ImplicitConversion.Method);
if (interpolatedString is BinaryExpressionSyntax)
{
Assert.False(semanticInfo.ConstantValue.HasValue);
AssertEx.Equal("System.String System.String.op_Addition(System.String left, System.String right)", semanticInfo.Symbol.ToTestDisplayString());
}
// https://github.com/dotnet/roslyn/issues/54505 Assert IConversionOperation.IsImplicit when IOperation is implemented for interpolated strings.
}
private CompilationVerifier CompileAndVerifyOnCorrectPlatforms(CSharpCompilation compilation, string expectedOutput)
=> CompileAndVerify(
compilation,
expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null,
verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped);
[Theory]
[CombinatorialData]
public void CustomHandlerLocal([CombinatorialValues("class", "struct")] string type, bool useBoolReturns,
[CombinatorialValues(@"$""Literal{1,2:f}""", @"$""Literal"" + $""{1,2:f}""")] string expression)
{
var code = @"
CustomHandler builder = " + expression + @";
System.Console.WriteLine(builder.ToString());";
var builder = GetInterpolatedStringCustomHandlerType("CustomHandler", type, useBoolReturns);
var comp = CreateCompilation(new[] { code, builder });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
literal:Literal
value:1
alignment:2
format:f");
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (type, useBoolReturns) switch
{
(type: "struct", useBoolReturns: true) => @"
{
// Code size 67 (0x43)
.maxstack 4
.locals init (CustomHandler V_0, //builder
CustomHandler V_1)
IL_0000: ldloca.s V_1
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_1
IL_000b: ldstr ""Literal""
IL_0010: call ""bool CustomHandler.AppendLiteral(string)""
IL_0015: brfalse.s IL_002c
IL_0017: ldloca.s V_1
IL_0019: ldc.i4.1
IL_001a: box ""int""
IL_001f: ldc.i4.2
IL_0020: ldstr ""f""
IL_0025: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_002a: br.s IL_002d
IL_002c: ldc.i4.0
IL_002d: pop
IL_002e: ldloc.1
IL_002f: stloc.0
IL_0030: ldloca.s V_0
IL_0032: constrained. ""CustomHandler""
IL_0038: callvirt ""string object.ToString()""
IL_003d: call ""void System.Console.WriteLine(string)""
IL_0042: ret
}
",
(type: "struct", useBoolReturns: false) => @"
{
// Code size 61 (0x3d)
.maxstack 4
.locals init (CustomHandler V_0, //builder
CustomHandler V_1)
IL_0000: ldloca.s V_1
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_1
IL_000b: ldstr ""Literal""
IL_0010: call ""void CustomHandler.AppendLiteral(string)""
IL_0015: ldloca.s V_1
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: ldc.i4.2
IL_001e: ldstr ""f""
IL_0023: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0028: ldloc.1
IL_0029: stloc.0
IL_002a: ldloca.s V_0
IL_002c: constrained. ""CustomHandler""
IL_0032: callvirt ""string object.ToString()""
IL_0037: call ""void System.Console.WriteLine(string)""
IL_003c: ret
}
",
(type: "class", useBoolReturns: true) => @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""Literal""
IL_000e: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0013: brfalse.s IL_0029
IL_0015: ldloc.0
IL_0016: ldc.i4.1
IL_0017: box ""int""
IL_001c: ldc.i4.2
IL_001d: ldstr ""f""
IL_0022: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: callvirt ""string object.ToString()""
IL_0031: call ""void System.Console.WriteLine(string)""
IL_0036: ret
}
",
(type: "class", useBoolReturns: false) => @"
{
// Code size 47 (0x2f)
.maxstack 5
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldstr ""Literal""
IL_000d: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0012: dup
IL_0013: ldc.i4.1
IL_0014: box ""int""
IL_0019: ldc.i4.2
IL_001a: ldstr ""f""
IL_001f: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0024: callvirt ""string object.ToString()""
IL_0029: call ""void System.Console.WriteLine(string)""
IL_002e: ret
}
",
_ => throw ExceptionUtilities.Unreachable
};
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void CustomHandlerMethodArgument(string expression)
{
var code = @"
M(" + expression + @");
void M(CustomHandler b)
{
System.Console.WriteLine(b.ToString());
}";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", @"
{
// Code size 50 (0x32)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_0031: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"($""{1,2:f}"" + $""Literal"")")]
public void ExplicitHandlerCast_InCode(string expression)
{
var code = @"System.Console.WriteLine((CustomHandler)" + expression + @");";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) });
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
SyntaxNode syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single();
var semanticInfo = model.GetSemanticInfoSummary(syntax);
Assert.Equal("CustomHandler", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(SpecialType.System_Object, semanticInfo.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
syntax = ((CastExpressionSyntax)syntax).Expression;
Assert.Equal(expression, syntax.ToString());
semanticInfo = model.GetSemanticInfoSummary(syntax);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
Assert.Equal(SpecialType.System_String, semanticInfo.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
// https://github.com/dotnet/roslyn/issues/54505 Assert cast is explicit after IOperation is implemented
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 42 (0x2a)
.maxstack 5
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldc.i4.1
IL_0009: box ""int""
IL_000e: ldc.i4.2
IL_000f: ldstr ""f""
IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0019: dup
IL_001a: ldstr ""Literal""
IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0024: call ""void System.Console.WriteLine(object)""
IL_0029: ret
}
");
}
[Theory, WorkItem(55345, "https://github.com/dotnet/roslyn/issues/55345")]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void HandlerConversionPreferredOverStringForNonConstant(string expression)
{
var code = @"
CultureInfoNormalizer.Normalize();
C.M(" + expression + @");
class C
{
public static void M(CustomHandler b)
{
System.Console.WriteLine(b.ToString());
}
public static void M(string s)
{
System.Console.WriteLine(s);
}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.7
IL_0006: ldc.i4.1
IL_0007: newobj ""CustomHandler..ctor(int, int)""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldc.i4.1
IL_000f: box ""int""
IL_0014: ldc.i4.2
IL_0015: ldstr ""f""
IL_001a: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001f: brfalse.s IL_002e
IL_0021: ldloc.0
IL_0022: ldstr ""Literal""
IL_0027: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_002c: br.s IL_002f
IL_002e: ldc.i4.0
IL_002f: pop
IL_0030: ldloc.0
IL_0031: call ""void C.M(CustomHandler)""
IL_0036: ret
}
");
comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular9);
verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", expression.Contains('+') ? @"
{
// Code size 37 (0x25)
.maxstack 2
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldstr ""{0,2:f}""
IL_000a: ldc.i4.1
IL_000b: box ""int""
IL_0010: call ""string string.Format(string, object)""
IL_0015: ldstr ""Literal""
IL_001a: call ""string string.Concat(string, string)""
IL_001f: call ""void C.M(string)""
IL_0024: ret
}
"
: @"
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldstr ""{0,2:f}Literal""
IL_000a: ldc.i4.1
IL_000b: box ""int""
IL_0010: call ""string string.Format(string, object)""
IL_0015: call ""void C.M(string)""
IL_001a: ret
}
");
}
[Theory]
[InlineData(@"$""{""Literal""}""")]
[InlineData(@"$""{""Lit""}"" + $""{""eral""}""")]
public void StringPreferredOverHandlerConversionForConstant(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler b)
{
throw null;
}
public static void M(string s)
{
System.Console.WriteLine(s);
}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
var verifier = CompileAndVerify(comp, expectedOutput: @"Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""Literal""
IL_0005: call ""void C.M(string)""
IL_000a: ret
}
");
}
[Theory]
[InlineData(@"$""{1}{2}""")]
[InlineData(@"$""{1}"" + $""{2}""")]
public void HandlerConversionPreferredOverStringForNonConstant_AttributeConstructor(string expression)
{
var code = @"
using System;
[Attr(" + expression + @")]
class Attr : Attribute
{
public Attr(string s) {}
public Attr(CustomHandler c) {}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
comp.VerifyDiagnostics(
// (4,2): error CS0181: Attribute constructor parameter 'c' has type 'CustomHandler', which is not a valid attribute parameter type
// [Attr($"{1}{2}")]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("c", "CustomHandler").WithLocation(4, 2)
);
VerifyInterpolatedStringExpression(comp);
var attr = comp.SourceAssembly.SourceModule.GlobalNamespace.GetTypeMember("Attr");
Assert.Equal("Attr..ctor(CustomHandler c)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString());
}
[Theory]
[InlineData(@"$""{""Literal""}""")]
[InlineData(@"$""{""Lit""}"" + $""{""eral""}""")]
public void StringPreferredOverHandlerConversionForConstant_AttributeConstructor(string expression)
{
var code = @"
using System;
[Attr(" + expression + @")]
class Attr : Attribute
{
public Attr(string s) {}
public Attr(CustomHandler c) {}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate);
void validate(ModuleSymbol m)
{
var attr = m.GlobalNamespace.GetTypeMember("Attr");
Assert.Equal("Attr..ctor(System.String s)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString());
}
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void MultipleBuilderTypes(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler1 c) => throw null;
public static void M(CustomHandler2 c) => throw null;
}";
var comp = CreateCompilation(new[]
{
code,
GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false),
GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false)
});
comp.VerifyDiagnostics(
// (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(CustomHandler1)' and 'C.M(CustomHandler2)'
// C.M($"");
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(CustomHandler1)", "C.M(CustomHandler2)").WithLocation(2, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericOverloadResolution_01(string expression)
{
var code = @"
using System;
C.M(" + expression + @");
class C
{
public static void M<T>(T t) => throw null;
public static void M(CustomHandler c) => Console.WriteLine(c);
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 50 (0x32)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: call ""void C.M(CustomHandler)""
IL_0031: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericOverloadResolution_02(string expression)
{
var code = @"
using System;
C.M(" + expression + @");
class C
{
public static void M<T>(T t) where T : CustomHandler => throw null;
public static void M(CustomHandler c) => Console.WriteLine(c);
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 50 (0x32)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: call ""void C.M(CustomHandler)""
IL_0031: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericOverloadResolution_03(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M<T>(T t) where T : CustomHandler => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
comp.VerifyDiagnostics(
// (2,3): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(T)'. There is no implicit reference conversion from 'string' to 'CustomHandler'.
// C.M($"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(T)", "CustomHandler", "T", "string").WithLocation(2, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_01(string expression)
{
var code = @"
C.M(" + expression + @", default(CustomHandler));
C.M(default(CustomHandler), " + expression + @");
class C
{
public static void M<T>(T t1, T t2) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (2,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// C.M($"{1,2:f}Literal", default(CustomHandler));
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(2, 3),
// (3,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// C.M(default(CustomHandler), $"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_02(string expression)
{
var code = @"
using System;
C.M(default(CustomHandler), () => " + expression + @");
class C
{
public static void M<T>(T t1, Func<T> t2) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
comp.VerifyDiagnostics(
// (3,3): error CS0411: The type arguments for method 'C.M<T>(T, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// C.M(default(CustomHandler), () => $"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, System.Func<T>)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_03(string expression)
{
var code = @"
using System;
C.M(" + expression + @", default(CustomHandler));
class C
{
public static void M<T>(T t1, T t2) => Console.WriteLine(t1);
}
partial class CustomHandler
{
public static implicit operator CustomHandler(string s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 51 (0x33)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: ldnull
IL_002d: call ""void C.M<CustomHandler>(CustomHandler, CustomHandler)""
IL_0032: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_04(string expression)
{
var code = @"
using System;
C.M(default(CustomHandler), () => " + expression + @");
class C
{
public static void M<T>(T t1, Func<T> t2) => Console.WriteLine(t2());
}
partial class CustomHandler
{
public static implicit operator CustomHandler(string s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<Program>$.<>c.<<Main>$>b__0_0()", @"
{
// Code size 45 (0x2d)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_01(string expression)
{
var code = @"
using System;
Func<CustomHandler> f = () => " + expression + @";
Console.WriteLine(f());
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @"
{
// Code size 45 (0x2d)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_02(string expression)
{
var code = @"
using System;
CultureInfoNormalizer.Normalize();
C.M(() => " + expression + @");
class C
{
public static void M(Func<string> f) => Console.WriteLine(f());
public static void M(Func<CustomHandler> f) => throw null;
}
";
// Interpolated string handler conversions are not considered when determining the natural type of an expression: the natural return type of this lambda is string,
// so we don't even consider that there is a conversion from interpolated string expression to CustomHandler here (Sections 12.6.3.13 and 12.6.3.15 of the spec).
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
var verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal");
// No DefaultInterpolatedStringHandler was included in the compilation, so it falls back to string.Format
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", !expression.Contains('+') ? @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldstr ""{0,2:f}Literal""
IL_0005: ldc.i4.1
IL_0006: box ""int""
IL_000b: call ""string string.Format(string, object)""
IL_0010: ret
}
"
: @"
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: ldstr ""{0,2:f}""
IL_0005: ldc.i4.1
IL_0006: box ""int""
IL_000b: call ""string string.Format(string, object)""
IL_0010: ldstr ""Literal""
IL_0015: call ""string string.Concat(string, string)""
IL_001a: ret
}
");
}
[Theory]
[InlineData(@"$""{new S { Field = ""Field"" }}""")]
[InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")]
public void LambdaReturnInference_03(string expression)
{
// Same as 2, but using a type that isn't allowed in an interpolated string. There is an implicit conversion error on the ref struct
// when converting to a string, because S cannot be a component of an interpolated string. This conversion error causes the lambda to
// fail to bind as Func<string>, even though the natural return type is string, and the only successful bind is Func<CustomHandler>.
var code = @"
using System;
C.M(() => " + expression + @");
static class C
{
public static void M(Func<string> f) => throw null;
public static void M(Func<CustomHandler> f) => Console.WriteLine(f());
}
public partial class CustomHandler
{
public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field);
}
public ref struct S
{
public string Field { get; set; }
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field");
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @"
{
// Code size 35 (0x23)
.maxstack 4
.locals init (S V_0)
IL_0000: ldc.i4.0
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldloca.s V_0
IL_000a: initobj ""S""
IL_0010: ldloca.s V_0
IL_0012: ldstr ""Field""
IL_0017: call ""void S.Field.set""
IL_001c: ldloc.0
IL_001d: callvirt ""void CustomHandler.AppendFormatted(S)""
IL_0022: ret
}
");
}
[Theory]
[InlineData(@"$""{new S { Field = ""Field"" }}""")]
[InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")]
public void LambdaReturnInference_04(string expression)
{
// Same as 3, but with S added to DefaultInterpolatedStringHandler (which then allows the lambda to be bound as Func<string>, matching the natural return type)
var code = @"
using System;
C.M(() => " + expression + @");
static class C
{
public static void M(Func<string> f) => Console.WriteLine(f());
public static void M(Func<CustomHandler> f) => throw null;
}
public partial class CustomHandler
{
public void AppendFormatted(S value) => throw null;
}
public ref struct S
{
public string Field { get; set; }
}
namespace System.Runtime.CompilerServices
{
public ref partial struct DefaultInterpolatedStringHandler
{
public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field);
}
}
";
string[] source = new[] {
code,
GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false),
GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: true, useBoolReturns: false)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (3,11): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// C.M(() => $"{new S { Field = "Field" }}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, expression).WithArguments("interpolated string handlers", "10.0").WithLocation(3, 11),
// (3,14): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// C.M(() => $"{new S { Field = "Field" }}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"new S { Field = ""Field"" }").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 14)
);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field");
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0,
S V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldloca.s V_1
IL_000d: initobj ""S""
IL_0013: ldloca.s V_1
IL_0015: ldstr ""Field""
IL_001a: call ""void S.Field.set""
IL_001f: ldloc.1
IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(S)""
IL_0025: ldloca.s V_0
IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_05(string expression)
{
var code = @"
using System;
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => throw null;
public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false));
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0(bool)", @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_06(string expression)
{
// Same as 5, but with an implicit conversion from the builder type to string. This implicit conversion
// means that a best common type can be inferred for all branches of the lambda expression (Section 12.6.3.15 of the spec)
// and because there is a best common type, the inferred return type of the lambda is string. Since the inferred return type
// has an identity conversion to the return type of Func<bool, string>, that is preferred.
var code = @"
using System;
CultureInfoNormalizer.Normalize();
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => Console.WriteLine(f(false));
public static void M(Func<bool, CustomHandler> f) => throw null;
}
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0(bool)", !expression.Contains('+') ? @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0012
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0011: ret
IL_0012: ldstr ""{0,2:f}Literal""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: ret
}
"
: @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0012
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0011: ret
IL_0012: ldstr ""{0,2:f}""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: ldstr ""Literal""
IL_0027: call ""string string.Concat(string, string)""
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_07(string expression)
{
// Same as 5, but with an implicit conversion from string to the builder type.
var code = @"
using System;
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => Console.WriteLine(f(false));
public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false));
}
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0(bool)", @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_08(string expression)
{
// Same as 5, but with an implicit conversion from the builder type to string and from string to the builder type.
var code = @"
using System;
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => Console.WriteLine(f(false));
public static void M(Func<bool, CustomHandler> f) => throw null;
}
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
public static implicit operator CustomHandler(string c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Func<bool, string>)' and 'C.M(Func<bool, CustomHandler>)'
// C.M(b =>
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Func<bool, string>)", "C.M(System.Func<bool, CustomHandler>)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1}""")]
[InlineData(@"$""{1}"" + $""{2}""")]
public void LambdaInference_AmbiguousInOlderLangVersions(string expression)
{
var code = @"
using System;
C.M(param =>
{
param = " + expression + @";
});
static class C
{
public static void M(Action<string> f) => throw null;
public static void M(Action<CustomHandler> f) => throw null;
}
";
var source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) };
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
// This successful emit is being caused by https://github.com/dotnet/roslyn/issues/53761, along with the duplicate diagnostics in LambdaReturnInference_04
// We should not be changing binding behavior based on LangVersion.
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Action<string>)' and 'C.M(Action<CustomHandler>)'
// C.M(param =>
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Action<string>)", "C.M(System.Action<CustomHandler>)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_01(string expression)
{
var code = @"
using System;
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brtrue.s IL_0038
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: br.s IL_0041
IL_0038: ldloca.s V_0
IL_003a: initobj ""CustomHandler""
IL_0040: ldloc.0
IL_0041: box ""CustomHandler""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_02(string expression)
{
// Same as 01, but with a conversion from CustomHandler to string. The rules here are similar to LambdaReturnInference_06
var code = @"
using System;
CultureInfoNormalizer.Normalize();
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @"
{
// Code size 56 (0x38)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brtrue.s IL_0024
IL_0012: ldstr ""{0,2:f}Literal""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: br.s IL_0032
IL_0024: ldloca.s V_0
IL_0026: initobj ""CustomHandler""
IL_002c: ldloc.0
IL_002d: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0032: call ""void System.Console.WriteLine(string)""
IL_0037: ret
}
"
: @"
{
// Code size 66 (0x42)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brtrue.s IL_002e
IL_0012: ldstr ""{0,2:f}""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: ldstr ""Literal""
IL_0027: call ""string string.Concat(string, string)""
IL_002c: br.s IL_003c
IL_002e: ldloca.s V_0
IL_0030: initobj ""CustomHandler""
IL_0036: ldloc.0
IL_0037: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_003c: call ""void System.Console.WriteLine(string)""
IL_0041: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_03(string expression)
{
// Same as 02, but with a target-type
var code = @"
using System;
CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler'
// CustomHandler x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("string", "CustomHandler").WithLocation(4, 19)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_04(string expression)
{
// Same 01, but with a conversion from string to CustomHandler. The rules here are similar to LambdaReturnInference_07
var code = @"
using System;
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brtrue.s IL_0038
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: br.s IL_0041
IL_0038: ldloca.s V_0
IL_003a: initobj ""CustomHandler""
IL_0040: ldloc.0
IL_0041: box ""CustomHandler""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_05(string expression)
{
// Same 01, but with a conversion from string to CustomHandler and CustomHandler to string.
var code = @"
using System;
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,9): error CS0172: Type of conditional expression cannot be determined because 'CustomHandler' and 'string' implicitly convert to one another
// var x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal";
Diagnostic(ErrorCode.ERR_AmbigQM, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("CustomHandler", "string").WithLocation(4, 9)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_06(string expression)
{
// Same 05, but with a target type
var code = @"
using System;
CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => c.ToString();
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brtrue.s IL_0038
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: br.s IL_0041
IL_0038: ldloca.s V_0
IL_003a: initobj ""CustomHandler""
IL_0040: ldloc.0
IL_0041: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0046: call ""void System.Console.WriteLine(string)""
IL_004b: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_01(string expression)
{
// Switch expressions infer a best type based on _types_, not based on expressions (section 12.6.3.15 of the spec). Because this is based on types
// and not on expression conversions, no best type can be found for this switch expression.
var code = @"
using System;
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,29): error CS8506: No best type was found for the switch expression.
// var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_02(string expression)
{
// Same as 01, but with a conversion from CustomHandler. This allows the switch expression to infer a best-common type, which is string.
var code = @"
using System;
CultureInfoNormalizer.Normalize();
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @"
{
// Code size 59 (0x3b)
.maxstack 2
.locals init (string V_0,
CustomHandler V_1)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brfalse.s IL_0023
IL_0012: ldloca.s V_1
IL_0014: initobj ""CustomHandler""
IL_001a: ldloc.1
IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0020: stloc.0
IL_0021: br.s IL_0034
IL_0023: ldstr ""{0,2:f}Literal""
IL_0028: ldc.i4.1
IL_0029: box ""int""
IL_002e: call ""string string.Format(string, object)""
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: call ""void System.Console.WriteLine(string)""
IL_003a: ret
}
"
: @"
{
// Code size 69 (0x45)
.maxstack 2
.locals init (string V_0,
CustomHandler V_1)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brfalse.s IL_0023
IL_0012: ldloca.s V_1
IL_0014: initobj ""CustomHandler""
IL_001a: ldloc.1
IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0020: stloc.0
IL_0021: br.s IL_003e
IL_0023: ldstr ""{0,2:f}""
IL_0028: ldc.i4.1
IL_0029: box ""int""
IL_002e: call ""string string.Format(string, object)""
IL_0033: ldstr ""Literal""
IL_0038: call ""string string.Concat(string, string)""
IL_003d: stloc.0
IL_003e: ldloc.0
IL_003f: call ""void System.Console.WriteLine(string)""
IL_0044: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_03(string expression)
{
// Same 02, but with a target-type. The natural type will fail to compile, so the switch will use a target type (unlike TernaryTypes_03, which fails to compile).
var code = @"
using System;
CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => c.ToString();
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (CustomHandler V_0,
CustomHandler V_1)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brfalse.s IL_0019
IL_000d: ldloca.s V_1
IL_000f: initobj ""CustomHandler""
IL_0015: ldloc.1
IL_0016: stloc.0
IL_0017: br.s IL_0043
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.7
IL_001c: ldc.i4.1
IL_001d: call ""CustomHandler..ctor(int, int)""
IL_0022: ldloca.s V_1
IL_0024: ldc.i4.1
IL_0025: box ""int""
IL_002a: ldc.i4.2
IL_002b: ldstr ""f""
IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldstr ""Literal""
IL_003c: call ""void CustomHandler.AppendLiteral(string)""
IL_0041: ldloc.1
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0049: call ""void System.Console.WriteLine(string)""
IL_004e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_04(string expression)
{
// Same as 01, but with a conversion to CustomHandler. This allows the switch expression to infer a best-common type, which is CustomHandler.
var code = @"
using System;
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (CustomHandler V_0,
CustomHandler V_1)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brfalse.s IL_0019
IL_000d: ldloca.s V_1
IL_000f: initobj ""CustomHandler""
IL_0015: ldloc.1
IL_0016: stloc.0
IL_0017: br.s IL_0043
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.7
IL_001c: ldc.i4.1
IL_001d: call ""CustomHandler..ctor(int, int)""
IL_0022: ldloca.s V_1
IL_0024: ldc.i4.1
IL_0025: box ""int""
IL_002a: ldc.i4.2
IL_002b: ldstr ""f""
IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldstr ""Literal""
IL_003c: call ""void CustomHandler.AppendLiteral(string)""
IL_0041: ldloc.1
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: box ""CustomHandler""
IL_0049: call ""void System.Console.WriteLine(object)""
IL_004e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_05(string expression)
{
// Same as 01, but with conversions in both directions. No best common type can be found.
var code = @"
using System;
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,29): error CS8506: No best type was found for the switch expression.
// var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_06(string expression)
{
// Same as 05, but with a target type.
var code = @"
using System;
CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => c.ToString();
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (CustomHandler V_0,
CustomHandler V_1)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brfalse.s IL_0019
IL_000d: ldloca.s V_1
IL_000f: initobj ""CustomHandler""
IL_0015: ldloc.1
IL_0016: stloc.0
IL_0017: br.s IL_0043
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.7
IL_001c: ldc.i4.1
IL_001d: call ""CustomHandler..ctor(int, int)""
IL_0022: ldloca.s V_1
IL_0024: ldc.i4.1
IL_0025: box ""int""
IL_002a: ldc.i4.2
IL_002b: ldstr ""f""
IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldstr ""Literal""
IL_003c: call ""void CustomHandler.AppendLiteral(string)""
IL_0041: ldloc.1
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0049: call ""void System.Console.WriteLine(string)""
IL_004e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_01(string expression)
{
var code = @"
M(" + expression + @");
void M(ref CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 48 (0x30)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_0
IL_002a: call ""void <Program>$.<<Main>$>g__M|0_0(ref CustomHandler)""
IL_002f: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_02(string expression)
{
var code = @"
M(" + expression + @");
M(ref " + expression + @");
void M(ref CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (2,3): error CS1620: Argument 1 must be passed with the 'ref' keyword
// M($"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("1", "ref").WithLocation(2, 3),
// (3,7): error CS1510: A ref or out value must be an assignable variable
// M(ref $"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_RefLvalueExpected, expression).WithLocation(3, 7)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_03(string expression)
{
var code = @"
M(" + expression + @");
void M(in CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 45 (0x2d)
.maxstack 5
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldc.i4.1
IL_0009: box ""int""
IL_000e: ldc.i4.2
IL_000f: ldstr ""f""
IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0019: dup
IL_001a: ldstr ""Literal""
IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0024: stloc.0
IL_0025: ldloca.s V_0
IL_0027: call ""void <Program>$.<<Main>$>g__M|0_0(in CustomHandler)""
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_04(string expression)
{
var code = @"
M(" + expression + @");
void M(in CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 48 (0x30)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_0
IL_002a: call ""void <Program>$.<<Main>$>g__M|0_0(in CustomHandler)""
IL_002f: ret
}
");
}
[Theory]
[CombinatorialData]
public void RefOverloadResolution_Struct([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler c) => System.Console.WriteLine(c);
public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c);
}";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 47 (0x2f)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloc.0
IL_0029: call ""void C.M(CustomHandler)""
IL_002e: ret
}
");
}
[Theory]
[CombinatorialData]
public void RefOverloadResolution_Class([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler c) => System.Console.WriteLine(c);
public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c);
}";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 47 (0x2f)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloc.0
IL_0029: call ""void C.M(CustomHandler)""
IL_002e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void RefOverloadResolution_MultipleBuilderTypes(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler1 c) => System.Console.WriteLine(c);
public static void M(ref CustomHandler2 c) => throw null;
}";
var comp = CreateCompilation(new[]
{
code,
GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false),
GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false)
});
VerifyInterpolatedStringExpression(comp, "CustomHandler1");
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 47 (0x2f)
.maxstack 4
.locals init (CustomHandler1 V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler1..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler1.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler1.AppendLiteral(string)""
IL_0028: ldloc.0
IL_0029: call ""void C.M(CustomHandler1)""
IL_002e: ret
}
");
}
private const string InterpolatedStringHandlerAttributesVB = @"
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=False, Inherited:=False)>
Public NotInheritable Class InterpolatedStringHandlerAttribute
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=False, Inherited:=False)>
Public NotInheritable Class InterpolatedStringHandlerArgumentAttribute
Inherits Attribute
Public Sub New(argument As String)
Arguments = { argument }
End Sub
Public Sub New(ParamArray arguments() as String)
Me.Arguments = arguments
End Sub
Public ReadOnly Property Arguments As String()
End Class
End Namespace
";
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute });
comp.VerifyDiagnostics(
// (8,27): error CS8946: 'string' is not an interpolated string handler type.
// public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {}
Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("string").WithLocation(8, 27)
);
var sParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(sParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType_Metadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i as Integer, <InterpolatedStringHandlerArgument(""i"")> c As String)
End Sub
End Class
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
// Note: there is no compilation error here because the natural type of a string is still string, and
// we just bind to that method without checking the handler attribute.
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics();
var sParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(sParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_InvalidArgument(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (8,70): error CS1503: Argument 1: cannot convert from 'int' to 'string'
// public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(8, 70)
);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""NonExistant"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5),
// (8,27): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(CustomHandler)'.
// public static void M([InterpolatedStringHandlerArgumentAttribute("NonExistant")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant"")").WithArguments("NonExistant", "C.M(CustomHandler)").WithLocation(8, 27)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(""NonExistant"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(int, CustomHandler)'.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("i", "NonExistant")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")").WithArguments("NonExistant", "C.M(int, CustomHandler)").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""i"", ""NonExistant"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8945: 'NonExistant1' is not a valid parameter name from 'C.M(int, CustomHandler)'.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant1", "C.M(int, CustomHandler)").WithLocation(8, 34),
// (8,34): error CS8945: 'NonExistant2' is not a valid parameter name from 'C.M(int, CustomHandler)'.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant2", "C.M(int, CustomHandler)").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""NonExistant1"", ""NonExistant2"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ReferenceSelf(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""c"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8948: InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("c")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, @"InterpolatedStringHandlerArgumentAttribute(""c"")").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_ReferencesSelf_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(""c"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8943: null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, "InterpolatedStringHandlerArgumentAttribute(new string[] { null })").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_01()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing })> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_02()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing, ""i"" })> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_03()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(CStr(Nothing))> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5),
// (8,27): error CS8944: 'C.M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// public static void M([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.M(CustomHandler)").WithLocation(8, 27)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"{""""}")]
[InlineData(@"""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod_FromMetadata(string arg)
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
_ = new C(" + expression + @");
class C
{
public C([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// _ = new C($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 11),
// (8,15): error CS8944: 'C.C(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// public C([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.C(CustomHandler)").WithLocation(8, 15)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod(".ctor").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"{""""}")]
[InlineData(@"""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor_FromMetadata(string arg)
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Sub New(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"_ = new C($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// _ = new C($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 11),
// (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// _ = new C($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 11),
// (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// _ = new C($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 11)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod(".ctor").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerAttributeArgumentError_SubstitutedTypeSymbol(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C<CustomHandler>.M(" + expression + @");
public class C<T>
{
public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { }
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler });
comp.VerifyDiagnostics(
// (4,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 20),
// (8,27): error CS8946: 'T' is not an interpolated string handler type.
// public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { }
Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("T").WithLocation(8, 27)
);
var c = comp.SourceModule.GlobalNamespace.GetTypeMember("C");
var handler = comp.SourceModule.GlobalNamespace.GetTypeMember("CustomHandler");
var substitutedC = c.WithTypeArguments(ImmutableArray.Create(TypeWithAnnotations.Create(handler)));
var cParam = substitutedC.GetMethod("M").Parameters.Single();
Assert.IsType<SubstitutedParameterSymbol>(cParam);
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_SubstitutedTypeSymbol_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C(Of T)
Public Shared Sub M(<InterpolatedStringHandlerArgument()> c As T)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C<CustomHandler>.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 20),
// (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 20),
// (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 20)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C`1").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""text""", @"$""text"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
public class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var goodCode = @"
int i = 10;
C.M(i: i, c: " + expression + @");
";
var comp = CreateCompilation(new[] { code, goodCode, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"
i:10
literal:text
");
verifier.VerifyDiagnostics(
// (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller
// to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString());
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27)
);
verifyIL(verifier);
var badCode = @"C.M(" + expression + @", 1);";
comp = CreateCompilation(new[] { code, badCode, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (1,10): error CS8950: Parameter 'i' is an argument to the interpolated string handler conversion on parameter 'c', but is specified after the interpolated string constant. Reorder the arguments to move 'i' before 'c'.
// C.M($"", 1);
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, "1").WithArguments("i", "c").WithLocation(1, 7 + expression.Length),
// (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller
// to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString());
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27)
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.First();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
void verifyIL(CompilationVerifier verifier)
{
verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == ""
? @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init (int V_0,
int V_1,
CustomHandler V_2)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ldloca.s V_2
IL_0007: ldc.i4.4
IL_0008: ldc.i4.0
IL_0009: ldloc.0
IL_000a: call ""CustomHandler..ctor(int, int, int)""
IL_000f: ldloca.s V_2
IL_0011: ldstr ""text""
IL_0016: call ""bool CustomHandler.AppendLiteral(string)""
IL_001b: pop
IL_001c: ldloc.2
IL_001d: ldloc.1
IL_001e: call ""void C.M(CustomHandler, int)""
IL_0023: ret
}
"
: @"
{
// Code size 43 (0x2b)
.maxstack 4
.locals init (int V_0,
int V_1,
CustomHandler V_2,
bool V_3)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ldc.i4.4
IL_0006: ldc.i4.0
IL_0007: ldloc.0
IL_0008: ldloca.s V_3
IL_000a: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000f: stloc.2
IL_0010: ldloc.3
IL_0011: brfalse.s IL_0021
IL_0013: ldloca.s V_2
IL_0015: ldstr ""text""
IL_001a: call ""bool CustomHandler.AppendLiteral(string)""
IL_001f: br.s IL_0022
IL_0021: ldc.i4.0
IL_0022: pop
IL_0023: ldloc.2
IL_0024: ldloc.1
IL_0025: call ""void C.M(CustomHandler, int)""
IL_002a: ret
}
");
}
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(""i"")> c As CustomHandler, i As Integer)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation("", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics();
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.First();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_OptionalNotSpecifiedAtCallsite(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
public class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i = 0) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount)
{
}
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler });
comp.VerifyDiagnostics(
// (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5),
// (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { }
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ParamsNotSpecifiedAtCallsite(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
public class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, params int[] i) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int[] i) : this(literalLength, formattedCount)
{
}
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler });
comp.VerifyDiagnostics(
// (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5),
// (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { }
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MissingConstructor(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate).VerifyDiagnostics();
CreateCompilation(@"C.M(1, " + expression + @");", new[] { comp.ToMetadataReference() }).VerifyDiagnostics(
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8)
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_InaccessibleConstructor_01(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {}
}
public partial struct CustomHandler
{
private CustomHandler(int literalLength, int formattedCount, int i) : this() {}
static void InCustomHandler()
{
C.M(1, " + expression + @");
}
}
";
var executableCode = @"C.M(1, " + expression + @");";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8)
);
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics();
comp = CreateCompilation(executableCode, new[] { dependency.EmitToImageReference() });
comp.VerifyDiagnostics(
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
comp = CreateCompilation(executableCode, new[] { dependency.ToMetadataReference() });
comp.VerifyDiagnostics(
// (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8)
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
}
private void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes(string mRef, string customHandlerRef, string expression, params DiagnosticDescription[] expectedDiagnostics)
{
var code = @"
using System.Runtime.CompilerServices;
int i = 0;
C.M(" + mRef + @" i, " + expression + @");
public class C
{
public static void M(" + mRef + @" int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) { " + (mRef == "out" ? "i = 0;" : "") + @" }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, " + customHandlerRef + @" int i) : this() { " + (customHandlerRef == "out" ? "i = 0;" : "") + @" }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(expectedDiagnostics);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefNone(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "", expression,
// (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword
// C.M(ref i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefOut(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "out", expression,
// (5,9): error CS1620: Argument 3 must be passed with the 'out' keyword
// C.M(ref i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefIn(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "in", expression,
// (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword
// C.M(ref i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InNone(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "", expression,
// (5,8): error CS1615: Argument 3 may not be passed with the 'in' keyword
// C.M(in i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "in").WithLocation(5, 8));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InOut(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "out", expression,
// (5,8): error CS1620: Argument 3 must be passed with the 'out' keyword
// C.M(in i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 8));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InRef(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "ref", expression,
// (5,8): error CS1620: Argument 3 must be passed with the 'ref' keyword
// C.M(in i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 8));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutNone(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "", expression,
// (5,9): error CS1615: Argument 3 may not be passed with the 'out' keyword
// C.M(out i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "out").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutRef(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "ref", expression,
// (5,9): error CS1620: Argument 3 must be passed with the 'ref' keyword
// C.M(out i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneRef(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "ref", expression,
// (5,6): error CS1620: Argument 3 must be passed with the 'ref' keyword
// C.M( i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 6));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneOut(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "out", expression,
// (5,6): error CS1620: Argument 3 must be passed with the 'out' keyword
// C.M( i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 6));
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedType([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s" + extraConstructorArg + @") : this()
{
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var executableCode = @"C.M(1, " + expression + @");";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var expectedDiagnostics = extraConstructorArg == ""
? new DiagnosticDescription[]
{
// (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string'
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5)
}
: new DiagnosticDescription[]
{
// (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string'
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5),
// (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, string, out bool)'
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, string, out bool)").WithLocation(1, 8)
};
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(expectedDiagnostics);
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics();
foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() })
{
comp = CreateCompilation(executableCode, new[] { d });
comp.VerifyDiagnostics(expectedDiagnostics);
}
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_SingleArg([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""2""", @"$""2"" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static string M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) => c.ToString();
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var executableCode = @"
using System;
int i = 10;
Console.WriteLine(C.M(i, " + expression + @"));
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i:10
literal:2");
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() })
{
verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: @"
i:10
literal:2");
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
}
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
static void verifyIL(string extraConstructorArg, CompilationVerifier verifier)
{
verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == ""
? @"
{
// Code size 39 (0x27)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldloca.s V_1
IL_0006: ldc.i4.1
IL_0007: ldc.i4.0
IL_0008: ldloc.0
IL_0009: call ""CustomHandler..ctor(int, int, int)""
IL_000e: ldloca.s V_1
IL_0010: ldstr ""2""
IL_0015: call ""bool CustomHandler.AppendLiteral(string)""
IL_001a: pop
IL_001b: ldloc.1
IL_001c: call ""string C.M(int, CustomHandler)""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: ret
}
"
: @"
{
// Code size 46 (0x2e)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.1
IL_0005: ldc.i4.0
IL_0006: ldloc.0
IL_0007: ldloca.s V_2
IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000e: stloc.1
IL_000f: ldloc.2
IL_0010: brfalse.s IL_0020
IL_0012: ldloca.s V_1
IL_0014: ldstr ""2""
IL_0019: call ""bool CustomHandler.AppendLiteral(string)""
IL_001e: br.s IL_0021
IL_0020: ldc.i4.0
IL_0021: pop
IL_0022: ldloc.1
IL_0023: call ""string C.M(int, CustomHandler)""
IL_0028: call ""void System.Console.WriteLine(string)""
IL_002d: ret
}
");
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_MultipleArgs([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var executableCode = @"
int i = 10;
string s = ""arg"";
C.M(i, s, " + expression + @");
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
string expectedOutput = @"
i:10
s:arg
literal:literal
";
var verifier = base.CompileAndVerify((Compilation)comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() })
{
verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
}
static void validator(ModuleSymbol verifier)
{
var cParam = verifier.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
static void verifyIL(string extraConstructorArg, CompilationVerifier verifier)
{
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 44 (0x2c)
.maxstack 7
.locals init (string V_0, //s
int V_1,
string V_2,
CustomHandler V_3)
IL_0000: ldc.i4.s 10
IL_0002: ldstr ""arg""
IL_0007: stloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloc.0
IL_000b: stloc.2
IL_000c: ldloc.2
IL_000d: ldloca.s V_3
IL_000f: ldc.i4.7
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: ldloc.2
IL_0013: call ""CustomHandler..ctor(int, int, int, string)""
IL_0018: ldloca.s V_3
IL_001a: ldstr ""literal""
IL_001f: call ""bool CustomHandler.AppendLiteral(string)""
IL_0024: pop
IL_0025: ldloc.3
IL_0026: call ""void C.M(int, string, CustomHandler)""
IL_002b: ret
}
"
: @"
{
// Code size 52 (0x34)
.maxstack 7
.locals init (string V_0, //s
int V_1,
string V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.s 10
IL_0002: ldstr ""arg""
IL_0007: stloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloc.0
IL_000b: stloc.2
IL_000c: ldloc.2
IL_000d: ldc.i4.7
IL_000e: ldc.i4.0
IL_000f: ldloc.1
IL_0010: ldloc.2
IL_0011: ldloca.s V_4
IL_0013: newobj ""CustomHandler..ctor(int, int, int, string, out bool)""
IL_0018: stloc.3
IL_0019: ldloc.s V_4
IL_001b: brfalse.s IL_002b
IL_001d: ldloca.s V_3
IL_001f: ldstr ""literal""
IL_0024: call ""bool CustomHandler.AppendLiteral(string)""
IL_0029: br.s IL_002c
IL_002b: ldc.i4.0
IL_002c: pop
IL_002d: ldloc.3
IL_002e: call ""void C.M(int, string, CustomHandler)""
IL_0033: ret
}
");
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_RefKindsMatch([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 1;
string s = null;
object o;
C.M(i, ref s, out o, " + expression + @");
Console.WriteLine(s);
Console.WriteLine(o);
public class C
{
public static void M(in int i, ref string s, out object o, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"", ""o"")] CustomHandler c)
{
Console.WriteLine(s);
o = ""o in M"";
s = ""s in M"";
Console.Write(c.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, in int i, ref string s, out object o" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
o = null;
s = ""s in constructor"";
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
s in constructor
i:1
literal:literal
s in M
o in M
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 67 (0x43)
.maxstack 8
.locals init (int V_0, //i
string V_1, //s
object V_2, //o
int& V_3,
string& V_4,
object& V_5,
CustomHandler V_6)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: stloc.3
IL_0007: ldloc.3
IL_0008: ldloca.s V_1
IL_000a: stloc.s V_4
IL_000c: ldloc.s V_4
IL_000e: ldloca.s V_2
IL_0010: stloc.s V_5
IL_0012: ldloc.s V_5
IL_0014: ldc.i4.7
IL_0015: ldc.i4.0
IL_0016: ldloc.3
IL_0017: ldloc.s V_4
IL_0019: ldloc.s V_5
IL_001b: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object)""
IL_0020: stloc.s V_6
IL_0022: ldloca.s V_6
IL_0024: ldstr ""literal""
IL_0029: call ""bool CustomHandler.AppendLiteral(string)""
IL_002e: pop
IL_002f: ldloc.s V_6
IL_0031: call ""void C.M(in int, ref string, out object, CustomHandler)""
IL_0036: ldloc.1
IL_0037: call ""void System.Console.WriteLine(string)""
IL_003c: ldloc.2
IL_003d: call ""void System.Console.WriteLine(object)""
IL_0042: ret
}
"
: @"
{
// Code size 76 (0x4c)
.maxstack 9
.locals init (int V_0, //i
string V_1, //s
object V_2, //o
int& V_3,
string& V_4,
object& V_5,
CustomHandler V_6,
bool V_7)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: stloc.3
IL_0007: ldloc.3
IL_0008: ldloca.s V_1
IL_000a: stloc.s V_4
IL_000c: ldloc.s V_4
IL_000e: ldloca.s V_2
IL_0010: stloc.s V_5
IL_0012: ldloc.s V_5
IL_0014: ldc.i4.7
IL_0015: ldc.i4.0
IL_0016: ldloc.3
IL_0017: ldloc.s V_4
IL_0019: ldloc.s V_5
IL_001b: ldloca.s V_7
IL_001d: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object, out bool)""
IL_0022: stloc.s V_6
IL_0024: ldloc.s V_7
IL_0026: brfalse.s IL_0036
IL_0028: ldloca.s V_6
IL_002a: ldstr ""literal""
IL_002f: call ""bool CustomHandler.AppendLiteral(string)""
IL_0034: br.s IL_0037
IL_0036: ldc.i4.0
IL_0037: pop
IL_0038: ldloc.s V_6
IL_003a: call ""void C.M(in int, ref string, out object, CustomHandler)""
IL_003f: ldloc.1
IL_0040: call ""void System.Console.WriteLine(string)""
IL_0045: ldloc.2
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(3).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1, 2 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_ReorderedAttributePositions([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(GetInt(), GetString(), " + expression + @");
int GetInt()
{
Console.WriteLine(""GetInt"");
return 10;
}
string GetString()
{
Console.WriteLine(""GetString"");
return ""str"";
}
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""s:"" + s);
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
GetInt
GetString
s:str
i:10
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 45 (0x2d)
.maxstack 7
.locals init (string V_0,
int V_1,
CustomHandler V_2)
IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_1()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldloca.s V_2
IL_0010: ldc.i4.7
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: call ""CustomHandler..ctor(int, int, string, int)""
IL_0019: ldloca.s V_2
IL_001b: ldstr ""literal""
IL_0020: call ""bool CustomHandler.AppendLiteral(string)""
IL_0025: pop
IL_0026: ldloc.2
IL_0027: call ""void C.M(int, string, CustomHandler)""
IL_002c: ret
}
"
: @"
{
// Code size 52 (0x34)
.maxstack 7
.locals init (string V_0,
int V_1,
CustomHandler V_2,
bool V_3)
IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_1()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldc.i4.7
IL_000f: ldc.i4.0
IL_0010: ldloc.0
IL_0011: ldloc.1
IL_0012: ldloca.s V_3
IL_0014: newobj ""CustomHandler..ctor(int, int, string, int, out bool)""
IL_0019: stloc.2
IL_001a: ldloc.3
IL_001b: brfalse.s IL_002b
IL_001d: ldloca.s V_2
IL_001f: ldstr ""literal""
IL_0024: call ""bool CustomHandler.AppendLiteral(string)""
IL_0029: br.s IL_002c
IL_002b: ldc.i4.0
IL_002c: pop
IL_002d: ldloc.2
IL_002e: call ""void C.M(int, string, CustomHandler)""
IL_0033: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_ParametersReordered([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
GetC().M(s: GetString(), i: GetInt(), c: " + expression + @");
C GetC()
{
Console.WriteLine(""GetC"");
return new C { Field = 5 };
}
int GetInt()
{
Console.WriteLine(""GetInt"");
return 10;
}
string GetString()
{
Console.WriteLine(""GetString"");
return ""str"";
}
public class C
{
public int Field;
public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", """", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s, C c, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""s:"" + s);
_builder.AppendLine(""c.Field:"" + c.Field.ToString());
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
GetC
GetString
GetInt
s:str
c.Field:5
i:10
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 56 (0x38)
.maxstack 9
.locals init (string V_0,
C V_1,
int V_2,
string V_3,
CustomHandler V_4)
IL_0000: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_2()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.3
IL_000f: call ""int <Program>$.<<Main>$>g__GetInt|0_1()""
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldloc.3
IL_0017: ldloca.s V_4
IL_0019: ldc.i4.7
IL_001a: ldc.i4.0
IL_001b: ldloc.0
IL_001c: ldloc.1
IL_001d: ldloc.2
IL_001e: call ""CustomHandler..ctor(int, int, string, C, int)""
IL_0023: ldloca.s V_4
IL_0025: ldstr ""literal""
IL_002a: call ""bool CustomHandler.AppendLiteral(string)""
IL_002f: pop
IL_0030: ldloc.s V_4
IL_0032: callvirt ""void C.M(int, string, CustomHandler)""
IL_0037: ret
}
"
: @"
{
// Code size 65 (0x41)
.maxstack 9
.locals init (string V_0,
C V_1,
int V_2,
string V_3,
CustomHandler V_4,
bool V_5)
IL_0000: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_2()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.3
IL_000f: call ""int <Program>$.<<Main>$>g__GetInt|0_1()""
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldloc.3
IL_0017: ldc.i4.7
IL_0018: ldc.i4.0
IL_0019: ldloc.0
IL_001a: ldloc.1
IL_001b: ldloc.2
IL_001c: ldloca.s V_5
IL_001e: newobj ""CustomHandler..ctor(int, int, string, C, int, out bool)""
IL_0023: stloc.s V_4
IL_0025: ldloc.s V_5
IL_0027: brfalse.s IL_0037
IL_0029: ldloca.s V_4
IL_002b: ldstr ""literal""
IL_0030: call ""bool CustomHandler.AppendLiteral(string)""
IL_0035: br.s IL_0038
IL_0037: ldc.i4.0
IL_0038: pop
IL_0039: ldloc.s V_4
IL_003b: callvirt ""void C.M(int, string, CustomHandler)""
IL_0040: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 1, -1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_Duplicated([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(GetInt(), """", " + expression + @");
int GetInt()
{
Console.WriteLine(""GetInt"");
return 10;
}
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, int i2" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""i2:"" + i2.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
GetInt
i1:10
i2:10
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 43 (0x2b)
.maxstack 7
.locals init (int V_0,
CustomHandler V_1)
IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr """"
IL_000c: ldloca.s V_1
IL_000e: ldc.i4.7
IL_000f: ldc.i4.0
IL_0010: ldloc.0
IL_0011: ldloc.0
IL_0012: call ""CustomHandler..ctor(int, int, int, int)""
IL_0017: ldloca.s V_1
IL_0019: ldstr ""literal""
IL_001e: call ""bool CustomHandler.AppendLiteral(string)""
IL_0023: pop
IL_0024: ldloc.1
IL_0025: call ""void C.M(int, string, CustomHandler)""
IL_002a: ret
}
"
: @"
{
// Code size 50 (0x32)
.maxstack 7
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr """"
IL_000c: ldc.i4.7
IL_000d: ldc.i4.0
IL_000e: ldloc.0
IL_000f: ldloc.0
IL_0010: ldloca.s V_2
IL_0012: newobj ""CustomHandler..ctor(int, int, int, int, out bool)""
IL_0017: stloc.1
IL_0018: ldloc.2
IL_0019: brfalse.s IL_0029
IL_001b: ldloca.s V_1
IL_001d: ldstr ""literal""
IL_0022: call ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.1
IL_002c: call ""void C.M(int, string, CustomHandler)""
IL_0031: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_EmptyWithMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, """", " + expression + @");
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) => Console.WriteLine(c.ToString());
}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount" + extraConstructorArg + @")
{
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: "CustomHandler").VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 19 (0x13)
.maxstack 4
IL_0000: ldc.i4.1
IL_0001: ldstr """"
IL_0006: ldc.i4.0
IL_0007: ldc.i4.0
IL_0008: newobj ""CustomHandler..ctor(int, int)""
IL_000d: call ""void C.M(int, string, CustomHandler)""
IL_0012: ret
}
"
: @"
{
// Code size 21 (0x15)
.maxstack 5
.locals init (bool V_0)
IL_0000: ldc.i4.1
IL_0001: ldstr """"
IL_0006: ldc.i4.0
IL_0007: ldc.i4.0
IL_0008: ldloca.s V_0
IL_000a: newobj ""CustomHandler..ctor(int, int, out bool)""
IL_000f: call ""void C.M(int, string, CustomHandler)""
IL_0014: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_EmptyWithoutMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) { }
}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @")
{
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute });
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics();
CreateCompilation(@"C.M(1, """", " + expression + @");", new[] { comp.EmitToImageReference() }).VerifyDiagnostics(
(extraConstructorArg == "")
? new[]
{
// (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int)'
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 12),
// (1,12): error CS1615: Argument 3 may not be passed with the 'out' keyword
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "out").WithLocation(1, 12)
}
: new[]
{
// (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int, out bool)'
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12),
// (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, int, out bool)'
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12)
}
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_OnIndexerRvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
var c = new C();
Console.WriteLine(c[10, ""str"", " + expression + @"]);
public class C
{
public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { get => c.ToString(); }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i1:10
s:str
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 52 (0x34)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldloca.s V_2
IL_0012: ldc.i4.7
IL_0013: ldc.i4.0
IL_0014: ldloc.0
IL_0015: ldloc.1
IL_0016: call ""CustomHandler..ctor(int, int, int, string)""
IL_001b: ldloca.s V_2
IL_001d: ldstr ""literal""
IL_0022: call ""bool CustomHandler.AppendLiteral(string)""
IL_0027: pop
IL_0028: ldloc.2
IL_0029: callvirt ""string C.this[int, string, CustomHandler].get""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: ret
}
"
: @"
{
// Code size 59 (0x3b)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2,
bool V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldc.i4.7
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: callvirt ""string C.this[int, string, CustomHandler].get""
IL_0035: call ""void System.Console.WriteLine(string)""
IL_003a: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_OnIndexerLvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
var c = new C();
c[10, ""str"", " + expression + @"] = """";
public class C
{
public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { set => Console.WriteLine(c.ToString()); }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i1:10
s:str
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 52 (0x34)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldloca.s V_2
IL_0012: ldc.i4.7
IL_0013: ldc.i4.0
IL_0014: ldloc.0
IL_0015: ldloc.1
IL_0016: call ""CustomHandler..ctor(int, int, int, string)""
IL_001b: ldloca.s V_2
IL_001d: ldstr ""literal""
IL_0022: call ""bool CustomHandler.AppendLiteral(string)""
IL_0027: pop
IL_0028: ldloc.2
IL_0029: ldstr """"
IL_002e: callvirt ""void C.this[int, string, CustomHandler].set""
IL_0033: ret
}
"
: @"
{
// Code size 59 (0x3b)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2,
bool V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldc.i4.7
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: ldstr """"
IL_0035: callvirt ""void C.this[int, string, CustomHandler].set""
IL_003a: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_ThisParameter([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
(new C(5)).M((int)10, ""str"", " + expression + @");
public class C
{
public int Prop { get; }
public C(int i) => Prop = i;
public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", """", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, C c, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""c.Prop:"" + c.Prop.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i1:10
c.Prop:5
s:str
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 51 (0x33)
.maxstack 9
.locals init (int V_0,
C V_1,
string V_2,
CustomHandler V_3)
IL_0000: ldc.i4.5
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.s 10
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldstr ""str""
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: ldloca.s V_3
IL_0015: ldc.i4.7
IL_0016: ldc.i4.0
IL_0017: ldloc.0
IL_0018: ldloc.1
IL_0019: ldloc.2
IL_001a: call ""CustomHandler..ctor(int, int, int, C, string)""
IL_001f: ldloca.s V_3
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: pop
IL_002c: ldloc.3
IL_002d: callvirt ""void C.M(int, string, CustomHandler)""
IL_0032: ret
}
"
: @"
{
// Code size 59 (0x3b)
.maxstack 9
.locals init (int V_0,
C V_1,
string V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.5
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.s 10
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldstr ""str""
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: ldc.i4.7
IL_0014: ldc.i4.0
IL_0015: ldloc.0
IL_0016: ldloc.1
IL_0017: ldloc.2
IL_0018: ldloca.s V_4
IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, string, out bool)""
IL_001f: stloc.3
IL_0020: ldloc.s V_4
IL_0022: brfalse.s IL_0032
IL_0024: ldloca.s V_3
IL_0026: ldstr ""literal""
IL_002b: call ""bool CustomHandler.AppendLiteral(string)""
IL_0030: br.s IL_0033
IL_0032: ldc.i4.0
IL_0033: pop
IL_0034: ldloc.3
IL_0035: callvirt ""void C.M(int, string, CustomHandler)""
IL_003a: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, -1, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void InterpolatedStringHandlerArgumentAttribute_OnConstructor(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
_ = new C(5, " + expression + @");
public class C
{
public int Prop { get; }
public C(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")]CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
i:5
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 34 (0x22)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.5
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldloca.s V_1
IL_0005: ldc.i4.7
IL_0006: ldc.i4.0
IL_0007: ldloc.0
IL_0008: call ""CustomHandler..ctor(int, int, int)""
IL_000d: ldloca.s V_1
IL_000f: ldstr ""literal""
IL_0014: call ""bool CustomHandler.AppendLiteral(string)""
IL_0019: pop
IL_001a: ldloc.1
IL_001b: newobj ""C..ctor(int, CustomHandler)""
IL_0020: pop
IL_0021: ret
}
");
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_Success([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C c = new C(1);
GetC(ref c).M(" + expression + @");
Console.WriteLine(c.I);
ref C GetC(ref C c)
{
Console.WriteLine(""GetC"");
return ref c;
}
public class C
{
public int I;
public C(int i)
{
I = i;
}
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
c = new C(2);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @"
GetC
literal:literal
2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldind.ref
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)""
IL_0019: stloc.2
IL_001a: ldloca.s V_2
IL_001c: ldstr ""literal""
IL_0021: call ""bool CustomHandler.AppendLiteral(string)""
IL_0026: pop
IL_0027: ldloc.2
IL_0028: callvirt ""void C.M(CustomHandler)""
IL_002d: ldloc.0
IL_002e: ldfld ""int C.I""
IL_0033: call ""void System.Console.WriteLine(int)""
IL_0038: ret
}
"
: @"
{
// Code size 65 (0x41)
.maxstack 5
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2,
bool V_3)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldind.ref
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: callvirt ""void C.M(CustomHandler)""
IL_0035: ldloc.0
IL_0036: ldfld ""int C.I""
IL_003b: call ""void System.Console.WriteLine(int)""
IL_0040: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_Success_StructReceiver([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C c = new C(1);
GetC(ref c).M(" + expression + @");
Console.WriteLine(c.I);
ref C GetC(ref C c)
{
Console.WriteLine(""GetC"");
return ref c;
}
public struct C
{
public int I;
public C(int i)
{
I = i;
}
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
c = new C(2);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @"
GetC
literal:literal
2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""C..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)""
IL_0019: stloc.2
IL_001a: ldloca.s V_2
IL_001c: ldstr ""literal""
IL_0021: call ""bool CustomHandler.AppendLiteral(string)""
IL_0026: pop
IL_0027: ldloc.2
IL_0028: call ""void C.M(CustomHandler)""
IL_002d: ldloc.0
IL_002e: ldfld ""int C.I""
IL_0033: call ""void System.Console.WriteLine(int)""
IL_0038: ret
}
"
: @"
{
// Code size 65 (0x41)
.maxstack 5
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2,
bool V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""C..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: call ""void C.M(CustomHandler)""
IL_0035: ldloc.0
IL_0036: ldfld ""int C.I""
IL_003b: call ""void System.Console.WriteLine(int)""
IL_0040: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_MismatchedRefness_01([CombinatorialValues("ref readonly", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C c = new C(1);
GetC().M(" + expression + @");
" + refness + @" C GetC() => throw null;
public class C
{
public C(int i) { }
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref C c) : this(literalLength, formattedCount) { }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (5,10): error CS1620: Argument 3 must be passed with the 'ref' keyword
// GetC().M($"literal");
Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(5, 10)
);
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_MismatchedRefness_02([CombinatorialValues("in", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C c = new C(1);
GetC(ref c).M(" + expression + @");
ref C GetC(ref C c) => ref c;
public class C
{
public C(int i) { }
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount," + refness + @" C c) : this(literalLength, formattedCount) { }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (5,15): error CS1615: Argument 3 may not be passed with the 'ref' keyword
// GetC(ref c).M($"literal");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "ref").WithLocation(5, 15)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructReceiver_Rvalue(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s1 = new S { I = 1 };
S s2 = new S { I = 2 };
s1.M(s2, " + expression + @");
public struct S
{
public int I;
public void M(S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler)
{
Console.WriteLine(""s1.I:"" + this.I.ToString());
Console.WriteLine(""s2.I:"" + s2.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, S s1, S s2) : this(literalLength, formattedCount)
{
s1.I = 3;
s2.I = 4;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
s1.I:1
s2.I:2");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 56 (0x38)
.maxstack 6
.locals init (S V_0, //s2
S V_1,
S V_2)
IL_0000: ldloca.s V_1
IL_0002: initobj ""S""
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.I""
IL_0010: ldloc.1
IL_0011: ldloca.s V_1
IL_0013: initobj ""S""
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.2
IL_001c: stfld ""int S.I""
IL_0021: ldloc.1
IL_0022: stloc.0
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: ldloc.0
IL_0027: stloc.2
IL_0028: ldloc.2
IL_0029: ldc.i4.0
IL_002a: ldc.i4.0
IL_002b: ldloc.1
IL_002c: ldloc.2
IL_002d: newobj ""CustomHandler..ctor(int, int, S, S)""
IL_0032: call ""void S.M(S, CustomHandler)""
IL_0037: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructReceiver_Lvalue(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s1 = new S { I = 1 };
S s2 = new S { I = 2 };
s1.M(ref s2, " + expression + @");
public struct S
{
public int I;
public void M(ref S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler)
{
Console.WriteLine(""s1.I:"" + this.I.ToString());
Console.WriteLine(""s2.I:"" + s2.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref S s1, ref S s2) : this(literalLength, formattedCount)
{
s1.I = 3;
s2.I = 4;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (8,14): error CS1620: Argument 3 must be passed with the 'ref' keyword
// s1.M(ref s2, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(8, 14)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructParameter_ByVal(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s = new S { I = 1 };
S.M(s, " + expression + @");
public struct S
{
public int I;
public static void M(S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler)
{
Console.WriteLine(""s.I:"" + s.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, S s) : this(literalLength, formattedCount)
{
s.I = 2;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 33 (0x21)
.maxstack 4
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.I""
IL_0010: ldloc.0
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: ldc.i4.0
IL_0014: ldc.i4.0
IL_0015: ldloc.0
IL_0016: newobj ""CustomHandler..ctor(int, int, S)""
IL_001b: call ""void S.M(S, CustomHandler)""
IL_0020: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructParameter_ByRef(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s = new S { I = 1 };
S.M(ref s, " + expression + @");
public struct S
{
public int I;
public static void M(ref S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler)
{
Console.WriteLine(""s.I:"" + s.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref S s) : this(literalLength, formattedCount)
{
s.I = 2;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:2");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init (S V_0, //s
S V_1,
S& V_2)
IL_0000: ldloca.s V_1
IL_0002: initobj ""S""
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.I""
IL_0010: ldloc.1
IL_0011: stloc.0
IL_0012: ldloca.s V_0
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldc.i4.0
IL_0017: ldc.i4.0
IL_0018: ldloc.2
IL_0019: newobj ""CustomHandler..ctor(int, int, ref S)""
IL_001e: call ""void S.M(ref S, CustomHandler)""
IL_0023: ret
}
");
}
[Theory]
[CombinatorialData]
public void SideEffects(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal""", @"$"""" + $""literal""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
GetReceiver().M(
GetArg(""Unrelated parameter 1""),
GetArg(""Second value""),
GetArg(""Unrelated parameter 2""),
GetArg(""First value""),
" + expression + @",
GetArg(""Unrelated parameter 4""));
C GetReceiver()
{
Console.WriteLine(""GetReceiver"");
return new C() { Prop = ""Prop"" };
}
string GetArg(string s)
{
Console.WriteLine(s);
return s;
}
public class C
{
public string Prop { get; set; }
public void M(string param1, string param2, string param3, string param4, [InterpolatedStringHandlerArgument(""param4"", """", ""param2"")] CustomHandler c, string param6)
=> Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s1, C c, string s2" + (validityParameter ? ", out bool success" : "") + @")
: this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""s1:"" + s1);
_builder.AppendLine(""c.Prop:"" + c.Prop);
_builder.AppendLine(""s2:"" + s2);
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns);
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: @"
GetReceiver
Unrelated parameter 1
Second value
Unrelated parameter 2
First value
Handler constructor
Unrelated parameter 4
s1:First value
c.Prop:Prop
s2:Second value
literal:literal
");
verifier.VerifyDiagnostics();
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$""literal"" + $""""")]
public void InterpolatedStringHandlerArgumentsAttribute_ConversionFromArgumentType(string expression)
{
var code = @"
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
int i = 1;
C.M(i, " + expression + @");
public class C
{
public static implicit operator C(int i) => throw null;
public static implicit operator C(double d)
{
Console.WriteLine(d.ToString(""G"", CultureInfo.InvariantCulture));
return new C();
}
public override string ToString() => ""C"";
public static void M(double d, [InterpolatedStringHandlerArgument(""d"")] CustomHandler handler) => Console.WriteLine(handler.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
1
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 39 (0x27)
.maxstack 5
.locals init (double V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: conv.r8
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldloca.s V_1
IL_0006: ldc.i4.7
IL_0007: ldc.i4.0
IL_0008: ldloc.0
IL_0009: call ""C C.op_Implicit(double)""
IL_000e: call ""CustomHandler..ctor(int, int, C)""
IL_0013: ldloca.s V_1
IL_0015: ldstr ""literal""
IL_001a: call ""bool CustomHandler.AppendLiteral(string)""
IL_001f: pop
IL_0020: ldloc.1
IL_0021: call ""void C.M(double, CustomHandler)""
IL_0026: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_01(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 3;
GetC()[GetInt(1), " + expression + @"] += GetInt(2);
static C GetC()
{
Console.WriteLine(""GetC"");
return new C() { Prop = 2 };
}
static int GetInt(int i)
{
Console.WriteLine(""GetInt"" + i.ToString());
return 1;
}
public class C
{
public int Prop { get; set; }
public int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c]
{
get
{
Console.WriteLine(""Indexer getter"");
return 0;
}
set
{
Console.WriteLine(""Indexer setter"");
Console.WriteLine(c.ToString());
}
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""arg1:"" + arg1);
_builder.AppendLine(""C.Prop:"" + c.Prop.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
GetC
GetInt1
Handler constructor
Indexer getter
GetInt2
Indexer setter
arg1:1
C.Prop:2
literal:literal
value:3
alignment:0
format:
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 85 (0x55)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldloca.s V_5
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_5
IL_001e: ldstr ""literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_5
IL_002a: ldloc.0
IL_002b: box ""int""
IL_0030: ldc.i4.0
IL_0031: ldnull
IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0037: ldloc.s V_5
IL_0039: stloc.s V_4
IL_003b: ldloc.2
IL_003c: ldloc.3
IL_003d: ldloc.s V_4
IL_003f: ldloc.2
IL_0040: ldloc.3
IL_0041: ldloc.s V_4
IL_0043: callvirt ""int C.this[int, CustomHandler].get""
IL_0048: ldc.i4.2
IL_0049: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_004e: add
IL_004f: callvirt ""void C.this[int, CustomHandler].set""
IL_0054: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 96 (0x60)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5,
bool V_6)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_6
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.s V_5
IL_001e: ldloc.s V_6
IL_0020: brfalse.s IL_0040
IL_0022: ldloca.s V_5
IL_0024: ldstr ""literal""
IL_0029: call ""void CustomHandler.AppendLiteral(string)""
IL_002e: ldloca.s V_5
IL_0030: ldloc.0
IL_0031: box ""int""
IL_0036: ldc.i4.0
IL_0037: ldnull
IL_0038: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003d: ldc.i4.1
IL_003e: br.s IL_0041
IL_0040: ldc.i4.0
IL_0041: pop
IL_0042: ldloc.s V_5
IL_0044: stloc.s V_4
IL_0046: ldloc.2
IL_0047: ldloc.3
IL_0048: ldloc.s V_4
IL_004a: ldloc.2
IL_004b: ldloc.3
IL_004c: ldloc.s V_4
IL_004e: callvirt ""int C.this[int, CustomHandler].get""
IL_0053: ldc.i4.2
IL_0054: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_0059: add
IL_005a: callvirt ""void C.this[int, CustomHandler].set""
IL_005f: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 91 (0x5b)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldloca.s V_5
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_5
IL_001e: ldstr ""literal""
IL_0023: call ""bool CustomHandler.AppendLiteral(string)""
IL_0028: brfalse.s IL_003b
IL_002a: ldloca.s V_5
IL_002c: ldloc.0
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.s V_5
IL_003f: stloc.s V_4
IL_0041: ldloc.2
IL_0042: ldloc.3
IL_0043: ldloc.s V_4
IL_0045: ldloc.2
IL_0046: ldloc.3
IL_0047: ldloc.s V_4
IL_0049: callvirt ""int C.this[int, CustomHandler].get""
IL_004e: ldc.i4.2
IL_004f: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_0054: add
IL_0055: callvirt ""void C.this[int, CustomHandler].set""
IL_005a: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 97 (0x61)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5,
bool V_6)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_6
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.s V_5
IL_001e: ldloc.s V_6
IL_0020: brfalse.s IL_0041
IL_0022: ldloca.s V_5
IL_0024: ldstr ""literal""
IL_0029: call ""bool CustomHandler.AppendLiteral(string)""
IL_002e: brfalse.s IL_0041
IL_0030: ldloca.s V_5
IL_0032: ldloc.0
IL_0033: box ""int""
IL_0038: ldc.i4.0
IL_0039: ldnull
IL_003a: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_003f: br.s IL_0042
IL_0041: ldc.i4.0
IL_0042: pop
IL_0043: ldloc.s V_5
IL_0045: stloc.s V_4
IL_0047: ldloc.2
IL_0048: ldloc.3
IL_0049: ldloc.s V_4
IL_004b: ldloc.2
IL_004c: ldloc.3
IL_004d: ldloc.s V_4
IL_004f: callvirt ""int C.this[int, CustomHandler].get""
IL_0054: ldc.i4.2
IL_0055: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_005a: add
IL_005b: callvirt ""void C.this[int, CustomHandler].set""
IL_0060: ret
}
",
};
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_02(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 3;
GetC()[GetInt(1), " + expression + @"] += GetInt(2);
static C GetC()
{
Console.WriteLine(""GetC"");
return new C() { Prop = 2 };
}
static int GetInt(int i)
{
Console.WriteLine(""GetInt"" + i.ToString());
return 1;
}
public class C
{
private int field;
public int Prop { get; set; }
public ref int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c]
{
get
{
Console.WriteLine(""Indexer getter"");
Console.WriteLine(c.ToString());
return ref field;
}
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""arg1:"" + arg1);
_builder.AppendLine(""C.Prop:"" + c.Prop.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
GetC
GetInt1
Handler constructor
Indexer getter
arg1:1
C.Prop:2
literal:literal
value:3
alignment:0
format:
GetInt2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 72 (0x48)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_3
IL_002a: ldloc.0
IL_002b: box ""int""
IL_0030: ldc.i4.0
IL_0031: ldnull
IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0037: ldloc.3
IL_0038: callvirt ""ref int C.this[int, CustomHandler].get""
IL_003d: dup
IL_003e: ldind.i4
IL_003f: ldc.i4.2
IL_0040: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_0045: add
IL_0046: stind.i4
IL_0047: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 82 (0x52)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_003f
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""void CustomHandler.AppendLiteral(string)""
IL_002d: ldloca.s V_3
IL_002f: ldloc.0
IL_0030: box ""int""
IL_0035: ldc.i4.0
IL_0036: ldnull
IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003c: ldc.i4.1
IL_003d: br.s IL_0040
IL_003f: ldc.i4.0
IL_0040: pop
IL_0041: ldloc.3
IL_0042: callvirt ""ref int C.this[int, CustomHandler].get""
IL_0047: dup
IL_0048: ldind.i4
IL_0049: ldc.i4.2
IL_004a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_004f: add
IL_0050: stind.i4
IL_0051: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 78 (0x4e)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""bool CustomHandler.AppendLiteral(string)""
IL_0028: brfalse.s IL_003b
IL_002a: ldloca.s V_3
IL_002c: ldloc.0
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.3
IL_003e: callvirt ""ref int C.this[int, CustomHandler].get""
IL_0043: dup
IL_0044: ldind.i4
IL_0045: ldc.i4.2
IL_0046: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_004b: add
IL_004c: stind.i4
IL_004d: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 83 (0x53)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_0040
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""bool CustomHandler.AppendLiteral(string)""
IL_002d: brfalse.s IL_0040
IL_002f: ldloca.s V_3
IL_0031: ldloc.0
IL_0032: box ""int""
IL_0037: ldc.i4.0
IL_0038: ldnull
IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_003e: br.s IL_0041
IL_0040: ldc.i4.0
IL_0041: pop
IL_0042: ldloc.3
IL_0043: callvirt ""ref int C.this[int, CustomHandler].get""
IL_0048: dup
IL_0049: ldind.i4
IL_004a: ldc.i4.2
IL_004b: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_0050: add
IL_0051: stind.i4
IL_0052: ret
}
",
};
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_RefReturningMethod(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 3;
GetC().M(GetInt(1), " + expression + @") += GetInt(2);
static C GetC()
{
Console.WriteLine(""GetC"");
return new C() { Prop = 2 };
}
static int GetInt(int i)
{
Console.WriteLine(""GetInt"" + i.ToString());
return 1;
}
public class C
{
private int field;
public int Prop { get; set; }
public ref int M(int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c)
{
Console.WriteLine(""M"");
Console.WriteLine(c.ToString());
return ref field;
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""arg1:"" + arg1);
_builder.AppendLine(""C.Prop:"" + c.Prop.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
GetC
GetInt1
Handler constructor
M
arg1:1
C.Prop:2
literal:literal
value:3
alignment:0
format:
GetInt2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 72 (0x48)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_3
IL_002a: ldloc.0
IL_002b: box ""int""
IL_0030: ldc.i4.0
IL_0031: ldnull
IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0037: ldloc.3
IL_0038: callvirt ""ref int C.M(int, CustomHandler)""
IL_003d: dup
IL_003e: ldind.i4
IL_003f: ldc.i4.2
IL_0040: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_0045: add
IL_0046: stind.i4
IL_0047: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 82 (0x52)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_003f
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""void CustomHandler.AppendLiteral(string)""
IL_002d: ldloca.s V_3
IL_002f: ldloc.0
IL_0030: box ""int""
IL_0035: ldc.i4.0
IL_0036: ldnull
IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003c: ldc.i4.1
IL_003d: br.s IL_0040
IL_003f: ldc.i4.0
IL_0040: pop
IL_0041: ldloc.3
IL_0042: callvirt ""ref int C.M(int, CustomHandler)""
IL_0047: dup
IL_0048: ldind.i4
IL_0049: ldc.i4.2
IL_004a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_004f: add
IL_0050: stind.i4
IL_0051: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 78 (0x4e)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""bool CustomHandler.AppendLiteral(string)""
IL_0028: brfalse.s IL_003b
IL_002a: ldloca.s V_3
IL_002c: ldloc.0
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.3
IL_003e: callvirt ""ref int C.M(int, CustomHandler)""
IL_0043: dup
IL_0044: ldind.i4
IL_0045: ldc.i4.2
IL_0046: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_004b: add
IL_004c: stind.i4
IL_004d: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 83 (0x53)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_0040
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""bool CustomHandler.AppendLiteral(string)""
IL_002d: brfalse.s IL_0040
IL_002f: ldloca.s V_3
IL_0031: ldloc.0
IL_0032: box ""int""
IL_0037: ldc.i4.0
IL_0038: ldnull
IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_003e: br.s IL_0041
IL_0040: ldc.i4.0
IL_0041: pop
IL_0042: ldloc.3
IL_0043: callvirt ""ref int C.M(int, CustomHandler)""
IL_0048: dup
IL_0049: ldind.i4
IL_004a: ldc.i4.2
IL_004b: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)""
IL_0050: add
IL_0051: stind.i4
IL_0052: ret
}
",
};
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void InterpolatedStringHandlerArgumentsAttribute_CollectionInitializerAdd(string expression)
{
var code = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
_ = new C(1) { " + expression + @" };
public class C : IEnumerable<int>
{
public int Field;
public C(int i)
{
Field = i;
}
public void Add([InterpolatedStringHandlerArgument("""")] CustomHandler c)
{
Console.WriteLine(c.ToString());
}
public IEnumerator<int> GetEnumerator() => throw null;
IEnumerator IEnumerable.GetEnumerator() => throw null;
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount)
{
_builder.AppendLine(""c.Field:"" + c.Field.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
c.Field:1
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 37 (0x25)
.maxstack 5
.locals init (C V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.7
IL_000b: ldc.i4.0
IL_000c: ldloc.0
IL_000d: call ""CustomHandler..ctor(int, int, C)""
IL_0012: ldloca.s V_1
IL_0014: ldstr ""literal""
IL_0019: call ""void CustomHandler.AppendLiteral(string)""
IL_001e: ldloc.1
IL_001f: callvirt ""void C.Add(CustomHandler)""
IL_0024: ret
}
");
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_AttributeOnAppendFormatCall(bool useBoolReturns, bool validityParameter,
[CombinatorialValues(@"$""{$""Inner string""}{2}""", @"$""{$""Inner string""}"" + $""{2}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler handler)
{
Console.WriteLine(handler.ToString());
}
}
public partial class CustomHandler
{
private int I = 0;
public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""int constructor"");
I = i;
" + (validityParameter ? "success = true;" : "") + @"
}
public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""CustomHandler constructor"");
_builder.AppendLine(""c.I:"" + c.I.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted([InterpolatedStringHandlerArgument("""")]CustomHandler c)
{
_builder.AppendLine(""CustomHandler AppendFormatted"");
_builder.Append(c.ToString());
" + (useBoolReturns ? "return true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
int constructor
CustomHandler constructor
CustomHandler AppendFormatted
c.I:1
literal:Inner string
value:2
alignment:0
format:
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 59 (0x3b)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: dup
IL_000c: stloc.1
IL_000d: ldloc.1
IL_000e: ldc.i4.s 12
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0017: dup
IL_0018: ldstr ""Inner string""
IL_001d: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0022: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)""
IL_0027: dup
IL_0028: ldc.i4.2
IL_0029: box ""int""
IL_002e: ldc.i4.0
IL_002f: ldnull
IL_0030: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: call ""void C.M(int, CustomHandler)""
IL_003a: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 87 (0x57)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2,
CustomHandler V_3,
CustomHandler V_4,
bool V_5)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.2
IL_000f: brfalse.s IL_004e
IL_0011: ldloc.1
IL_0012: stloc.3
IL_0013: ldloc.3
IL_0014: ldc.i4.s 12
IL_0016: ldc.i4.0
IL_0017: ldloc.3
IL_0018: ldloca.s V_5
IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_001f: stloc.s V_4
IL_0021: ldloc.s V_5
IL_0023: brfalse.s IL_0034
IL_0025: ldloc.s V_4
IL_0027: ldstr ""Inner string""
IL_002c: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0031: ldc.i4.1
IL_0032: br.s IL_0035
IL_0034: ldc.i4.0
IL_0035: pop
IL_0036: ldloc.s V_4
IL_0038: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)""
IL_003d: ldloc.1
IL_003e: ldc.i4.2
IL_003f: box ""int""
IL_0044: ldc.i4.0
IL_0045: ldnull
IL_0046: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_004b: ldc.i4.1
IL_004c: br.s IL_004f
IL_004e: ldc.i4.0
IL_004f: pop
IL_0050: ldloc.1
IL_0051: call ""void C.M(int, CustomHandler)""
IL_0056: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 68 (0x44)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1,
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: stloc.2
IL_000e: ldloc.2
IL_000f: ldc.i4.s 12
IL_0011: ldc.i4.0
IL_0012: ldloc.2
IL_0013: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0018: dup
IL_0019: ldstr ""Inner string""
IL_001e: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0023: pop
IL_0024: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)""
IL_0029: brfalse.s IL_003b
IL_002b: ldloc.1
IL_002c: ldc.i4.2
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.1
IL_003e: call ""void C.M(int, CustomHandler)""
IL_0043: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 87 (0x57)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2,
CustomHandler V_3,
CustomHandler V_4,
bool V_5)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.2
IL_000f: brfalse.s IL_004e
IL_0011: ldloc.1
IL_0012: stloc.3
IL_0013: ldloc.3
IL_0014: ldc.i4.s 12
IL_0016: ldc.i4.0
IL_0017: ldloc.3
IL_0018: ldloca.s V_5
IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_001f: stloc.s V_4
IL_0021: ldloc.s V_5
IL_0023: brfalse.s IL_0033
IL_0025: ldloc.s V_4
IL_0027: ldstr ""Inner string""
IL_002c: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0031: br.s IL_0034
IL_0033: ldc.i4.0
IL_0034: pop
IL_0035: ldloc.s V_4
IL_0037: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)""
IL_003c: brfalse.s IL_004e
IL_003e: ldloc.1
IL_003f: ldc.i4.2
IL_0040: box ""int""
IL_0045: ldc.i4.0
IL_0046: ldnull
IL_0047: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_004c: br.s IL_004f
IL_004e: ldc.i4.0
IL_004f: pop
IL_0050: ldloc.1
IL_0051: call ""void C.M(int, CustomHandler)""
IL_0056: ret
}
",
};
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void DiscardsUsedAsParameters(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(out _, " + expression + @");
public class C
{
public static void M(out int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c)
{
i = 0;
Console.WriteLine(c.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, out int i) : this(literalLength, formattedCount)
{
i = 1;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"literal:literal");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 31 (0x1f)
.maxstack 4
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.0
IL_0004: ldloca.s V_0
IL_0006: newobj ""CustomHandler..ctor(int, int, out int)""
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: ldstr ""literal""
IL_0013: call ""void CustomHandler.AppendLiteral(string)""
IL_0018: ldloc.1
IL_0019: call ""void C.M(out int, CustomHandler)""
IL_001e: ret
}
");
}
[Fact]
public void DiscardsUsedAsParameters_DefinedInVB()
{
var vb = @"
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
Public Shared Sub M(<Out> ByRef i As Integer, <InterpolatedStringHandlerArgument(""i"")>c As CustomHandler)
Console.WriteLine(i)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
Public Sub New(literalLength As Integer, formattedCount As Integer, <Out> ByRef i As Integer)
i = 1
End Sub
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vb, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var code = @"C.M(out _, $"""");";
var comp = CreateCompilation(code, new[] { vbComp.EmitToImageReference() });
var verifier = CompileAndVerify(comp, expectedOutput: @"1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 17 (0x11)
.maxstack 4
.locals init (int V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: ldloca.s V_0
IL_0006: newobj ""CustomHandler..ctor(int, int, out int)""
IL_000b: call ""void C.M(out int, CustomHandler)""
IL_0010: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DisallowedInExpressionTrees(string expression)
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<CustomHandler>> expr = () => " + expression + @";
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, handler });
comp.VerifyDiagnostics(
// (5,46): error CS8952: An expression tree may not contain an interpolated string handler conversion.
// Expression<Func<CustomHandler>> expr = () => $"";
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, expression).WithLocation(5, 46)
);
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_01()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<string, string>> e = o => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 127 (0x7f)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: pop
IL_007e: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_02()
{
var code = @"
using System.Linq.Expressions;
Expression e = (string o) => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 127 (0x7f)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: pop
IL_007e: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_03()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<Func<string, string>>> e = () => o => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 137 (0x89)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()""
IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_0087: pop
IL_0088: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_04()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression e = Func<string, string> () => (string o) => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 137 (0x89)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()""
IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_0087: pop
IL_0088: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_05()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<string, string>> e = o => $""{o.Length}"" + $""literal"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 167 (0xa7)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldstr ""literal""
IL_0073: ldtoken ""string""
IL_0078: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_007d: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0082: ldtoken ""string string.Concat(string, string)""
IL_0087: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_008c: castclass ""System.Reflection.MethodInfo""
IL_0091: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0096: ldc.i4.1
IL_0097: newarr ""System.Linq.Expressions.ParameterExpression""
IL_009c: dup
IL_009d: ldc.i4.0
IL_009e: ldloc.0
IL_009f: stelem.ref
IL_00a0: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_00a5: pop
IL_00a6: ret
}
");
}
[Theory]
[CombinatorialData]
public void CustomHandlerUsedAsArgumentToCustomHandler(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, " + expression + @", " + expression + @");
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c1, [InterpolatedStringHandlerArgument(""c1"")] CustomHandler c2) => Console.WriteLine(c2.ToString());
}
public partial class CustomHandler
{
private int i;
public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
this.i = i;
" + (validityParameter ? "success = true;" : "") + @"
}
public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""c.i:"" + c.i.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: "c.i:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 27 (0x1b)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.0
IL_000e: ldc.i4.0
IL_000f: ldloc.1
IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001a: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 31 (0x1f)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: ldc.i4.0
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: ldloca.s V_2
IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001e: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 27 (0x1b)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.0
IL_000e: ldc.i4.0
IL_000f: ldloc.1
IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001a: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 31 (0x1f)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: ldc.i4.0
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: ldloca.s V_2
IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001e: ret
}
",
};
}
[Theory]
[CombinatorialData]
public void DefiniteAssignment_01(bool useBoolReturns, bool trailingOutParameter,
[CombinatorialValues(@"$""{i = 1}{M(out var o)}{s = o.ToString()}""", @"$""{i = 1}"" + $""{M(out var o)}"" + $""{s = o.ToString()}""")] string expression)
{
var code = @"
int i;
string s;
CustomHandler c = " + expression + @";
_ = i.ToString();
_ = o.ToString();
_ = s.ToString();
string M(out object o)
{
o = null;
return null;
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter);
var comp = CreateCompilation(new[] { code, customHandler });
if (trailingOutParameter)
{
comp.VerifyDiagnostics(
// (6,5): error CS0165: Use of unassigned local variable 'i'
// _ = i.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 5),
// (7,5): error CS0165: Use of unassigned local variable 'o'
// _ = o.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5),
// (8,5): error CS0165: Use of unassigned local variable 's'
// _ = s.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5)
);
}
else if (useBoolReturns)
{
comp.VerifyDiagnostics(
// (7,5): error CS0165: Use of unassigned local variable 'o'
// _ = o.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5),
// (8,5): error CS0165: Use of unassigned local variable 's'
// _ = s.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5)
);
}
else
{
comp.VerifyDiagnostics();
}
}
[Theory]
[CombinatorialData]
public void DefiniteAssignment_02(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}""", @"$"""" + $""{i = 1}""", @"$""{i = 1}"" + $""""")] string expression)
{
var code = @"
int i;
CustomHandler c = " + expression + @";
_ = i.ToString();
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter);
var comp = CreateCompilation(new[] { code, customHandler });
if (trailingOutParameter)
{
comp.VerifyDiagnostics(
// (5,5): error CS0165: Use of unassigned local variable 'i'
// _ = i.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(5, 5)
);
}
else
{
comp.VerifyDiagnostics();
}
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_01(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
dynamic d = 1;
M(d, " + expression + @");
void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute });
comp.VerifyDiagnostics(
// (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'.
// M(d, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_02(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
int i = 1;
M(i, " + expression + @");
void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute });
comp.VerifyDiagnostics(
// (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'.
// M(d, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_03(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 1;
M(i, " + expression + @");
void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) {}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, dynamic d) : this(literalLength, formattedCount)
{
Console.WriteLine(""d:"" + d.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false, includeOneTimeHelpers: false);
var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "d:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 22 (0x16)
.maxstack 4
.locals init (int V_0)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: box ""int""
IL_000b: newobj ""CustomHandler..ctor(int, int, dynamic)""
IL_0010: call ""void <Program>$.<<Main>$>g__M|0_0(int, CustomHandler)""
IL_0015: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_04(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(dynamic literalLength, int formattedCount)
{
Console.WriteLine(""ctor"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "ctor");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: box ""int""
IL_0006: ldc.i4.0
IL_0007: newobj ""CustomHandler..ctor(dynamic, int)""
IL_000c: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_0011: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_05(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
Console.WriteLine(""ctor"");
}
public CustomHandler(dynamic literalLength, int formattedCount)
{
throw null;
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "ctor");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_000c: ret
}
");
}
[Theory]
[InlineData(@"$""Literal""")]
[InlineData(@"$"""" + $""Literal""")]
public void DynamicConstruction_06(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public void AppendLiteral(dynamic d)
{
Console.WriteLine(""AppendLiteral"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "AppendLiteral");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 28 (0x1c)
.maxstack 3
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.0
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldstr ""Literal""
IL_0010: call ""void CustomHandler.AppendLiteral(dynamic)""
IL_0015: ldloc.0
IL_0016: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_001b: ret
}
");
}
[Theory]
[InlineData(@"$""{1}""")]
[InlineData(@"$""{1}"" + $""""")]
public void DynamicConstruction_07(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public void AppendFormatted(dynamic d)
{
Console.WriteLine(""AppendFormatted"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "AppendFormatted");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: call ""void CustomHandler.AppendFormatted(dynamic)""
IL_0016: ldloc.0
IL_0017: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_001c: ret
}
");
}
[Theory]
[InlineData(@"$""literal{d}""")]
[InlineData(@"$""literal"" + $""{d}""")]
public void DynamicConstruction_08(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
dynamic d = 1;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public void AppendLiteral(dynamic d)
{
Console.WriteLine(""AppendLiteral"");
}
public void AppendFormatted(dynamic d)
{
Console.WriteLine(""AppendFormatted"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
AppendLiteral
AppendFormatted");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 128 (0x80)
.maxstack 9
.locals init (object V_0, //d
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldloca.s V_1
IL_0009: ldc.i4.7
IL_000a: ldc.i4.1
IL_000b: call ""CustomHandler..ctor(int, int)""
IL_0010: ldloca.s V_1
IL_0012: ldstr ""literal""
IL_0017: call ""void CustomHandler.AppendLiteral(dynamic)""
IL_001c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0""
IL_0021: brtrue.s IL_0062
IL_0023: ldc.i4 0x100
IL_0028: ldstr ""AppendFormatted""
IL_002d: ldnull
IL_002e: ldtoken ""<Program>$""
IL_0033: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0038: ldc.i4.2
IL_0039: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_003e: dup
IL_003f: ldc.i4.0
IL_0040: ldc.i4.s 9
IL_0042: ldnull
IL_0043: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0048: stelem.ref
IL_0049: dup
IL_004a: ldc.i4.1
IL_004b: ldc.i4.0
IL_004c: ldnull
IL_004d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0052: stelem.ref
IL_0053: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0058: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_005d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0""
IL_0062: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0""
IL_0067: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Target""
IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0""
IL_0071: ldloca.s V_1
IL_0073: ldloc.0
IL_0074: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)""
IL_0079: ldloc.1
IL_007a: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_007f: ret
}
");
}
[Theory]
[InlineData(@"$""literal{d}""")]
[InlineData(@"$""literal"" + $""{d}""")]
public void DynamicConstruction_09(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
dynamic d = 1;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public bool AppendLiteral(dynamic d)
{
Console.WriteLine(""AppendLiteral"");
return true;
}
public bool AppendFormatted(dynamic d)
{
Console.WriteLine(""AppendFormatted"");
return true;
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
AppendLiteral
AppendFormatted");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 196 (0xc4)
.maxstack 11
.locals init (object V_0, //d
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldloca.s V_1
IL_0009: ldc.i4.7
IL_000a: ldc.i4.1
IL_000b: call ""CustomHandler..ctor(int, int)""
IL_0010: ldloca.s V_1
IL_0012: ldstr ""literal""
IL_0017: call ""bool CustomHandler.AppendLiteral(dynamic)""
IL_001c: brfalse IL_00bb
IL_0021: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1""
IL_0026: brtrue.s IL_004c
IL_0028: ldc.i4.0
IL_0029: ldtoken ""bool""
IL_002e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0033: ldtoken ""<Program>$""
IL_0038: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_0042: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0047: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1""
IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1""
IL_0051: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target""
IL_0056: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1""
IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0""
IL_0060: brtrue.s IL_009d
IL_0062: ldc.i4.0
IL_0063: ldstr ""AppendFormatted""
IL_0068: ldnull
IL_0069: ldtoken ""<Program>$""
IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0073: ldc.i4.2
IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0079: dup
IL_007a: ldc.i4.0
IL_007b: ldc.i4.s 9
IL_007d: ldnull
IL_007e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0083: stelem.ref
IL_0084: dup
IL_0085: ldc.i4.1
IL_0086: ldc.i4.0
IL_0087: ldnull
IL_0088: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_008d: stelem.ref
IL_008e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0093: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0""
IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0""
IL_00a2: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Target""
IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0""
IL_00ac: ldloca.s V_1
IL_00ae: ldloc.0
IL_00af: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)""
IL_00b4: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_00b9: br.s IL_00bc
IL_00bb: ldc.i4.0
IL_00bc: pop
IL_00bd: ldloc.1
IL_00be: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)""
IL_00c3: ret
}
");
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_01(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount) : this() {}
public void AppendFormatted(Span<char> s) => this.s = s;
public static CustomHandler M()
{
Span<char> s = stackalloc char[10];
return " + expression + @";
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,19): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope
// return $"{s}";
Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 19)
);
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_02(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount) : this() {}
public void AppendFormatted(Span<char> s) => this.s = s;
public static ref CustomHandler M()
{
Span<char> s = stackalloc char[10];
return " + expression + @";
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,9): error CS8150: By-value returns may only be used in methods that return by value
// return $"{s}";
Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(17, 9)
);
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_03(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount) : this() {}
public void AppendFormatted(Span<char> s) => this.s = s;
public static ref CustomHandler M()
{
Span<char> s = stackalloc char[10];
return ref " + expression + @";
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// return ref $"{s}";
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, expression).WithLocation(17, 20)
);
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_04(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
S1 s1;
public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { this.s1 = s1; }
public void AppendFormatted(Span<char> s) => this.s1.s = s;
public static void M(ref S1 s1)
{
Span<char> s = stackalloc char[10];
M2(ref s1, " + expression + @");
}
public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] ref CustomHandler handler) {}
}
public ref struct S1
{
public Span<char> s;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, ref CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope
// M2(ref s1, $"{s}");
Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, " + expression + @")").WithArguments("CustomHandler.M2(ref S1, ref CustomHandler)", "handler").WithLocation(17, 9),
// (17,23): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope
// M2(ref s1, $"{s}");
Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 23)
);
}
[Theory]
[InlineData(@"$""{s1}""")]
[InlineData(@"$""{s1}"" + $""""")]
public void RefEscape_05(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; }
public void AppendFormatted(S1 s1) => s1.s = this.s;
public static void M(ref S1 s1)
{
Span<char> s = stackalloc char[10];
M2(ref s, " + expression + @");
}
public static void M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler handler) {}
}
public ref struct S1
{
public Span<char> s;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics();
}
[Theory]
[InlineData(@"$""{s2}""")]
[InlineData(@"$""{s2}"" + $""""")]
public void RefEscape_06(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
Span<char> s = stackalloc char[5];
Span<char> s2 = stackalloc char[10];
s.TryWrite(" + expression + @");
public static class MemoryExtensions
{
public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] CustomHandler builder) => true;
}
[InterpolatedStringHandler]
public ref struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { }
public bool AppendFormatted(Span<char> s) => true;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics();
}
[Theory]
[InlineData(@"$""{s2}""")]
[InlineData(@"$""{s2}"" + $""""")]
public void RefEscape_07(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
Span<char> s = stackalloc char[5];
Span<char> s2 = stackalloc char[10];
s.TryWrite(" + expression + @");
public static class MemoryExtensions
{
public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] ref CustomHandler builder) => true;
}
[InterpolatedStringHandler]
public ref struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { }
public bool AppendFormatted(Span<char> s) => true;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics();
}
[Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")]
[InlineData(@"$""{{ {i} }}""")]
[InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")]
public void BracesAreEscaped_01(string expression)
{
var code = @"
int i = 1;
System.Console.WriteLine(" + expression + @");";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
{
value:1
}");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 56 (0x38)
.maxstack 3
.locals init (int V_0, //i
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.1
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""{ ""
IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_1
IL_0019: ldloc.0
IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_001f: ldloca.s V_1
IL_0021: ldstr "" }""
IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_002b: ldloca.s V_1
IL_002d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0032: call ""void System.Console.WriteLine(string)""
IL_0037: ret
}
");
}
[Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")]
[InlineData(@"$""{{ {i} }}""")]
[InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")]
public void BracesAreEscaped_02(string expression)
{
var code = @"
int i = 1;
CustomHandler c = " + expression + @";
System.Console.WriteLine(c.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
literal:{
value:1
alignment:0
format:
literal: }");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 71 (0x47)
.maxstack 4
.locals init (int V_0, //i
CustomHandler V_1, //c
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_2
IL_0004: ldc.i4.4
IL_0005: ldc.i4.1
IL_0006: call ""CustomHandler..ctor(int, int)""
IL_000b: ldloca.s V_2
IL_000d: ldstr ""{ ""
IL_0012: call ""void CustomHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_2
IL_0019: ldloc.0
IL_001a: box ""int""
IL_001f: ldc.i4.0
IL_0020: ldnull
IL_0021: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0026: ldloca.s V_2
IL_0028: ldstr "" }""
IL_002d: call ""void CustomHandler.AppendLiteral(string)""
IL_0032: ldloc.2
IL_0033: stloc.1
IL_0034: ldloca.s V_1
IL_0036: constrained. ""CustomHandler""
IL_003c: callvirt ""string object.ToString()""
IL_0041: call ""void System.Console.WriteLine(string)""
IL_0046: ret
}
");
}
[Fact]
public void InterpolatedStringsAddedUnderObjectAddition()
{
var code = @"
int i1 = 1;
int i2 = 2;
int i3 = 3;
int i4 = 4;
System.Console.WriteLine($""{i1}"" + $""{i2}"" + $""{i3}"" + i4);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
value:2
value:3
4
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 66 (0x42)
.maxstack 3
.locals init (int V_0, //i1
int V_1, //i2
int V_2, //i3
int V_3, //i4
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_4)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: ldc.i4.4
IL_0007: stloc.3
IL_0008: ldloca.s V_4
IL_000a: ldc.i4.0
IL_000b: ldc.i4.3
IL_000c: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0011: ldloca.s V_4
IL_0013: ldloc.0
IL_0014: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0019: ldloca.s V_4
IL_001b: ldloc.1
IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0021: ldloca.s V_4
IL_0023: ldloc.2
IL_0024: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0029: ldloca.s V_4
IL_002b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0030: ldloca.s V_3
IL_0032: call ""string int.ToString()""
IL_0037: call ""string string.Concat(string, string)""
IL_003c: call ""void System.Console.WriteLine(string)""
IL_0041: ret
}
");
}
[Fact]
public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment()
{
var code = @"
object o1;
object o2;
object o3;
_ = $""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1;
o1.ToString();
o2.ToString();
o3.ToString();
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) });
comp.VerifyDiagnostics(
// (7,1): error CS0165: Use of unassigned local variable 'o2'
// o2.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o2").WithArguments("o2").WithLocation(7, 1),
// (8,1): error CS0165: Use of unassigned local variable 'o3'
// o3.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o3").WithArguments("o3").WithLocation(8, 1)
);
}
[Fact]
public void ParenthesizedAdditiveExpression_01()
{
var code = @"
int i1 = 1;
int i2 = 2;
int i3 = 3;
CustomHandler c = ($""{i1}"" + $""{i2}"") + $""{i3}"";
System.Console.WriteLine(c.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:0
format:
value:2
alignment:0
format:
value:3
alignment:0
format:
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 82 (0x52)
.maxstack 4
.locals init (int V_0, //i1
int V_1, //i2
int V_2, //i3
CustomHandler V_3, //c
CustomHandler V_4)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: ldloca.s V_4
IL_0008: ldc.i4.0
IL_0009: ldc.i4.3
IL_000a: call ""CustomHandler..ctor(int, int)""
IL_000f: ldloca.s V_4
IL_0011: ldloc.0
IL_0012: box ""int""
IL_0017: ldc.i4.0
IL_0018: ldnull
IL_0019: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001e: ldloca.s V_4
IL_0020: ldloc.1
IL_0021: box ""int""
IL_0026: ldc.i4.0
IL_0027: ldnull
IL_0028: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_002d: ldloca.s V_4
IL_002f: ldloc.2
IL_0030: box ""int""
IL_0035: ldc.i4.0
IL_0036: ldnull
IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003c: ldloc.s V_4
IL_003e: stloc.3
IL_003f: ldloca.s V_3
IL_0041: constrained. ""CustomHandler""
IL_0047: callvirt ""string object.ToString()""
IL_004c: call ""void System.Console.WriteLine(string)""
IL_0051: ret
}");
}
[Fact]
public void ParenthesizedAdditiveExpression_02()
{
var code = @"
int i1 = 1;
int i2 = 2;
int i3 = 3;
CustomHandler c = $""{i1}"" + ($""{i2}"" + $""{i3}"");
System.Console.WriteLine(c.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (6,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler'
// CustomHandler c = $"{i1}" + ($"{i2}" + $"{i3}");
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{i1}"" + ($""{i2}"" + $""{i3}"")").WithArguments("string", "CustomHandler").WithLocation(6, 19)
);
}
[Theory]
[InlineData(@"$""{1}"", $""{2}""")]
[InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")]
public void TupleDeclaration_01(string initializer)
{
var code = @"
(CustomHandler c1, CustomHandler c2) = (" + initializer + @");
System.Console.Write(c1.ToString());
System.Console.WriteLine(c2.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:0
format:
value:2
alignment:0
format:
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 91 (0x5b)
.maxstack 4
.locals init (CustomHandler V_0, //c1
CustomHandler V_1, //c2
CustomHandler V_2,
CustomHandler V_3)
IL_0000: ldloca.s V_3
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_3
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.0
IL_0012: ldnull
IL_0013: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0018: ldloc.3
IL_0019: stloc.2
IL_001a: ldloca.s V_3
IL_001c: ldc.i4.0
IL_001d: ldc.i4.1
IL_001e: call ""CustomHandler..ctor(int, int)""
IL_0023: ldloca.s V_3
IL_0025: ldc.i4.2
IL_0026: box ""int""
IL_002b: ldc.i4.0
IL_002c: ldnull
IL_002d: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0032: ldloc.3
IL_0033: ldloc.2
IL_0034: stloc.0
IL_0035: stloc.1
IL_0036: ldloca.s V_0
IL_0038: constrained. ""CustomHandler""
IL_003e: callvirt ""string object.ToString()""
IL_0043: call ""void System.Console.Write(string)""
IL_0048: ldloca.s V_1
IL_004a: constrained. ""CustomHandler""
IL_0050: callvirt ""string object.ToString()""
IL_0055: call ""void System.Console.WriteLine(string)""
IL_005a: ret
}
");
}
[Theory]
[InlineData(@"$""{1}"", $""{2}""")]
[InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")]
public void TupleDeclaration_02(string initializer)
{
var code = @"
(CustomHandler c1, CustomHandler c2) t = (" + initializer + @");
System.Console.Write(t.c1.ToString());
System.Console.WriteLine(t.c2.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:0
format:
value:2
alignment:0
format:
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 104 (0x68)
.maxstack 6
.locals init (System.ValueTuple<CustomHandler, CustomHandler> V_0, //t
CustomHandler V_1)
IL_0000: ldloca.s V_0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.0
IL_0005: ldc.i4.1
IL_0006: call ""CustomHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.1
IL_000e: box ""int""
IL_0013: ldc.i4.0
IL_0014: ldnull
IL_0015: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001a: ldloc.1
IL_001b: ldloca.s V_1
IL_001d: ldc.i4.0
IL_001e: ldc.i4.1
IL_001f: call ""CustomHandler..ctor(int, int)""
IL_0024: ldloca.s V_1
IL_0026: ldc.i4.2
IL_0027: box ""int""
IL_002c: ldc.i4.0
IL_002d: ldnull
IL_002e: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0033: ldloc.1
IL_0034: call ""System.ValueTuple<CustomHandler, CustomHandler>..ctor(CustomHandler, CustomHandler)""
IL_0039: ldloca.s V_0
IL_003b: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item1""
IL_0040: constrained. ""CustomHandler""
IL_0046: callvirt ""string object.ToString()""
IL_004b: call ""void System.Console.Write(string)""
IL_0050: ldloca.s V_0
IL_0052: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item2""
IL_0057: constrained. ""CustomHandler""
IL_005d: callvirt ""string object.ToString()""
IL_0062: call ""void System.Console.WriteLine(string)""
IL_0067: ret
}
");
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Workspaces/Core/Portable/ExternalAccess/Pythia/Api/PythiaEditDistanceWrapper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
internal readonly struct PythiaEditDistanceWrapper : IDisposable
{
private readonly EditDistance _underlyingObject;
public PythiaEditDistanceWrapper(string str)
=> _underlyingObject = new EditDistance(str);
public double GetEditDistance(string target)
=> _underlyingObject.GetEditDistance(target);
public void Dispose()
=> _underlyingObject.Dispose();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
internal readonly struct PythiaEditDistanceWrapper : IDisposable
{
private readonly EditDistance _underlyingObject;
public PythiaEditDistanceWrapper(string str)
=> _underlyingObject = new EditDistance(str);
public double GetEditDistance(string target)
=> _underlyingObject.GetEditDistance(target);
public void Dispose()
=> _underlyingObject.Dispose();
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/EditorFeatures/CSharpTest/ConvertAnonymousTypeToClass/ConvertAnonymousTypeToClassTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.ConvertAnonymousTypeToClass;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAnonymousTypeToClass
{
public class ConvertAnonymousTypeToClassTests : AbstractCSharpCodeActionTest
{
private static readonly ParseOptions CSharp8 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8);
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpConvertAnonymousTypeToClassCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousType()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousType_FileScopedNamespace()
{
var text = @"
namespace N;
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
}
}
";
var expected = @"
namespace N;
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousType_CSharp9()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewRecord|}(1, 2);
}
}
internal record NewRecord(int A, int B);
";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo());
}
[WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousType_Explicit()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass other &&
A == other.A &&
B == other.B;
}
public override int GetHashCode()
{
int hashCode = -1817952719;
hashCode = hashCode * -1521134295 + A.GetHashCode();
hashCode = hashCode * -1521134295 + B.GetHashCode();
return hashCode;
}
}";
await TestInRegularAndScriptAsync(text, expected, parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task OnEmptyAnonymousType()
{
await TestInRegularAndScriptAsync(@"
class Test
{
void Method()
{
var t1 = [||]new { };
}
}
",
@"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}();
}
}
internal class NewClass
{
public NewClass()
{
}
public override bool Equals(object obj)
{
return obj is NewClass other;
}
public override int GetHashCode()
{
return 0;
}
}", parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task OnEmptyAnonymousType_CSharp9()
{
await TestInRegularAndScriptAsync(@"
class Test
{
void Method()
{
var t1 = [||]new { };
}
}
",
@"
class Test
{
void Method()
{
var t1 = new {|Rename:NewRecord|}();
}
}
internal record NewRecord();
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task OnSingleFieldAnonymousType()
{
await TestInRegularAndScriptAsync(@"
class Test
{
void Method()
{
var t1 = [||]new { a = 1 };
}
}
",
@"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1);
}
}
internal class NewClass
{
public int A { get; }
public NewClass(int a)
{
A = a;
}
public override bool Equals(object obj)
{
return obj is NewClass other &&
A == other.A;
}
public override int GetHashCode()
{
return -862436692 + A.GetHashCode();
}
}", parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task OnSingleFieldAnonymousType_CSharp9()
{
await TestInRegularAndScriptAsync(@"
class Test
{
void Method()
{
var t1 = [||]new { a = 1 };
}
}
",
@"
class Test
{
void Method()
{
var t1 = new {|Rename:NewRecord|}(1);
}
}
internal record NewRecord(int A);
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousTypeWithInferredName()
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||]new { a = 1, b };
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new {|Rename:NewClass|}(1, b);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousTypeWithInferredName_CSharp9()
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||]new { a = 1, b };
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new {|Rename:NewRecord|}(1, b);
}
}
internal record NewRecord(int A, int B);
";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertMultipleInstancesInSameMethod()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
var t2 = new NewClass(3, 4);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertMultipleInstancesInSameMethod_CSharp9()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewRecord|}(1, 2);
var t2 = new NewRecord(3, 4);
}
}
internal record NewRecord(int A, int B);
";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertMultipleInstancesAcrossMethods()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
void Method2()
{
var t1 = new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
var t2 = new NewClass(3, 4);
}
void Method2()
{
var t1 = new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task OnlyConvertMatchingTypesInSameMethod()
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||]new { a = 1, b = 2 };
var t2 = new { a = 3, b };
var t3 = new { a = 4 };
var t4 = new { b = 5, a = 6 };
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new {|Rename:NewClass|}(1, 2);
var t2 = new NewClass(3, b);
var t3 = new { a = 4 };
var t4 = new { b = 5, a = 6 };
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestFixAllMatchesInSingleMethod()
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||]new { a = 1, b = 2 };
var t2 = new { a = 3, b };
var t3 = new { a = 4 };
var t4 = new { b = 5, a = 6 };
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new {|Rename:NewClass|}(1, 2);
var t2 = new NewClass(3, b);
var t3 = new { a = 4 };
var t4 = new { b = 5, a = 6 };
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestFixNotAcrossMethods()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
void Method2()
{
var t1 = new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
var t2 = new NewClass(3, 4);
}
void Method2()
{
var t1 = new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestTrivia()
{
var text = @"
class Test
{
void Method()
{
var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ;
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = /*1*/ new {|Rename:NewClass|}( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ;
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestTrivia2()
{
var text = @"
class Test
{
void Method()
{
var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ;
var t2 = /*1*/ new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ;
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = /*1*/ new {|Rename:NewClass|}( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ;
var t2 = /*1*/ new NewClass( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ;
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task NotIfReferencesAnonymousTypeInternally()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = new { c = 1, d = 2 } };
}
}
";
await TestMissingInRegularAndScriptAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertMultipleNestedInstancesInSameMethod()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = (object)new { a = 1, b = default(object) } };
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, (object)new NewClass(1, default(object)));
}
}
internal class NewClass
{
public int A { get; }
public object B { get; }
public NewClass(int a, object b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass other &&
A == other.A &&
EqualityComparer<object>.Default.Equals(B, other.B);
}
public override int GetHashCode()
{
var hashCode = -1817952719;
hashCode = hashCode * -1521134295 + A.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(B);
return hashCode;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task RenameAnnotationOnStartingPoint()
{
var text = @"
class Test
{
void Method()
{
var t1 = new { a = 1, b = 2 };
var t2 = [||]new { a = 3, b = 4 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewClass(1, 2);
var t2 = new {|Rename:NewClass|}(3, 4);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task UpdateReferences()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
Console.WriteLine(t1.a + t1?.b);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
Console.WriteLine(t1.A + t1?.B);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task CapturedTypeParameters()
{
var text = @"
class Test<X> where X : struct
{
void Method<Y>(List<X> x, Y[] y) where Y : class, new()
{
var t1 = [||]new { a = x, b = y };
}
}
";
var expected = @"
class Test<X> where X : struct
{
void Method<Y>(List<X> x, Y[] y) where Y : class, new()
{
var t1 = new {|Rename:NewClass|}<X, Y>(x, y);
}
}
internal class NewClass<X, Y>
where X : struct
where Y : class, new()
{
public List<X> A { get; }
public Y[] B { get; }
public NewClass(List<X> a, Y[] b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass<X, Y> other &&
System.Collections.Generic.EqualityComparer<List<X>>.Default.Equals(A, other.A) &&
System.Collections.Generic.EqualityComparer<Y[]>.Default.Equals(B, other.B);
}
public override int GetHashCode()
{
var hashCode = -1817952719;
hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<List<X>>.Default.GetHashCode(A);
hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<Y[]>.Default.GetHashCode(B);
return hashCode;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task CapturedTypeParameters_CSharp9()
{
var text = @"
class Test<X> where X : struct
{
void Method<Y>(List<X> x, Y[] y) where Y : class, new()
{
var t1 = [||]new { a = x, b = y };
}
}
";
var expected = @"
class Test<X> where X : struct
{
void Method<Y>(List<X> x, Y[] y) where Y : class, new()
{
var t1 = new {|Rename:NewRecord|}<X, Y>(x, y);
}
}
internal record NewRecord<X, Y>(List<X> A, Y[] B)
where X : struct
where Y : class, new();
";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task NewTypeNameCollision()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
}
}
class NewClass
{
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass1|}(1, 2);
}
}
class NewClass
{
}
internal class NewClass1
{
public int A { get; }
public int B { get; }
public NewClass1(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass1 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestDuplicatedName()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, a = 2 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int Item { get; }
public NewClass(int a, int item)
{
A = a;
Item = item;
}
public override bool Equals(object obj)
{
return obj is NewClass other &&
A == other.A &&
Item == other.Item;
}
public override int GetHashCode()
{
var hashCode = -335756622;
hashCode = hashCode * -1521134295 + A.GetHashCode();
hashCode = hashCode * -1521134295 + Item.GetHashCode();
return hashCode;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestDuplicatedName_CSharp9()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, a = 2 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewRecord|}(1, 2);
}
}
internal record NewRecord(int A, int Item);
";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestNewSelection()
{
var text = @"
class Test
{
void Method()
{
var t1 = [|new|] { a = 1, b = 2 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestInLambda1()
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
Action a = () =>
{
var t2 = new { a = 3, b = 4 };
};
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
Action a = () =>
{
var t2 = new NewClass(3, 4);
};
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestInLambda2()
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = new { a = 1, b = 2 };
Action a = () =>
{
var t2 = [||]new { a = 3, b = 4 };
};
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewClass(1, 2);
Action a = () =>
{
var t2 = new {|Rename:NewClass|}(3, 4);
};
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestInLocalFunction1()
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
void Goo()
{
var t2 = new { a = 3, b = 4 };
}
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
void Goo()
{
var t2 = new NewClass(3, 4);
}
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestInLocalFunction2()
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = new { a = 1, b = 2 };
void Goo()
{
var t2 = [||]new { a = 3, b = 4 };
}
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewClass(1, 2);
void Goo()
{
var t2 = new {|Rename:NewClass|}(3, 4);
}
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousTypeSelection1()
{
var text = @"
class Test
{
void Method()
{
var t1 = [|new { a = 1, b = 2 }|];
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousTypeSelection2()
{
var text = @"
class Test
{
void Method()
{
[|var t1 = new { a = 1, b = 2 };|]
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousTypeSelection3()
{
var text = @"
class Test
{
void Method()
{
var t1 = [|new { a = 1, b = 2 };|]
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[WorkItem(45747, "https://github.com/dotnet/roslyn/issues/45747")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertOmittingTrailingComma()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new
{
a = 1,
b = 2,
};
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(
1,
2
);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[WorkItem(45747, "https://github.com/dotnet/roslyn/issues/45747")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertOmittingTrailingCommaButPreservingTrivia()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new
{
a = 1,
b = 2 // and
// more
,
};
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(
1,
2 // and
// more
);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.ConvertAnonymousTypeToClass;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAnonymousTypeToClass
{
public class ConvertAnonymousTypeToClassTests : AbstractCSharpCodeActionTest
{
private static readonly ParseOptions CSharp8 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8);
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpConvertAnonymousTypeToClassCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousType()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousType_FileScopedNamespace()
{
var text = @"
namespace N;
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
}
}
";
var expected = @"
namespace N;
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousType_CSharp9()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewRecord|}(1, 2);
}
}
internal record NewRecord(int A, int B);
";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo());
}
[WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousType_Explicit()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass other &&
A == other.A &&
B == other.B;
}
public override int GetHashCode()
{
int hashCode = -1817952719;
hashCode = hashCode * -1521134295 + A.GetHashCode();
hashCode = hashCode * -1521134295 + B.GetHashCode();
return hashCode;
}
}";
await TestInRegularAndScriptAsync(text, expected, parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task OnEmptyAnonymousType()
{
await TestInRegularAndScriptAsync(@"
class Test
{
void Method()
{
var t1 = [||]new { };
}
}
",
@"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}();
}
}
internal class NewClass
{
public NewClass()
{
}
public override bool Equals(object obj)
{
return obj is NewClass other;
}
public override int GetHashCode()
{
return 0;
}
}", parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task OnEmptyAnonymousType_CSharp9()
{
await TestInRegularAndScriptAsync(@"
class Test
{
void Method()
{
var t1 = [||]new { };
}
}
",
@"
class Test
{
void Method()
{
var t1 = new {|Rename:NewRecord|}();
}
}
internal record NewRecord();
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task OnSingleFieldAnonymousType()
{
await TestInRegularAndScriptAsync(@"
class Test
{
void Method()
{
var t1 = [||]new { a = 1 };
}
}
",
@"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1);
}
}
internal class NewClass
{
public int A { get; }
public NewClass(int a)
{
A = a;
}
public override bool Equals(object obj)
{
return obj is NewClass other &&
A == other.A;
}
public override int GetHashCode()
{
return -862436692 + A.GetHashCode();
}
}", parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task OnSingleFieldAnonymousType_CSharp9()
{
await TestInRegularAndScriptAsync(@"
class Test
{
void Method()
{
var t1 = [||]new { a = 1 };
}
}
",
@"
class Test
{
void Method()
{
var t1 = new {|Rename:NewRecord|}(1);
}
}
internal record NewRecord(int A);
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousTypeWithInferredName()
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||]new { a = 1, b };
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new {|Rename:NewClass|}(1, b);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousTypeWithInferredName_CSharp9()
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||]new { a = 1, b };
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new {|Rename:NewRecord|}(1, b);
}
}
internal record NewRecord(int A, int B);
";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertMultipleInstancesInSameMethod()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
var t2 = new NewClass(3, 4);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertMultipleInstancesInSameMethod_CSharp9()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewRecord|}(1, 2);
var t2 = new NewRecord(3, 4);
}
}
internal record NewRecord(int A, int B);
";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertMultipleInstancesAcrossMethods()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
void Method2()
{
var t1 = new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
var t2 = new NewClass(3, 4);
}
void Method2()
{
var t1 = new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task OnlyConvertMatchingTypesInSameMethod()
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||]new { a = 1, b = 2 };
var t2 = new { a = 3, b };
var t3 = new { a = 4 };
var t4 = new { b = 5, a = 6 };
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new {|Rename:NewClass|}(1, 2);
var t2 = new NewClass(3, b);
var t3 = new { a = 4 };
var t4 = new { b = 5, a = 6 };
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestFixAllMatchesInSingleMethod()
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||]new { a = 1, b = 2 };
var t2 = new { a = 3, b };
var t3 = new { a = 4 };
var t4 = new { b = 5, a = 6 };
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new {|Rename:NewClass|}(1, 2);
var t2 = new NewClass(3, b);
var t3 = new { a = 4 };
var t4 = new { b = 5, a = 6 };
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestFixNotAcrossMethods()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
void Method2()
{
var t1 = new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
var t2 = new NewClass(3, 4);
}
void Method2()
{
var t1 = new { a = 1, b = 2 };
var t2 = new { a = 3, b = 4 };
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestTrivia()
{
var text = @"
class Test
{
void Method()
{
var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ;
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = /*1*/ new {|Rename:NewClass|}( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ;
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestTrivia2()
{
var text = @"
class Test
{
void Method()
{
var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ;
var t2 = /*1*/ new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ;
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = /*1*/ new {|Rename:NewClass|}( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ;
var t2 = /*1*/ new NewClass( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ;
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task NotIfReferencesAnonymousTypeInternally()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = new { c = 1, d = 2 } };
}
}
";
await TestMissingInRegularAndScriptAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertMultipleNestedInstancesInSameMethod()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = (object)new { a = 1, b = default(object) } };
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, (object)new NewClass(1, default(object)));
}
}
internal class NewClass
{
public int A { get; }
public object B { get; }
public NewClass(int a, object b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass other &&
A == other.A &&
EqualityComparer<object>.Default.Equals(B, other.B);
}
public override int GetHashCode()
{
var hashCode = -1817952719;
hashCode = hashCode * -1521134295 + A.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(B);
return hashCode;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task RenameAnnotationOnStartingPoint()
{
var text = @"
class Test
{
void Method()
{
var t1 = new { a = 1, b = 2 };
var t2 = [||]new { a = 3, b = 4 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewClass(1, 2);
var t2 = new {|Rename:NewClass|}(3, 4);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task UpdateReferences()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
Console.WriteLine(t1.a + t1?.b);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
Console.WriteLine(t1.A + t1?.B);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task CapturedTypeParameters()
{
var text = @"
class Test<X> where X : struct
{
void Method<Y>(List<X> x, Y[] y) where Y : class, new()
{
var t1 = [||]new { a = x, b = y };
}
}
";
var expected = @"
class Test<X> where X : struct
{
void Method<Y>(List<X> x, Y[] y) where Y : class, new()
{
var t1 = new {|Rename:NewClass|}<X, Y>(x, y);
}
}
internal class NewClass<X, Y>
where X : struct
where Y : class, new()
{
public List<X> A { get; }
public Y[] B { get; }
public NewClass(List<X> a, Y[] b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass<X, Y> other &&
System.Collections.Generic.EqualityComparer<List<X>>.Default.Equals(A, other.A) &&
System.Collections.Generic.EqualityComparer<Y[]>.Default.Equals(B, other.B);
}
public override int GetHashCode()
{
var hashCode = -1817952719;
hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<List<X>>.Default.GetHashCode(A);
hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<Y[]>.Default.GetHashCode(B);
return hashCode;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task CapturedTypeParameters_CSharp9()
{
var text = @"
class Test<X> where X : struct
{
void Method<Y>(List<X> x, Y[] y) where Y : class, new()
{
var t1 = [||]new { a = x, b = y };
}
}
";
var expected = @"
class Test<X> where X : struct
{
void Method<Y>(List<X> x, Y[] y) where Y : class, new()
{
var t1 = new {|Rename:NewRecord|}<X, Y>(x, y);
}
}
internal record NewRecord<X, Y>(List<X> A, Y[] B)
where X : struct
where Y : class, new();
";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task NewTypeNameCollision()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
}
}
class NewClass
{
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass1|}(1, 2);
}
}
class NewClass
{
}
internal class NewClass1
{
public int A { get; }
public int B { get; }
public NewClass1(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass1 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestDuplicatedName()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, a = 2 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int Item { get; }
public NewClass(int a, int item)
{
A = a;
Item = item;
}
public override bool Equals(object obj)
{
return obj is NewClass other &&
A == other.A &&
Item == other.Item;
}
public override int GetHashCode()
{
var hashCode = -335756622;
hashCode = hashCode * -1521134295 + A.GetHashCode();
hashCode = hashCode * -1521134295 + Item.GetHashCode();
return hashCode;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestDuplicatedName_CSharp9()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new { a = 1, a = 2 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewRecord|}(1, 2);
}
}
internal record NewRecord(int A, int Item);
";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestNewSelection()
{
var text = @"
class Test
{
void Method()
{
var t1 = [|new|] { a = 1, b = 2 };
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestInLambda1()
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
Action a = () =>
{
var t2 = new { a = 3, b = 4 };
};
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
Action a = () =>
{
var t2 = new NewClass(3, 4);
};
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestInLambda2()
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = new { a = 1, b = 2 };
Action a = () =>
{
var t2 = [||]new { a = 3, b = 4 };
};
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewClass(1, 2);
Action a = () =>
{
var t2 = new {|Rename:NewClass|}(3, 4);
};
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestInLocalFunction1()
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = [||]new { a = 1, b = 2 };
void Goo()
{
var t2 = new { a = 3, b = 4 };
}
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
void Goo()
{
var t2 = new NewClass(3, 4);
}
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task TestInLocalFunction2()
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = new { a = 1, b = 2 };
void Goo()
{
var t2 = [||]new { a = 3, b = 4 };
}
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewClass(1, 2);
void Goo()
{
var t2 = new {|Rename:NewClass|}(3, 4);
}
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousTypeSelection1()
{
var text = @"
class Test
{
void Method()
{
var t1 = [|new { a = 1, b = 2 }|];
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousTypeSelection2()
{
var text = @"
class Test
{
void Method()
{
[|var t1 = new { a = 1, b = 2 };|]
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertSingleAnonymousTypeSelection3()
{
var text = @"
class Test
{
void Method()
{
var t1 = [|new { a = 1, b = 2 };|]
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(1, 2);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[WorkItem(45747, "https://github.com/dotnet/roslyn/issues/45747")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertOmittingTrailingComma()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new
{
a = 1,
b = 2,
};
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(
1,
2
);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
[WorkItem(45747, "https://github.com/dotnet/roslyn/issues/45747")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)]
public async Task ConvertOmittingTrailingCommaButPreservingTrivia()
{
var text = @"
class Test
{
void Method()
{
var t1 = [||]new
{
a = 1,
b = 2 // and
// more
,
};
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new {|Rename:NewClass|}(
1,
2 // and
// more
);
}
}
internal class NewClass
{
public int A { get; }
public int B { get; }
public NewClass(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewClass 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;
}
}";
await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8);
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/IVSTypeScriptSignatureHelpClassifierProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal interface IVSTypeScriptSignatureHelpClassifierProvider
{
IClassifier Create(ITextBuffer textBuffer, ClassificationTypeMap typeMap);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal interface IVSTypeScriptSignatureHelpClassifierProvider
{
IClassifier Create(ITextBuffer textBuffer, ClassificationTypeMap typeMap);
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./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 | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationAsyncResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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
// D:\Roslyn\Main\Open\Binaries\Debug\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
{
public struct DkmEvaluationAsyncResult
{
private readonly DkmEvaluationResult _result;
public DkmEvaluationAsyncResult(DkmEvaluationResult Result)
: this()
{
if (Result == null)
{
throw new ArgumentNullException(nameof(Result));
}
_result = Result;
}
public int ErrorCode { get { throw new NotImplementedException(); } }
public DkmEvaluationResult Result { get { return _result; } }
internal Exception Exception { get; set; }
public static DkmEvaluationAsyncResult CreateErrorResult(Exception exception)
{
return new DkmEvaluationAsyncResult() { Exception = exception };
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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
// D:\Roslyn\Main\Open\Binaries\Debug\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
{
public struct DkmEvaluationAsyncResult
{
private readonly DkmEvaluationResult _result;
public DkmEvaluationAsyncResult(DkmEvaluationResult Result)
: this()
{
if (Result == null)
{
throw new ArgumentNullException(nameof(Result));
}
_result = Result;
}
public int ErrorCode { get { throw new NotImplementedException(); } }
public DkmEvaluationResult Result { get { return _result; } }
internal Exception Exception { get; set; }
public static DkmEvaluationAsyncResult CreateErrorResult(Exception exception)
{
return new DkmEvaluationAsyncResult() { Exception = exception };
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/CSharp/Test/Semantic/Semantics/BindingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class BindingTests : CompilingTestBase
{
[Fact, WorkItem(539872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539872")]
public void NoWRN_UnreachableCode()
{
var text = @"
public class Cls
{
public static int Main()
{
goto Label2;
Label1:
return (1);
Label2:
goto Label1;
}
}";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void GenericMethodName()
{
var source =
@"class A
{
class B
{
static void M(System.Action a)
{
M(M1);
M(M2<object>);
M(M3<int>);
}
static void M1() { }
static void M2<T>() { }
}
static void M3<T>() { }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void GenericTypeName()
{
var source =
@"class A
{
class B
{
static void M(System.Type t)
{
M(typeof(C<int>));
M(typeof(S<string, string>));
M(typeof(C<int, int>));
}
class C<T> { }
}
struct S<T, U> { }
}
class C<T, U> { }
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void GenericTypeParameterName()
{
var source =
@"class A<T>
{
class B<U>
{
static void M<V>()
{
N(typeof(V));
N(typeof(U));
N(typeof(T));
}
static void N(System.Type t) { }
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void WrongMethodArity()
{
var source =
@"class C
{
static void M1<T>() { }
static void M2() { }
void M3<T>() { }
void M4() { }
void M()
{
M1<object, object>();
C.M1<object, object>();
M2<int>();
C.M2<int>();
M3<object, object>();
this.M3<object, object>();
M4<int>();
this.M4<int>();
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,9): error CS0305: Using the generic method 'C.M1<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M1<object, object>").WithArguments("C.M1<T>()", "method", "1").WithLocation(9, 9),
// (10,11): error CS0305: Using the generic method 'C.M1<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M1<object, object>").WithArguments("C.M1<T>()", "method", "1").WithLocation(10, 11),
// (11,9): error CS0308: The non-generic method 'C.M2()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M2<int>").WithArguments("C.M2()", "method").WithLocation(11, 9),
// (12,11): error CS0308: The non-generic method 'C.M2()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M2<int>").WithArguments("C.M2()", "method").WithLocation(12, 11),
// (13,9): error CS0305: Using the generic method 'C.M3<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M3<object, object>").WithArguments("C.M3<T>()", "method", "1").WithLocation(13, 9),
// (14,14): error CS0305: Using the generic method 'C.M3<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M3<object, object>").WithArguments("C.M3<T>()", "method", "1").WithLocation(14, 14),
// (15,9): error CS0308: The non-generic method 'C.M4()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M4<int>").WithArguments("C.M4()", "method").WithLocation(15, 9),
// (16,14): error CS0308: The non-generic method 'C.M4()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M4<int>").WithArguments("C.M4()", "method").WithLocation(16, 14));
}
[Fact]
public void AmbiguousInaccessibleMethod()
{
var source =
@"class A
{
protected void M1() { }
protected void M1(object o) { }
protected void M2(string s) { }
protected void M2(object o) { }
}
class B
{
static void M(A a)
{
a.M1();
a.M2();
M(a.M1);
M(a.M2);
}
static void M(System.Action<object> a) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (12,11): error CS0122: 'A.M1()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("A.M1()").WithLocation(12, 11),
// (13,11): error CS0122: 'A.M2(string)' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("A.M2(string)").WithLocation(13, 11),
// (14,13): error CS0122: 'A.M1()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("A.M1()").WithLocation(14, 13),
// (15,13): error CS0122: 'A.M2(string)' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("A.M2(string)").WithLocation(15, 13));
}
/// <summary>
/// Should report inaccessible method, even when using
/// method as a delegate in an invalid context.
/// </summary>
[Fact]
public void InaccessibleMethodInvalidDelegateUse()
{
var source =
@"class A
{
protected object F() { return null; }
}
class B
{
static void M(A a)
{
if (a.F != null)
{
M(a.F);
a.F.ToString();
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,15): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(9, 15),
// (11,17): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(11, 17),
// (12,15): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(12, 15));
}
/// <summary>
/// Methods should be resolved correctly even
/// in cases where a method group is not allowed.
/// </summary>
[Fact]
public void InvalidUseOfMethodGroup()
{
var source =
@"class A
{
internal object E() { return null; }
private object F() { return null; }
}
class B
{
static void M(A a)
{
object o;
a.E += a.E;
if (a.E != null)
{
M(a.E);
a.E.ToString();
o = !a.E;
o = a.E ?? a.F;
}
a.F += a.F;
if (a.F != null)
{
M(a.F);
a.F.ToString();
o = !a.F;
o = (o != null) ? a.E : a.F;
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (11,9): error CS1656: Cannot assign to 'E' because it is a 'method group'
// a.E += a.E;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "a.E").WithArguments("E", "method group").WithLocation(11, 9),
// (14,15): error CS1503: Argument 1: cannot convert from 'method group' to 'A'
// M(a.E);
Diagnostic(ErrorCode.ERR_BadArgType, "a.E").WithArguments("1", "method group", "A").WithLocation(14, 15),
// (15,15): error CS0119: 'A.E()' is a method, which is not valid in the given context
// a.E.ToString();
Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("A.E()", "method").WithLocation(15, 15),
// (16,17): error CS0023: Operator '!' cannot be applied to operand of type 'method group'
// o = !a.E;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "!a.E").WithArguments("!", "method group").WithLocation(16, 17),
// (17,26): error CS0122: 'A.F()' is inaccessible due to its protection level
// o = a.E ?? a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(17, 26),
// (19,11): error CS0122: 'A.F()' is inaccessible due to its protection level
// a.F += a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(19, 11),
// (19,18): error CS0122: 'A.F()' is inaccessible due to its protection level
// a.F += a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(19, 18),
// (20,15): error CS0122: 'A.F()' is inaccessible due to its protection level
// if (a.F != null)
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(20, 15),
// (22,17): error CS0122: 'A.F()' is inaccessible due to its protection level
// M(a.F);
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(22, 17),
// (23,15): error CS0122: 'A.F()' is inaccessible due to its protection level
// a.F.ToString();
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(23, 15),
// (24,20): error CS0122: 'A.F()' is inaccessible due to its protection level
// o = !a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(24, 20),
// (25,39): error CS0122: 'A.F()' is inaccessible due to its protection level
// o = (o != null) ? a.E : a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(25, 39));
}
[WorkItem(528425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528425")]
[Fact(Skip = "528425")]
public void InaccessibleAndAccessible()
{
var source =
@"using System;
class A
{
void F() { }
internal void F(object o) { }
static void G() { }
internal static void G(object o) { }
void H(object o) { }
}
class B : A
{
static void M(A a)
{
a.F(null);
a.F();
A.G();
M1(a.F);
M2(a.F);
Action<object> a1 = a.F;
Action a2 = a.F;
}
void M()
{
G();
}
static void M1(Action<object> a) { }
static void M2(Action a) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (15,11): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(15, 11),
// (16,11): error CS0122: 'A.G()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(16, 11),
// (18,12): error CS1503: Argument 1: cannot convert from 'method group' to 'System.Action'
Diagnostic(ErrorCode.ERR_BadArgType, "a.F").WithArguments("1", "method group", "System.Action").WithLocation(18, 12),
// (20,23): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(20, 23),
// (24,9): error CS0122: 'A.G()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(24, 9));
}
[Fact]
public void InaccessibleAndAccessibleAndAmbiguous()
{
var source =
@"class A
{
void F(string x) { }
void F(string x, string y) { }
internal void F(object x, string y) { }
internal void F(string x, object y) { }
void G(object x, string y) { }
internal void G(string x, object y) { }
static void M(A a, string s)
{
a.F(s, s); // no error
}
}
class B
{
static void M(A a, string s, object o)
{
a.F(s, s); // accessible ambiguous
a.G(s, s); // accessible and inaccessible ambiguous, no error
a.G(o, o); // accessible and inaccessible invalid
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'A.F(object, string)' and 'A.F(string, object)'
Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("A.F(object, string)", "A.F(string, object)").WithLocation(18, 11),
// (20,13): error CS1503: Argument 1: cannot convert from 'object' to 'string'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("1", "object", "string").WithLocation(20, 13));
}
[Fact]
public void InaccessibleAndAccessibleValid()
{
var source =
@"class A
{
void F(int i) { }
internal void F(long l) { }
static void M(A a)
{
a.F(1); // no error
}
}
class B
{
static void M(A a)
{
a.F(1); // no error
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void ParenthesizedDelegate()
{
var source =
@"class C
{
System.Action<object> F = null;
void M()
{
((this.F))(null);
(new C().F)(null, null);
}
}";
CreateCompilation(source).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(new C().F)").WithArguments("System.Action<object>", "2").WithLocation(7, 9));
}
/// <summary>
/// Report errors for invocation expressions for non-invocable expressions,
/// and bind arguments even though invocation expression was invalid.
/// </summary>
[Fact]
public void NonMethodsWithArgs()
{
var source =
@"namespace N
{
class C<T>
{
object F;
object P { get; set; }
void M()
{
N(a);
C<string>(b);
N.C<int>(c);
N.D(d);
T(e);
(typeof(C<int>))(f);
P(g) = F(h);
this.F(i) = (this).P(j);
null.M(k);
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,15): error CS0103: The name 'a' does not exist in the current context
// N(a);
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a"),
// (9,13): error CS0118: 'N' is a namespace but is used like a variable
// N(a);
Diagnostic(ErrorCode.ERR_BadSKknown, "N").WithArguments("N", "namespace", "variable"),
// (10,23): error CS0103: The name 'b' does not exist in the current context
// C<string>(b);
Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b"),
// (10,13): error CS1955: Non-invocable member 'N.C<T>' cannot be used like a method.
// C<string>(b);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "C<string>").WithArguments("N.C<T>"),
// (11,22): error CS0103: The name 'c' does not exist in the current context
// N.C<int>(c);
Diagnostic(ErrorCode.ERR_NameNotInContext, "c").WithArguments("c"),
// (11,15): error CS1955: Non-invocable member 'N.C<T>' cannot be used like a method.
// N.C<int>(c);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "C<int>").WithArguments("N.C<T>"),
// (12,17): error CS0103: The name 'd' does not exist in the current context
// N.D(d);
Diagnostic(ErrorCode.ERR_NameNotInContext, "d").WithArguments("d"),
// (12,13): error CS0234: The type or namespace name 'D' does not exist in the namespace 'N' (are you missing an assembly reference?)
// N.D(d);
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "N.D").WithArguments("D", "N"),
// (13,15): error CS0103: The name 'e' does not exist in the current context
// T(e);
Diagnostic(ErrorCode.ERR_NameNotInContext, "e").WithArguments("e"),
// (13,13): error CS0103: The name 'T' does not exist in the current context
// T(e);
Diagnostic(ErrorCode.ERR_NameNotInContext, "T").WithArguments("T"),
// (14,30): error CS0103: The name 'f' does not exist in the current context
// (typeof(C<int>))(f);
Diagnostic(ErrorCode.ERR_NameNotInContext, "f").WithArguments("f"),
// (14,13): error CS0149: Method name expected
// (typeof(C<int>))(f);
Diagnostic(ErrorCode.ERR_MethodNameExpected, "(typeof(C<int>))"),
// (15,15): error CS0103: The name 'g' does not exist in the current context
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NameNotInContext, "g").WithArguments("g"),
// (15,13): error CS1955: Non-invocable member 'N.C<T>.P' cannot be used like a method.
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("N.C<T>.P"),
// (15,22): error CS0103: The name 'h' does not exist in the current context
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NameNotInContext, "h").WithArguments("h"),
// (15,20): error CS1955: Non-invocable member 'N.C<T>.F' cannot be used like a method.
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("N.C<T>.F"),
// (16,20): error CS0103: The name 'i' does not exist in the current context
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i"),
// (16,18): error CS1955: Non-invocable member 'N.C<T>.F' cannot be used like a method.
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("N.C<T>.F"),
// (16,34): error CS0103: The name 'j' does not exist in the current context
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NameNotInContext, "j").WithArguments("j"),
// (16,32): error CS1955: Non-invocable member 'N.C<T>.P' cannot be used like a method.
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("N.C<T>.P"),
// (17,20): error CS0103: The name 'k' does not exist in the current context
// null.M(k);
Diagnostic(ErrorCode.ERR_NameNotInContext, "k").WithArguments("k"),
// (17,13): error CS0023: Operator '.' cannot be applied to operand of type '<null>'
// null.M(k);
Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.M").WithArguments(".", "<null>"),
// (5,16): warning CS0649: Field 'N.C<T>.F' is never assigned to, and will always have its default value null
// object F;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("N.C<T>.F", "null")
);
}
[Fact]
public void SimpleDelegates()
{
var source =
@"static class S
{
public static void F(System.Action a) { }
}
class C
{
void M()
{
S.F(this.M);
System.Action a = this.M;
S.F(a);
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void DelegatesFromOverloads()
{
var source =
@"using System;
class C
{
static void A(Action<object> a) { }
static void M(C c)
{
A(C.F);
A(c.G);
Action<object> a;
a = C.F;
a = c.G;
}
static void F() { }
static void F(object o) { }
void G(object o) { }
void G(object x, object y) { }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void NonViableDelegates()
{
var source =
@"using System;
class A
{
static Action F = null;
Action G = null;
}
class B
{
static void M(A a)
{
A.F(x);
a.G(y);
}
}";
CreateCompilation(source).VerifyDiagnostics( // (11,13): error CS0103: The name 'x' does not exist in the current context
// A.F(x);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"),
// (11,11): error CS0122: 'A.F' is inaccessible due to its protection level
// A.F(x);
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F"),
// (12,13): error CS0103: The name 'y' does not exist in the current context
// a.G(y);
Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y"),
// (12,11): error CS0122: 'A.G' is inaccessible due to its protection level
// a.G(y);
Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"),
// (4,19): warning CS0414: The field 'A.F' is assigned but its value is never used
// static Action F = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A.F"),
// (5,12): warning CS0414: The field 'A.G' is assigned but its value is never used
// Action G = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "G").WithArguments("A.G")
);
}
/// <summary>
/// Choose one method if overloaded methods are
/// equally invalid.
/// </summary>
[Fact]
public void ChooseOneMethodIfEquallyInvalid()
{
var source =
@"internal static class S
{
public static void M(double x, A y) { }
public static void M(double x, B y) { }
}
class A { }
class B { }
class C
{
static void M()
{
S.M(1.0, null); // ambiguous
S.M(1.0, 2.0); // equally invalid
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'S.M(double, A)' and 'S.M(double, B)'
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("S.M(double, A)", "S.M(double, B)").WithLocation(12, 11),
// (13,18): error CS1503: Argument 2: cannot convert from 'double' to 'A'
Diagnostic(ErrorCode.ERR_BadArgType, "2.0").WithArguments("2", "double", "A").WithLocation(13, 18));
}
[Fact]
public void ChooseExpandedFormIfBadArgCountAndBadArgument()
{
var source =
@"class C
{
static void M(object o)
{
F();
F(o);
F(1, o);
F(1, 2, o);
}
static void F(int i, params int[] args) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'C.F(int, params int[])'
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "F").WithArguments("i", "C.F(int, params int[])").WithLocation(5, 9),
// (6,11): error CS1503: Argument 1: cannot convert from 'object' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("1", "object", "int").WithLocation(6, 11),
// (7,14): error CS1503: Argument 2: cannot convert from 'object' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("2", "object", "int").WithLocation(7, 14),
// (8,17): error CS1503: Argument 3: cannot convert from 'object' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("3", "object", "int").WithLocation(8, 17));
}
[Fact]
public void AmbiguousAndBadArgument()
{
var source =
@"class C
{
static void F(int x, double y) { }
static void F(double x, int y) { }
static void M()
{
F(1, 2);
F(1.0, 2.0);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.F(int, double)' and 'C.F(double, int)'
Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("C.F(int, double)", "C.F(double, int)").WithLocation(7, 9),
// (8,11): error CS1503: Argument 1: cannot convert from 'double' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "1.0").WithArguments("1", "double", "int").WithLocation(8, 11));
}
[WorkItem(541050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541050")]
[Fact]
public void IncompleteDelegateDecl()
{
var source =
@"namespace nms {
delegate";
CreateCompilation(source).VerifyDiagnostics(
// (3,9): error CS1031: Type expected
// delegate
Diagnostic(ErrorCode.ERR_TypeExpected, ""),
// (3,9): error CS1001: Identifier expected
// delegate
Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
// (3,9): error CS1003: Syntax error, '(' expected
// delegate
Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", ""),
// (3,9): error CS1026: ) expected
// delegate
Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
// (3,9): error CS1002: ; expected
// delegate
Diagnostic(ErrorCode.ERR_SemicolonExpected, ""),
// (3,9): error CS1513: } expected
// delegate
Diagnostic(ErrorCode.ERR_RbraceExpected, ""));
}
[WorkItem(541213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541213")]
[Fact]
public void IncompleteElsePartInIfStmt()
{
var source =
@"public class Test
{
public static int Main(string [] args)
{
if (true)
{
}
else
";
CreateCompilation(source).VerifyDiagnostics(
// (8,13): error CS1733: Expected expression
// else
Diagnostic(ErrorCode.ERR_ExpressionExpected, ""),
// (9,1): error CS1002: ; expected
//
Diagnostic(ErrorCode.ERR_SemicolonExpected, ""),
// (9,1): error CS1513: } expected
//
Diagnostic(ErrorCode.ERR_RbraceExpected, ""),
// (9,1): error CS1513: } expected
//
Diagnostic(ErrorCode.ERR_RbraceExpected, ""),
// (3,23): error CS0161: 'Test.Main(string[])': not all code paths return a value
// public static int Main(string [] args)
Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("Test.Main(string[])")
);
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest01()
{
var baseAssembly = CreateCompilation(
@"
namespace BaseAssembly {
public class BaseClass {
}
}
", assemblyName: "BaseAssembly1").VerifyDiagnostics();
var derivedAssembly = CreateCompilation(
@"
namespace DerivedAssembly {
public class DerivedClass: BaseAssembly.BaseClass {
public static int IntField = 123;
}
}
", assemblyName: "DerivedAssembly1", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics();
var testAssembly = CreateCompilation(
@"
using ClassAlias = DerivedAssembly.DerivedClass;
public class Test
{
static void Main()
{
int a = ClassAlias.IntField;
int b = ClassAlias.IntField;
}
}
", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() })
.VerifyDiagnostics();
// NOTE: Dev10 errors:
// <fine-name>(7,9): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest02()
{
var baseAssembly = CreateCompilation(
@"
namespace BaseAssembly {
public class BaseClass {
}
}
", assemblyName: "BaseAssembly2").VerifyDiagnostics();
var derivedAssembly = CreateCompilation(
@"
namespace DerivedAssembly {
public class DerivedClass: BaseAssembly.BaseClass {
public static int IntField = 123;
}
}
", assemblyName: "DerivedAssembly2", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics();
var testAssembly = CreateCompilation(
@"
using ClassAlias = DerivedAssembly.DerivedClass;
public class Test
{
static void Main()
{
ClassAlias a = new ClassAlias();
ClassAlias b = new ClassAlias();
}
}
", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() })
.VerifyDiagnostics();
// NOTE: Dev10 errors:
// <fine-name>(6,9): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest03()
{
var baseAssembly = CreateCompilation(
@"
namespace BaseAssembly {
public class BaseClass {
}
}
", assemblyName: "BaseAssembly3").VerifyDiagnostics();
var derivedAssembly = CreateCompilation(
@"
namespace DerivedAssembly {
public class DerivedClass: BaseAssembly.BaseClass {
public static int IntField = 123;
}
}
", assemblyName: "DerivedAssembly3", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics();
var testAssembly = CreateCompilation(
@"
using ClassAlias = DerivedAssembly.DerivedClass;
public class Test
{
ClassAlias a = null;
ClassAlias b = null;
ClassAlias m() { return null; }
void m2(ClassAlias p) { }
}", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() })
.VerifyDiagnostics(
// (5,16): warning CS0414: The field 'Test.a' is assigned but its value is never used
// ClassAlias a = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("Test.a"),
// (6,16): warning CS0414: The field 'Test.b' is assigned but its value is never used
// ClassAlias b = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("Test.b")
);
// NOTE: Dev10 errors:
// <fine-name>(4,16): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_Typical()
{
string scenarioCode = @"
public class ITT
: IInterfaceBase
{ }
public interface IInterfaceBase
{
void bar();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.bar()'
// : IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.bar()").WithLocation(3, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_FullyQualified()
{
// Using fully Qualified names
string scenarioCode = @"
public class ITT
: test.IInterfaceBase
{ }
namespace test
{
public interface IInterfaceBase
{
void bar();
}
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.bar()'
// : test.IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "test.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.bar()").WithLocation(3, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithAlias()
{
// Using Alias
string scenarioCode = @"
using a1 = test;
public class ITT
: a1.IInterfaceBase
{ }
namespace test
{
public interface IInterfaceBase
{
void bar();
}
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (5,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.bar()'
// : a1.IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.bar()").WithLocation(5, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario01()
{
// Two interfaces, neither implemented with alias - should have 2 errors each squiggling a different interface type.
string scenarioCode = @"
using a1 = test;
public class ITT
: a1.IInterfaceBase, a1.IInterfaceBase2
{ }
namespace test
{
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void xyz();
}
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (5,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.xyz()'
// : a1.IInterfaceBase, a1.IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.xyz()").WithLocation(5, 7),
// (5,26): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase2.xyz()'
// : a1.IInterfaceBase, a1.IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase2").WithArguments("ITT", "test.IInterfaceBase2.xyz()").WithLocation(5, 26));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario02()
{
// Two interfaces, only the second is implemented
string scenarioCode = @"
public class ITT
: IInterfaceBase, IInterfaceBase2
{
void IInterfaceBase2.abc()
{ }
}
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void abc();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// : IInterfaceBase, IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(3, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario03()
{
// Two interfaces, only the first is implemented
string scenarioCode = @"
public class ITT
: IInterfaceBase, IInterfaceBase2
{
void IInterfaceBase.xyz()
{ }
}
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void abc();
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,23): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase2.abc()'
// : IInterfaceBase, IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase2").WithArguments("ITT", "IInterfaceBase2.abc()").WithLocation(3, 23));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario04()
{
// Two interfaces, neither implemented but formatting of interfaces are on different lines
string scenarioCode = @"
public class ITT
: IInterfaceBase,
IInterfaceBase2
{ }
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void xyz();
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// : IInterfaceBase,
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(3, 7),
// (4,6): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase2.xyz()'
// IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase2").WithArguments("ITT", "IInterfaceBase2.xyz()").WithLocation(4, 6));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario05()
{
// Inherited Interface scenario
// With methods not implemented in both base and derived.
// Should reflect 2 diagnostics but both with be squiggling the derived as we are not
// explicitly implementing base.
string scenarioCode = @"
public class ITT: IDerived
{ }
interface IInterfaceBase
{
void xyzb();
}
interface IDerived : IInterfaceBase
{
void xyzd();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,19): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()'
// public class ITT: IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 19),
// (2,19): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyzb()'
// public class ITT: IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IInterfaceBase.xyzb()").WithLocation(2, 19));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario06()
{
// Inherited Interface scenario
string scenarioCode = @"
public class ITT: IDerived, IInterfaceBase
{ }
interface IInterfaceBase
{
void xyz();
}
interface IDerived : IInterfaceBase
{
void xyzd();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,19): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()'
// public class ITT: IDerived, IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 19),
// (2,29): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// public class ITT: IDerived, IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(2, 29));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario07()
{
// Inherited Interface scenario - different order.
string scenarioCode = @"
public class ITT: IInterfaceBase, IDerived
{ }
interface IDerived : IInterfaceBase
{
void xyzd();
}
interface IInterfaceBase
{
void xyz();
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,35): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()'
// public class ITT: IInterfaceBase, IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 35),
// (2,19): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// public class ITT: IInterfaceBase, IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(2, 19));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario08()
{
// Inherited Interface scenario
string scenarioCode = @"
public class ITT: IDerived2
{}
interface IBase
{
void method1();
}
interface IBase2
{
void Method2();
}
interface IDerived2: IBase, IBase2
{}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,19): error CS0535: 'ITT' does not implement interface member 'IBase.method1()'
// public class ITT: IDerived2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived2").WithArguments("ITT", "IBase.method1()").WithLocation(2, 19),
// (2,19): error CS0535: 'ITT' does not implement interface member 'IBase2.Method2()'
// public class ITT: IDerived2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived2").WithArguments("ITT", "IBase2.Method2()").WithLocation(2, 19));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation13UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario09()
{
// Inherited Interface scenario.
string scenarioCode = @"
public class ITT : IDerived
{
void IBase2.method2()
{ }
void IDerived.method3()
{ }
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IDerived : IBase, IBase2
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,20): error CS0535: 'ITT' does not implement interface member 'IBase.method1()'
// public class ITT : IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IBase.method1()").WithLocation(2, 20));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario10()
{
// Inherited Interface scenario.
string scenarioCode = @"
public class ITT : IDerived
{
void IBase2.method2()
{ }
void IBase3.method3()
{ }
void IDerived.method4()
{ }
}
public interface IBase
{
void method1();
}
public interface IBase2 : IBase
{
void method2();
}
public interface IBase3 : IBase
{
void method3();
}
public interface IDerived : IBase2, IBase3
{
void method4();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,20): error CS0535: 'ITT' does not implement interface member 'IBase.method1()'
// public class ITT : IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IBase.method1()").WithLocation(2, 20));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario11()
{
// Inherited Interface scenario
string scenarioCode = @"
static class Module1
{
public static void Main()
{
}
}
interface Ibase
{
void method1();
}
interface Ibase2
{
void method2();
}
interface Iderived : Ibase
{
void method3();
}
interface Iderived2 : Iderived
{
void method4();
}
class foo : Iderived2, Iderived, Ibase, Ibase2
{
void Ibase.method1()
{ }
void Ibase2.method2()
{ }
void Iderived2.method4()
{ }
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (29,24): error CS0535: 'foo' does not implement interface member 'Iderived.method3()'
// class foo : Iderived2, Iderived, Ibase, Ibase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Iderived").WithArguments("foo", "Iderived.method3()").WithLocation(29, 24));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithPartialClass01()
{
// partial class - missing method.
// each partial implements interface but one is missing method.
string scenarioCode = @"
public partial class Foo : IBase
{
void IBase.method1()
{ }
void IBase2.method2()
{ }
}
public partial class Foo : IBase2
{
}
public partial class Foo : IBase3
{
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IBase3
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (15,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()'
// public partial class Foo : IBase3
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(15, 28));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithPartialClass02()
{
// partial class - missing method. diagnostic is reported in correct partial class
// one partial class specifically does include any inherited interface
string scenarioCode = @"
public partial class Foo : IBase, IBase2
{
void IBase.method1()
{ }
}
public partial class Foo
{
}
public partial class Foo : IBase3
{
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IBase3
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,35): error CS0535: 'Foo' does not implement interface member 'IBase2.method2()'
// public partial class Foo : IBase, IBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase2").WithArguments("Foo", "IBase2.method2()").WithLocation(2, 35),
// (13,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()'
// public partial class Foo : IBase3
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(13, 28));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithPartialClass03()
{
// Partial class scenario
// One class implements multiple interfaces and is missing method.
string scenarioCode = @"
public partial class Foo : IBase, IBase2
{
void IBase.method1()
{ }
}
public partial class Foo : IBase3
{
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IBase3
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,35): error CS0535: 'Foo' does not implement interface member 'IBase2.method2()'
// public partial class Foo : IBase, IBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase2").WithArguments("Foo", "IBase2.method2()").WithLocation(2, 35),
// (9,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()'
// public partial class Foo : IBase3
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(9, 28)
);
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest04()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
void m()
{
int a = ClassAlias.Class1Foo();
int b = ClassAlias.Class1Foo();
}
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (7,28): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// int a = ClassAlias.Class1Foo();
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1Foo").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (8,28): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// int b = ClassAlias.Class1Foo();
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1Foo").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")
);
// NOTE: Dev10 errors:
// <fine-name>(8,28): error CS0117: 'Class1' does not contain a definition for 'Class1Foo'
// <fine-name>(9,28): error CS0117: 'Class1' does not contain a definition for 'Class1Foo'
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest05()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
void m()
{
var a = new ClassAlias();
var b = new ClassAlias();
}
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")
);
// NOTE: Dev10 errors:
// <fine-name>(8,17): error CS0143: The type 'Class1' has no constructors defined
// <fine-name>(9,17): error CS0143: The type 'Class1' has no constructors defined
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest06()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
ClassAlias a = null;
ClassAlias b = null;
ClassAlias m() { return null; }
void m2(ClassAlias p) { }
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (6,16): warning CS0414: The field 'Test.b' is assigned but its value is never used
// ClassAlias b = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("Test.b"),
// (5,16): warning CS0414: The field 'Test.a' is assigned but its value is never used
// ClassAlias a = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("Test.a")
);
// NOTE: Dev10 errors:
// <fine-name>(4,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
// <fine-name>(5,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
// <fine-name>(6,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
// <fine-name>(7,10): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest07()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
void m()
{
ClassAlias a = null;
ClassAlias b = null;
System.Console.WriteLine(a);
System.Console.WriteLine(b);
}
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (9,9): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// System.Console.WriteLine(a);
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "System.Console.WriteLine").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (10,9): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// System.Console.WriteLine(b);
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "System.Console.WriteLine").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"));
// NOTE: Dev10 reports NO ERRORS
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_1()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_1");
var source2 = @"
public interface IBar
{
ImageMoniker? Moniker { get; }
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_1");
var source3 = @"
public class BarImpl : IBar
{
public ImageMoniker? Moniker
{
get { return null; }
}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_2()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_2");
var source2 = @"
public interface IBar
{
ImageMoniker? Moniker { get; }
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_2");
var source3 = @"
public class BarImpl : IBar
{
ImageMoniker? IBar.Moniker
{
get { return null; }
}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (4,24): error CS0539: 'BarImpl.Moniker' in explicit interface declaration is not a member of interface
// ImageMoniker? IBar.Moniker
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Moniker").WithArguments("BarImpl.Moniker").WithLocation(4, 24),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (4,24): error CS0539: 'BarImpl.Moniker' in explicit interface declaration is not a member of interface
// ImageMoniker? IBar.Moniker
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Moniker").WithArguments("BarImpl.Moniker").WithLocation(4, 24),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_3()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_3");
var source2 = @"
public interface IBar
{
void SetMoniker(ImageMoniker? moniker);
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_3");
var source3 = @"
public class BarImpl : IBar
{
public void SetMoniker(ImageMoniker? moniker)
{}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_4()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_4");
var source2 = @"
public interface IBar
{
void SetMoniker(ImageMoniker? moniker);
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_4");
var source3 = @"
public class BarImpl : IBar
{
void IBar.SetMoniker(ImageMoniker? moniker)
{}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (4,15): error CS0539: 'BarImpl.SetMoniker(ImageMoniker?)' in explicit interface declaration is not a member of interface
// void IBar.SetMoniker(ImageMoniker? moniker)
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "SetMoniker").WithArguments("BarImpl.SetMoniker(ImageMoniker?)").WithLocation(4, 15),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (4,15): error CS0539: 'BarImpl.SetMoniker(ImageMoniker?)' in explicit interface declaration is not a member of interface
// void IBar.SetMoniker(ImageMoniker? moniker)
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "SetMoniker").WithArguments("BarImpl.SetMoniker(ImageMoniker?)").WithLocation(4, 15),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(541246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541246")]
[Fact]
public void NamespaceQualifiedGenericTypeName()
{
var source =
@"namespace N
{
public class A<T>
{
public static T F;
}
}
class B
{
static int G = N.A<int>.F;
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void NamespaceQualifiedGenericTypeNameWrongArity()
{
var source =
@"namespace N
{
public class A<T>
{
public static T F;
}
public class B
{
public static int F;
}
public class B<T1, T2>
{
public static System.Tuple<T1, T2> F;
}
}
class C
{
static int TooMany = N.A<int, int>.F;
static int TooFew = N.A.F;
static int TooIndecisive = N.B<int>;
}";
CreateCompilation(source).VerifyDiagnostics(
// (19,28): error CS0305: Using the generic type 'N.A<T>' requires '1' type arguments
//
Diagnostic(ErrorCode.ERR_BadArity, "A<int, int>").WithArguments("N.A<T>", "type", "1"),
// (20,27): error CS0305: Using the generic type 'N.A<T>' requires '1' type arguments
//
Diagnostic(ErrorCode.ERR_BadArity, "A").WithArguments("N.A<T>", "type", "1"),
// (21,34): error CS0308: The non-generic type 'N.B' cannot be used with type arguments
//
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "B<int>").WithArguments("N.B", "type")
);
}
[WorkItem(541570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541570")]
[Fact]
public void EnumNotMemberInConstructor()
{
var source =
@"enum E { A }
class C
{
public C(E e = E.A) { }
public E E { get { return E.A; } }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(541638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541638")]
[Fact]
public void KeywordAsLabelIdentifier()
{
var source =
@"class Program
{
static void Main(string[] args)
{
@int1:
System.Console.WriteLine();
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,5): warning CS0164: This label has not been referenced
//
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "@int1"));
}
[WorkItem(541677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541677")]
[Fact]
public void AssignStaticEventToLocalVariable()
{
var source =
@"delegate void Foo();
class driver
{
public static event Foo e;
static void Main(string[] args)
{
Foo x = e;
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
// Note: The locations for errors on generic methods are
// name only, while Dev11 uses name + type parameters.
[WorkItem(528743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528743")]
[Fact]
public void GenericMethodLocation()
{
var source =
@"interface I
{
void M1<T>() where T : class;
}
class C : I
{
public void M1<T>() { }
void M2<T>(this object o) { }
sealed void M3<T>() { }
internal static virtual void M4<T>() { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,7): error CS1106: Extension method must be defined in a non-generic static class
// class C : I
Diagnostic(ErrorCode.ERR_BadExtensionAgg, "C").WithLocation(5, 7),
// (7,17): error CS0425: The constraints for type parameter 'T' of method 'C.M1<T>()' must match the constraints for type parameter 'T' of interface method 'I.M1<T>()'. Consider using an explicit interface implementation instead.
// public void M1<T>() { }
Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "C.M1<T>()", "T", "I.M1<T>()").WithLocation(7, 17),
// (9,17): error CS0238: 'C.M3<T>()' cannot be sealed because it is not an override
// sealed void M3<T>() { }
Diagnostic(ErrorCode.ERR_SealedNonOverride, "M3").WithArguments("C.M3<T>()").WithLocation(9, 17),
// (10,34): error CS0112: A static member cannot be marked as 'virtual'
// internal static virtual void M4<T>() { }
Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M4").WithArguments("virtual").WithLocation(10, 34)
);
}
[WorkItem(542391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542391")]
[Fact]
public void PartialMethodOptionalParameters()
{
var source =
@"partial class C
{
partial void M1(object o);
partial void M1(object o = null) { }
partial void M2(object o = null);
partial void M2(object o) { }
partial void M3(object o = null);
partial void M3(object o = null) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,28): warning CS1066: The default value specified for parameter 'o' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments
// partial void M1(object o = null) { }
Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "o").WithArguments("o"),
// (8,28): warning CS1066: The default value specified for parameter 'o' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments
// partial void M3(object o = null) { }
Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "o").WithArguments("o")
);
}
[Fact]
[WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")]
public void PartialMethodParameterNamesFromDefinition1()
{
var source = @"
partial class C
{
partial void F(int i);
}
partial class C
{
partial void F(int j) { }
}
";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<MethodSymbol>("F");
Assert.Equal("i", method.Parameters[0].Name);
});
}
[Fact]
[WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")]
public void PartialMethodParameterNamesFromDefinition2()
{
var source = @"
partial class C
{
partial void F(int j) { }
}
partial class C
{
partial void F(int i);
}
";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<MethodSymbol>("F");
Assert.Equal("i", method.Parameters[0].Name);
});
}
/// <summary>
/// Handle a mix of parameter errors for default values,
/// partial methods, and static parameter type.
/// </summary>
[Fact]
public void ParameterErrorsDefaultPartialMethodStaticType()
{
var source =
@"static class S { }
partial class C
{
partial void M(S s = new A());
partial void M(S s = new B()) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,18): error CS0721: 'S': static types cannot be used as parameters
// partial void M(S s = new A());
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M").WithArguments("S").WithLocation(4, 18),
// (5,18): error CS0721: 'S': static types cannot be used as parameters
// partial void M(S s = new B()) { }
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M").WithArguments("S").WithLocation(5, 18),
// (5,30): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)
// partial void M(S s = new B()) { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(5, 30),
// (4,30): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// partial void M(S s = new A());
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(4, 30)
);
}
[WorkItem(543349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543349")]
[Fact]
public void Fixed()
{
var source =
@"class C
{
unsafe static void M(int[] arg)
{
fixed (int* ptr = arg) { }
fixed (int* ptr = arg) *ptr = 0;
fixed (int* ptr = arg) object o = null;
}
}";
CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,32): error CS1023: Embedded statement cannot be a declaration or labeled statement
// fixed (int* ptr = arg) object o = null;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "object o = null;").WithLocation(7, 32),
// (7,39): warning CS0219: The variable 'o' is assigned but its value is never used
// fixed (int* ptr = arg) object o = null;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o").WithArguments("o").WithLocation(7, 39)
);
}
[WorkItem(1040171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040171")]
[Fact]
public void Bug1040171()
{
const string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
foreach (string s in args)
label: c = false;
}
}
";
var compilation = CreateCompilation(sourceCode);
compilation.VerifyDiagnostics(
// (9,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// label: c = false;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "label: c = false;").WithLocation(9, 13),
// (9,13): warning CS0164: This label has not been referenced
// label: c = false;
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(9, 13),
// (6,14): warning CS0219: The variable 'c' is assigned but its value is never used
// bool c = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c").WithLocation(6, 14));
}
[Fact, WorkItem(543426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543426")]
private void NestedInterfaceImplementationWithOuterGenericType()
{
CompileAndVerify(@"
namespace System.ServiceModel
{
class Pipeline<T>
{
interface IStage
{
void Process(T context);
}
class AsyncStage : IStage
{
void IStage.Process(T context) { }
}
}
}");
}
/// <summary>
/// Error types should be allowed as constant types.
/// </summary>
[Fact]
public void ErrorTypeConst()
{
var source =
@"class C
{
const C1 F1 = 0;
const C2 F2 = null;
static void M()
{
const C3 c3 = 0;
const C4 c4 = null;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (3,11): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C1").WithArguments("C1").WithLocation(3, 11),
// (4,11): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C2").WithArguments("C2").WithLocation(4, 11),
// (7,15): error CS0246: The type or namespace name 'C3' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C3").WithArguments("C3").WithLocation(7, 15),
// (8,15): error CS0246: The type or namespace name 'C4' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C4").WithArguments("C4").WithLocation(8, 15));
}
[WorkItem(543777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543777")]
[Fact]
public void DefaultParameterAtEndOfFile()
{
var source =
@"class C
{
static void M(object o = null,";
CreateCompilation(source).VerifyDiagnostics(
// (3,35): error CS1031: Type expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_TypeExpected, ""),
// Cascading:
// (3,35): error CS1001: Identifier expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
// (3,35): error CS1026: ) expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
// (3,35): error CS1002: ; expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_SemicolonExpected, ""),
// (3,35): error CS1513: } expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_RbraceExpected, ""),
// (3,35): error CS1737: Optional parameters must appear after all required parameters
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_DefaultValueBeforeRequiredValue, ""),
// (3,17): error CS0501: 'C.M(object, ?)' must declare a body because it is not
// marked abstract, extern, or partial static void M(object o = null,
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("C.M(object, ?)"));
}
[WorkItem(543814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543814")]
[Fact]
public void DuplicateNamedArgumentNullLiteral()
{
var source =
@"class C
{
static void M()
{
M("""",
arg: 0,
arg: null);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,9): error CS1501: No overload for method 'M' takes 3 arguments
// M("",
Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "3").WithLocation(5, 9));
}
[WorkItem(543820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543820")]
[Fact]
public void GenericAttributeClassWithMultipleParts()
{
var source =
@"class C<T> { }
class C<T> : System.Attribute { }";
CreateCompilation(source).VerifyDiagnostics(
// (2,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'C'
// class C<T> : System.Attribute { }
Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>"),
// (2,14): error CS0698: A generic type cannot derive from 'System.Attribute' because it is an attribute class
// class C<T> : System.Attribute { }
Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "System.Attribute").WithArguments("System.Attribute")
);
}
[WorkItem(543822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543822")]
[Fact]
public void InterfaceWithPartialMethodExplicitImplementation()
{
var source =
@"interface I
{
partial void I.M();
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(
// (3,20): error CS0754: A partial method may not explicitly implement an interface method
// partial void I.M();
Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "M").WithLocation(3, 20),
// (3,20): error CS0751: A partial method must be declared within a partial type
// partial void I.M();
Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 20),
// (3,20): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater.
// partial void I.M();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "M").WithArguments("default interface implementation", "8.0").WithLocation(3, 20),
// (3,18): error CS0540: 'I.M()': containing type does not implement interface 'I'
// partial void I.M();
Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I").WithArguments("I.M()", "I").WithLocation(3, 18)
);
}
[WorkItem(543827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543827")]
[Fact]
public void StructConstructor()
{
var source =
@"struct S
{
private readonly object x;
private readonly object y;
S(object x, object y)
{
try
{
this.x = x;
}
finally
{
this.y = y;
}
}
S(S o) : this(o.x, o.y) {}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(543827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543827")]
[Fact]
public void StructVersusTryFinally()
{
var source =
@"struct S
{
private object x;
private object y;
static void M()
{
S s1;
try { s1.x = null; } finally { s1.y = null; }
S s2 = s1;
s1.x = s1.y; s1.y = s1.x;
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(544513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544513")]
[Fact()]
public void AnonTypesPropSameNameDiffType()
{
var source =
@"public class Test
{
public static void Main()
{
var p1 = new { Price = 495.00 };
var p2 = new { Price = ""36.50"" };
p1 = p2;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (8,14): error CS0029: Cannot implicitly convert type 'AnonymousType#1' to 'AnonymousType#2'
// p1 = p2;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "p2").WithArguments("<anonymous type: string Price>", "<anonymous type: double Price>"));
}
[WorkItem(545869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545869")]
[Fact]
public void TestSealedOverriddenMembers()
{
CompileAndVerify(
@"using System;
internal abstract class Base
{
public virtual int Property
{
get { return 0; }
protected set { }
}
protected virtual event EventHandler Event
{
add { } remove { }
}
protected abstract void Method();
}
internal sealed class Derived : Base
{
public override int Property
{
get { return 1; }
protected set { }
}
protected override event EventHandler Event;
protected override void Method() { }
void UseEvent() { Event(null, null); }
}
internal sealed class Derived2 : Base
{
public override int Property
{
get; protected set;
}
protected override event EventHandler Event
{
add { } remove { }
}
protected override void Method() { }
}
class Program
{
static void Main() { }
}").VerifyDiagnostics();
}
[Fact, WorkItem(1068547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068547")]
public void Bug1068547_01()
{
var source =
@"
class Program
{
[System.Diagnostics.DebuggerDisplay(this)]
static void Main(string[] args)
{
}
}";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.ThisExpression)).Cast<ThisExpressionSyntax>().Single();
var symbolInfo = model.GetSymbolInfo(node);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason);
}
[Fact, WorkItem(1068547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068547")]
public void Bug1068547_02()
{
var source =
@"
[System.Diagnostics.DebuggerDisplay(this)]
";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.ThisExpression)).Cast<ThisExpressionSyntax>().Single();
var symbolInfo = model.GetSymbolInfo(node);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason);
}
[Fact]
public void RefReturningDelegateCreation()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
ref int M()
{
return ref field;
}
void Test()
{
new D(M)();
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefReturningDelegateCreationBad()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
int M()
{
return field;
}
void Test()
{
new D(M)();
}
}
";
CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics(
// (15,15): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// new D(M)();
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(15, 15)
);
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (15,15): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// new D(M)();
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(15, 15)
);
}
[Fact]
public void RefReturningDelegateArgument()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
ref int M()
{
return ref field;
}
void M(D d)
{
}
void Test()
{
M(M);
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefReturningDelegateArgumentBad()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
int M()
{
return field;
}
void M(D d)
{
}
void Test()
{
M(M);
}
}
";
CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics(
// (19,11): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// M(M);
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(19, 11)
);
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (19,11): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// M(M);
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(19, 11)
);
}
[Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")]
public void Bug1078958()
{
const string source = @"
class C
{
static void Foo<T>()
{
T();
}
static void T() { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (6,9): error CS0119: 'T' is a type, which is not valid in the given context
// T();
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 9));
}
[Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")]
public void Bug1078958_2()
{
const string source = @"
class C
{
static void Foo<T>()
{
T<T>();
}
static void T() { }
static void T<U>() { }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961()
{
const string source = @"
class C
{
const int T = 42;
static void Foo<T>(int x = T)
{
System.Console.Write(x);
}
static void Main()
{
Foo<object>();
}
}";
CompileAndVerify(source, expectedOutput: "42");
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_2()
{
const string source = @"
class A : System.Attribute
{
public A(int i) { }
}
class C
{
const int T = 42;
static void Foo<T>([A(T)] int x)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var t = (FieldSymbol)c.GetMembers("T").Single();
var foo = (MethodSymbol)c.GetMembers("Foo").Single();
var x = foo.Parameters[0];
var a = x.GetAttributes()[0];
var i = a.ConstructorArguments.Single();
Assert.Equal((int)i.Value, (int)t.ConstantValue);
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_3()
{
const string source = @"
class A : System.Attribute
{
public A(int i) { }
}
class C
{
const int T = 42;
[A(T)]
static void Foo<T>(int x)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var t = (FieldSymbol)c.GetMembers("T").Single();
var foo = (MethodSymbol)c.GetMembers("Foo").Single();
var a = foo.GetAttributes()[0];
var i = a.ConstructorArguments.Single();
Assert.Equal((int)i.Value, (int)t.ConstantValue);
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_4()
{
const string source = @"
class A : System.Attribute
{
public A(int i) { }
}
class C
{
const int T = 42;
static void Foo<[A(T)] T>(int x)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var t = (FieldSymbol)c.GetMembers("T").Single();
var foo = (MethodSymbol)c.GetMembers("Foo").Single();
var tt = foo.TypeParameters[0];
var a = tt.GetAttributes()[0];
var i = a.ConstructorArguments.Single();
Assert.Equal((int)i.Value, (int)t.ConstantValue);
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_5()
{
const string source = @"
class C
{
class T { }
static void Foo<T>(T x = default(T))
{
System.Console.Write((object)x == null);
}
static void Main()
{
Foo<object>();
}
}";
CompileAndVerify(source, expectedOutput: "True");
}
[Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")]
public void CastToDelegate_01()
{
var sourceText = @"namespace NS
{
public static class A
{
public delegate void Action();
public static void M()
{
RunAction(A.B<string>.M0);
RunAction((Action)A.B<string>.M1);
}
private static void RunAction(Action action) { }
private class B<T>
{
public static void M0() { }
public static void M1() { }
}
}
}";
var compilation = CreateCompilation(sourceText, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var identifierNameM0 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M0"));
Assert.Equal("A.B<string>.M0", identifierNameM0.Parent.ToString());
var m0Symbol = model.GetSymbolInfo(identifierNameM0);
Assert.Equal("void NS.A.B<System.String>.M0()", m0Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m0Symbol.CandidateReason);
var identifierNameM1 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M1"));
Assert.Equal("A.B<string>.M1", identifierNameM1.Parent.ToString());
var m1Symbol = model.GetSymbolInfo(identifierNameM1);
Assert.Equal("void NS.A.B<System.String>.M1()", m1Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m1Symbol.CandidateReason);
}
[Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")]
public void CastToDelegate_02()
{
var sourceText = @"
class A
{
public delegate void MyDelegate<T>(T a);
public void Test()
{
UseMyDelegate((MyDelegate<int>)MyMethod);
UseMyDelegate((MyDelegate<long>)MyMethod);
UseMyDelegate((MyDelegate<float>)MyMethod);
UseMyDelegate((MyDelegate<double>)MyMethod);
}
private void UseMyDelegate<T>(MyDelegate<T> f) { }
private static void MyMethod(int a) { }
private static void MyMethod(long a) { }
private static void MyMethod(float a) { }
private static void MyMethod(double a) { }
}";
var compilation = CreateCompilation(sourceText, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var identifiers = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(x => x.Identifier.ValueText.Equals("MyMethod")).ToArray();
Assert.Equal(4, identifiers.Length);
Assert.Equal("(MyDelegate<int>)MyMethod", identifiers[0].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Int32 a)", model.GetSymbolInfo(identifiers[0]).Symbol.ToTestDisplayString());
Assert.Equal("(MyDelegate<long>)MyMethod", identifiers[1].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Int64 a)", model.GetSymbolInfo(identifiers[1]).Symbol.ToTestDisplayString());
Assert.Equal("(MyDelegate<float>)MyMethod", identifiers[2].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Single a)", model.GetSymbolInfo(identifiers[2]).Symbol.ToTestDisplayString());
Assert.Equal("(MyDelegate<double>)MyMethod", identifiers[3].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Double a)", model.GetSymbolInfo(identifiers[3]).Symbol.ToTestDisplayString());
}
[Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")]
public void CastToDelegate_03()
{
var sourceText = @"namespace NS
{
public static class A
{
public delegate void Action();
public static void M()
{
var b = new A.B<string>();
RunAction(b.M0);
RunAction((Action)b.M1);
}
private static void RunAction(Action action) { }
public class B<T>
{
}
public static void M0<T>(this B<T> x) { }
public static void M1<T>(this B<T> x) { }
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceText, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var identifierNameM0 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M0"));
Assert.Equal("b.M0", identifierNameM0.Parent.ToString());
var m0Symbol = model.GetSymbolInfo(identifierNameM0);
Assert.Equal("void NS.A.B<System.String>.M0<System.String>()", m0Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m0Symbol.CandidateReason);
var identifierNameM1 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M1"));
Assert.Equal("b.M1", identifierNameM1.Parent.ToString());
var m1Symbol = model.GetSymbolInfo(identifierNameM1);
Assert.Equal("void NS.A.B<System.String>.M1<System.String>()", m1Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m1Symbol.CandidateReason);
}
[Fact, WorkItem(5170, "https://github.com/dotnet/roslyn/issues/5170")]
public void TypeOfBinderParameter()
{
var sourceText = @"
using System.Linq;
using System.Text;
public static class LazyToStringExtension
{
public static string LazyToString<T>(this T obj) where T : class
{
StringBuilder sb = new StringBuilder();
typeof(T)
.GetProperties(System.Reflection.BindingFlags.Public)
.Select(x => x.GetValue(obj))
}
}";
var compilation = CreateCompilationWithMscorlib40(sourceText, new[] { TestMetadata.Net40.SystemCore }, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics(
// (12,42): error CS1002: ; expected
// .Select(x => x.GetValue(obj))
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(12, 42),
// (12,28): error CS1501: No overload for method 'GetValue' takes 1 arguments
// .Select(x => x.GetValue(obj))
Diagnostic(ErrorCode.ERR_BadArgCount, "GetValue").WithArguments("GetValue", "1").WithLocation(12, 28),
// (7,26): error CS0161: 'LazyToStringExtension.LazyToString<T>(T)': not all code paths return a value
// public static string LazyToString<T>(this T obj) where T : class
Diagnostic(ErrorCode.ERR_ReturnExpected, "LazyToString").WithArguments("LazyToStringExtension.LazyToString<T>(T)").WithLocation(7, 26));
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single();
var param = node.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single();
Assert.Equal("System.Reflection.PropertyInfo x", model.GetDeclaredSymbol(param).ToTestDisplayString());
}
[Fact, WorkItem(7520, "https://github.com/dotnet/roslyn/issues/7520")]
public void DelegateCreationWithIncompleteLambda()
{
var source =
@"
using System;
class C
{
public void F()
{
var x = new Action<int>(i => i.
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,40): error CS1001: Identifier expected
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(7, 40),
// (7,40): error CS1026: ) expected
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 40),
// (7,40): error CS1002: ; expected
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 40),
// (7,38): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_IllegalStatement, @"i.
").WithLocation(7, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single();
var param = lambda.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single();
var symbol1 = model.GetDeclaredSymbol(param);
Assert.Equal("System.Int32 i", symbol1.ToTestDisplayString());
var id = lambda.DescendantNodes().First(n => n.IsKind(SyntaxKind.IdentifierName));
var symbol2 = model.GetSymbolInfo(id).Symbol;
Assert.Equal("System.Int32 i", symbol2.ToTestDisplayString());
Assert.Same(symbol1, symbol2);
}
[Fact, WorkItem(7520, "https://github.com/dotnet/roslyn/issues/7520")]
public void ImplicitDelegateCreationWithIncompleteLambda()
{
var source =
@"
using System;
class C
{
public void F()
{
Action<int> x = i => i.
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,32): error CS1001: Identifier expected
// Action<int> x = i => i.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(7, 32),
// (7,32): error CS1002: ; expected
// Action<int> x = i => i.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 32),
// (7,30): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// Action<int> x = i => i.
Diagnostic(ErrorCode.ERR_IllegalStatement, @"i.
").WithLocation(7, 30)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single();
var param = lambda.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single();
var symbol1 = model.GetDeclaredSymbol(param);
Assert.Equal("System.Int32 i", symbol1.ToTestDisplayString());
var id = lambda.DescendantNodes().First(n => n.IsKind(SyntaxKind.IdentifierName));
var symbol2 = model.GetSymbolInfo(id).Symbol;
Assert.Equal("System.Int32 i", symbol2.ToTestDisplayString());
Assert.Same(symbol1, symbol2);
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_01()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
}
static class IApplicationBuilderExtensions
{
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware)
{
return app;
}
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore });
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(38, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(1, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_02()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
IApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware);
}
static class IApplicationBuilderExtensions
{
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware)
{
return app;
}
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore });
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(38, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(1, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_03()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
IApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware);
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(31, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(2, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols[1].ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_04()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
}
static class IApplicationBuilderExtensions
{
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware)
{
return app;
}
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware)
{
return app;
}
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore });
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(42, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(2, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols[1].ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(7101, "https://github.com/dotnet/roslyn/issues/7101")]
public void UsingStatic_01()
{
var source =
@"
using System;
using static ClassWithNonStaticMethod;
using static Extension1;
class Program
{
static void Main(string[] args)
{
var instance = new Program();
instance.NonStaticMethod();
}
private void NonStaticMethod()
{
MathMin(0, 1);
MathMax(0, 1);
MathMax2(0, 1);
int x;
x = F1;
x = F2;
x.MathMax2(3);
}
}
class ClassWithNonStaticMethod
{
public static int MathMax(int a, int b)
{
return Math.Max(a, b);
}
public int MathMin(int a, int b)
{
return Math.Min(a, b);
}
public int F2 = 0;
}
static class Extension1
{
public static int MathMax2(this int a, int b)
{
return Math.Max(a, b);
}
public static int F1 = 0;
}
static class Extension2
{
public static int MathMax3(this int a, int b)
{
return Math.Max(a, b);
}
}
";
var comp = CreateCompilationWithMscorlib45(source);
comp.VerifyDiagnostics(
// (16,9): error CS0103: The name 'MathMin' does not exist in the current context
// MathMin(0, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "MathMin").WithArguments("MathMin").WithLocation(16, 9),
// (18,9): error CS0103: The name 'MathMax2' does not exist in the current context
// MathMax2(0, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "MathMax2").WithArguments("MathMax2").WithLocation(18, 9),
// (22,13): error CS0103: The name 'F2' does not exist in the current context
// x = F2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "F2").WithArguments("F2").WithLocation(22, 13)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "MathMin").Single().Parent;
Assert.Equal("MathMin(0, 1)", node1.ToString());
var names = model.LookupNames(node1.SpanStart);
Assert.False(names.Contains("MathMin"));
Assert.True(names.Contains("MathMax"));
Assert.True(names.Contains("F1"));
Assert.False(names.Contains("F2"));
Assert.False(names.Contains("MathMax2"));
Assert.False(names.Contains("MathMax3"));
Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMin").IsEmpty);
Assert.Equal(1, model.LookupSymbols(node1.SpanStart, name: "MathMax").Length);
Assert.Equal(1, model.LookupSymbols(node1.SpanStart, name: "F1").Length);
Assert.True(model.LookupSymbols(node1.SpanStart, name: "F2").IsEmpty);
Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMax2").IsEmpty);
Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMax3").IsEmpty);
var symbols = model.LookupSymbols(node1.SpanStart);
Assert.False(symbols.Where(s => s.Name == "MathMin").Any());
Assert.True(symbols.Where(s => s.Name == "MathMax").Any());
Assert.True(symbols.Where(s => s.Name == "F1").Any());
Assert.False(symbols.Where(s => s.Name == "F2").Any());
Assert.False(symbols.Where(s => s.Name == "MathMax2").Any());
Assert.False(symbols.Where(s => s.Name == "MathMax3").Any());
}
[Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")]
public void UsingStaticGenericConstraint()
{
var code = @"
using static Test<System.String>;
public static class Test<T> where T : struct { }
";
CreateCompilationWithMscorlib45(code).VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using static Test<System.String>;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Test<System.String>;").WithLocation(2, 1),
// (2,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>'
// using static Test<System.String>;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test<System.String>").WithArguments("Test<T>", "T", "string").WithLocation(2, 14));
}
[Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")]
public void UsingStaticGenericConstraintNestedType()
{
var code = @"
using static A<A<int>[]>.B;
class A<T> where T : class
{
internal static class B { }
}
";
CreateCompilationWithMscorlib45(code).VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using static A<A<int>[]>.B;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<A<int>[]>.B;").WithLocation(2, 1),
// (2,14): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'A<T>'
// using static A<A<int>[]>.B;
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "A<A<int>[]>.B").WithArguments("A<T>", "T", "int").WithLocation(2, 14));
}
[Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")]
public void UsingStaticMultipleGenericConstraints()
{
var code = @"
using static A<int, string>;
static class A<T, U> where T : class where U : struct { }
";
CreateCompilationWithMscorlib45(code).VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using static A<int, string>;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<int, string>;").WithLocation(2, 1),
// (2,14): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'A<T, U>'
// using static A<int, string>;
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "A<int, string>").WithArguments("A<T, U>", "T", "int").WithLocation(2, 14),
// (2,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<T, U>'
// using static A<int, string>;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "A<int, string>").WithArguments("A<T, U>", "U", "string").WithLocation(2, 14));
}
[Fact, WorkItem(8234, "https://github.com/dotnet/roslyn/issues/8234")]
public void EventAccessInTypeNameContext()
{
var source =
@"
class Program
{
static void Main() {}
event System.EventHandler E1;
void Test(Program x)
{
System.Console.WriteLine();
x.E1.E
System.Console.WriteLine();
}
void Dummy()
{
E1 = null;
var x = E1;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,15): error CS1001: Identifier expected
// x.E1.E
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(11, 15),
// (11,15): error CS1002: ; expected
// x.E1.E
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 15),
// (11,9): error CS0118: 'x' is a variable but is used like a type
// x.E1.E
Diagnostic(ErrorCode.ERR_BadSKknown, "x").WithArguments("x", "variable", "type").WithLocation(11, 9)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "E").Single().Parent;
Assert.Equal("x.E1.E", node1.ToString());
Assert.Equal(SyntaxKind.QualifiedName, node1.Kind());
var node2 = ((QualifiedNameSyntax)node1).Left;
Assert.Equal("x.E1", node2.ToString());
var symbolInfo2 = model.GetSymbolInfo(node2);
Assert.Null(symbolInfo2.Symbol);
Assert.Equal("event System.EventHandler Program.E1", symbolInfo2.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.NotATypeOrNamespace, symbolInfo2.CandidateReason);
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.True(symbolInfo1.CandidateSymbols.IsEmpty);
}
[Fact, WorkItem(13617, "https://github.com/dotnet/roslyn/issues/13617")]
public void MissingTypeArgumentInGenericExtensionMethod()
{
var source =
@"
public static class FooExtensions
{
public static object ExtensionMethod0(this object obj) => default(object);
public static T ExtensionMethod1<T>(this object obj) => default(T);
public static T1 ExtensionMethod2<T1, T2>(this object obj) => default(T1);
}
public class Class1
{
public void Test()
{
var omittedArg0 = ""string literal"".ExtensionMethod0<>();
var omittedArg1 = ""string literal"".ExtensionMethod1<>();
var omittedArg2 = ""string literal"".ExtensionMethod2<>();
var omittedArgFunc0 = ""string literal"".ExtensionMethod0<>;
var omittedArgFunc1 = ""string literal"".ExtensionMethod1<>;
var omittedArgFunc2 = ""string literal"".ExtensionMethod2<>;
var moreArgs0 = ""string literal"".ExtensionMethod0<int>();
var moreArgs1 = ""string literal"".ExtensionMethod1<int, bool>();
var moreArgs2 = ""string literal"".ExtensionMethod2<int, bool, string>();
var lessArgs1 = ""string literal"".ExtensionMethod1();
var lessArgs2 = ""string literal"".ExtensionMethod2<int>();
var nonExistingMethod0 = ""string literal"".ExtensionMethodNotFound0();
var nonExistingMethod1 = ""string literal"".ExtensionMethodNotFound1<int>();
var nonExistingMethod2 = ""string literal"".ExtensionMethodNotFound2<int, string>();
System.Func<object> delegateConversion0 = ""string literal"".ExtensionMethod0<>;
System.Func<object> delegateConversion1 = ""string literal"".ExtensionMethod1<>;
System.Func<object> delegateConversion2 = ""string literal"".ExtensionMethod2<>;
var exactArgs0 = ""string literal"".ExtensionMethod0();
var exactArgs1 = ""string literal"".ExtensionMethod1<int>();
var exactArgs2 = ""string literal"".ExtensionMethod2<int, bool>();
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (13,27): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArg0 = "string literal".ExtensionMethod0<>();
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(13, 27),
// (13,44): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArg0 = "string literal".ExtensionMethod0<>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(13, 44),
// (14,27): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArg1 = "string literal".ExtensionMethod1<>();
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(14, 27),
// (15,27): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArg2 = "string literal".ExtensionMethod2<>();
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(15, 27),
// (15,44): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArg2 = "string literal".ExtensionMethod2<>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(15, 44),
// (17,31): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArgFunc0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(17, 31),
// (17,48): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArgFunc0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(17, 48),
// (18,31): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArgFunc1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(18, 31),
// (19,31): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArgFunc2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(19, 31),
// (19,48): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArgFunc2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(19, 48),
// (21,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var moreArgs0 = "string literal".ExtensionMethod0<int>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<int>").WithArguments("string", "ExtensionMethod0").WithLocation(21, 42),
// (22,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod1' and no accessible extension method 'ExtensionMethod1' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var moreArgs1 = "string literal".ExtensionMethod1<int, bool>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod1<int, bool>").WithArguments("string", "ExtensionMethod1").WithLocation(22, 42),
// (23,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var moreArgs2 = "string literal".ExtensionMethod2<int, bool, string>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<int, bool, string>").WithArguments("string", "ExtensionMethod2").WithLocation(23, 42),
// (25,42): error CS0411: The type arguments for method 'FooExtensions.ExtensionMethod1<T>(object)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// var lessArgs1 = "string literal".ExtensionMethod1();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "ExtensionMethod1").WithArguments("FooExtensions.ExtensionMethod1<T>(object)").WithLocation(25, 42),
// (26,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var lessArgs2 = "string literal".ExtensionMethod2<int>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<int>").WithArguments("string", "ExtensionMethod2").WithLocation(26, 42),
// (28,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound0' and no accessible extension method 'ExtensionMethodNotFound0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var nonExistingMethod0 = "string literal".ExtensionMethodNotFound0();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound0").WithArguments("string", "ExtensionMethodNotFound0").WithLocation(28, 51),
// (29,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound1' and no accessible extension method 'ExtensionMethodNotFound1' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var nonExistingMethod1 = "string literal".ExtensionMethodNotFound1<int>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound1<int>").WithArguments("string", "ExtensionMethodNotFound1").WithLocation(29, 51),
// (30,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound2' and no accessible extension method 'ExtensionMethodNotFound2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var nonExistingMethod2 = "string literal".ExtensionMethodNotFound2<int, string>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound2<int, string>").WithArguments("string", "ExtensionMethodNotFound2").WithLocation(30, 51),
// (32,51): error CS8389: Omitting the type argument is not allowed in the current context
// System.Func<object> delegateConversion0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(32, 51),
// (32,68): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// System.Func<object> delegateConversion0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(32, 68),
// (33,51): error CS8389: Omitting the type argument is not allowed in the current context
// System.Func<object> delegateConversion1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(33, 51),
// (33,51): error CS0407: '? FooExtensions.ExtensionMethod1<?>(object)' has the wrong return type
// System.Func<object> delegateConversion1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_BadRetType, @"""string literal"".ExtensionMethod1<>").WithArguments("FooExtensions.ExtensionMethod1<?>(object)", "?").WithLocation(33, 51),
// (34,51): error CS8389: Omitting the type argument is not allowed in the current context
// System.Func<object> delegateConversion2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(34, 51),
// (34,68): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// System.Func<object> delegateConversion2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(34, 68));
}
[WorkItem(22757, "https://github.com/dotnet/roslyn/issues/22757")]
[Fact]
public void MethodGroupConversionNoReceiver()
{
var source =
@"using System;
using System.Collections.Generic;
class A
{
class B
{
void F()
{
IEnumerable<string> c = null;
c.S(G);
}
}
object G(string s)
{
return null;
}
}
static class E
{
internal static IEnumerable<U> S<T, U>(this IEnumerable<T> c, Func<T, U> f)
{
throw new NotImplementedException();
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (10,17): error CS0120: An object reference is required for the non-static field, method, or property 'A.G(string)'
// c.S(G);
Diagnostic(ErrorCode.ERR_ObjectRequired, "G").WithArguments("A.G(string)").WithLocation(10, 17));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "G").First();
var info = model.GetSymbolInfo(node);
Assert.Equal("System.Object A.G(System.String s)", info.Symbol.ToTestDisplayString());
}
[Fact]
public void BindingLambdaArguments_DuplicateNamedArguments()
{
var compilation = CreateCompilation(@"
using System;
class X
{
void M<T>(T arg1, Func<T, T> arg2)
{
}
void N()
{
M(arg1: 5, arg2: x => x, arg2: y => y);
}
}").VerifyDiagnostics(
// (10,34): error CS1740: Named argument 'arg2' cannot be specified multiple times
// M(arg1: 5, arg2: x => 0, arg2: y => 0);
Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "arg2").WithArguments("arg2").WithLocation(10, 34));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var lambda = tree.GetRoot().DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(s => s.Parameter.Identifier.Text == "x");
var typeInfo = model.GetTypeInfo(lambda.Body);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class BindingTests : CompilingTestBase
{
[Fact, WorkItem(539872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539872")]
public void NoWRN_UnreachableCode()
{
var text = @"
public class Cls
{
public static int Main()
{
goto Label2;
Label1:
return (1);
Label2:
goto Label1;
}
}";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void GenericMethodName()
{
var source =
@"class A
{
class B
{
static void M(System.Action a)
{
M(M1);
M(M2<object>);
M(M3<int>);
}
static void M1() { }
static void M2<T>() { }
}
static void M3<T>() { }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void GenericTypeName()
{
var source =
@"class A
{
class B
{
static void M(System.Type t)
{
M(typeof(C<int>));
M(typeof(S<string, string>));
M(typeof(C<int, int>));
}
class C<T> { }
}
struct S<T, U> { }
}
class C<T, U> { }
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void GenericTypeParameterName()
{
var source =
@"class A<T>
{
class B<U>
{
static void M<V>()
{
N(typeof(V));
N(typeof(U));
N(typeof(T));
}
static void N(System.Type t) { }
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void WrongMethodArity()
{
var source =
@"class C
{
static void M1<T>() { }
static void M2() { }
void M3<T>() { }
void M4() { }
void M()
{
M1<object, object>();
C.M1<object, object>();
M2<int>();
C.M2<int>();
M3<object, object>();
this.M3<object, object>();
M4<int>();
this.M4<int>();
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,9): error CS0305: Using the generic method 'C.M1<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M1<object, object>").WithArguments("C.M1<T>()", "method", "1").WithLocation(9, 9),
// (10,11): error CS0305: Using the generic method 'C.M1<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M1<object, object>").WithArguments("C.M1<T>()", "method", "1").WithLocation(10, 11),
// (11,9): error CS0308: The non-generic method 'C.M2()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M2<int>").WithArguments("C.M2()", "method").WithLocation(11, 9),
// (12,11): error CS0308: The non-generic method 'C.M2()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M2<int>").WithArguments("C.M2()", "method").WithLocation(12, 11),
// (13,9): error CS0305: Using the generic method 'C.M3<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M3<object, object>").WithArguments("C.M3<T>()", "method", "1").WithLocation(13, 9),
// (14,14): error CS0305: Using the generic method 'C.M3<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M3<object, object>").WithArguments("C.M3<T>()", "method", "1").WithLocation(14, 14),
// (15,9): error CS0308: The non-generic method 'C.M4()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M4<int>").WithArguments("C.M4()", "method").WithLocation(15, 9),
// (16,14): error CS0308: The non-generic method 'C.M4()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M4<int>").WithArguments("C.M4()", "method").WithLocation(16, 14));
}
[Fact]
public void AmbiguousInaccessibleMethod()
{
var source =
@"class A
{
protected void M1() { }
protected void M1(object o) { }
protected void M2(string s) { }
protected void M2(object o) { }
}
class B
{
static void M(A a)
{
a.M1();
a.M2();
M(a.M1);
M(a.M2);
}
static void M(System.Action<object> a) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (12,11): error CS0122: 'A.M1()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("A.M1()").WithLocation(12, 11),
// (13,11): error CS0122: 'A.M2(string)' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("A.M2(string)").WithLocation(13, 11),
// (14,13): error CS0122: 'A.M1()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("A.M1()").WithLocation(14, 13),
// (15,13): error CS0122: 'A.M2(string)' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("A.M2(string)").WithLocation(15, 13));
}
/// <summary>
/// Should report inaccessible method, even when using
/// method as a delegate in an invalid context.
/// </summary>
[Fact]
public void InaccessibleMethodInvalidDelegateUse()
{
var source =
@"class A
{
protected object F() { return null; }
}
class B
{
static void M(A a)
{
if (a.F != null)
{
M(a.F);
a.F.ToString();
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,15): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(9, 15),
// (11,17): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(11, 17),
// (12,15): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(12, 15));
}
/// <summary>
/// Methods should be resolved correctly even
/// in cases where a method group is not allowed.
/// </summary>
[Fact]
public void InvalidUseOfMethodGroup()
{
var source =
@"class A
{
internal object E() { return null; }
private object F() { return null; }
}
class B
{
static void M(A a)
{
object o;
a.E += a.E;
if (a.E != null)
{
M(a.E);
a.E.ToString();
o = !a.E;
o = a.E ?? a.F;
}
a.F += a.F;
if (a.F != null)
{
M(a.F);
a.F.ToString();
o = !a.F;
o = (o != null) ? a.E : a.F;
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (11,9): error CS1656: Cannot assign to 'E' because it is a 'method group'
// a.E += a.E;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "a.E").WithArguments("E", "method group").WithLocation(11, 9),
// (14,15): error CS1503: Argument 1: cannot convert from 'method group' to 'A'
// M(a.E);
Diagnostic(ErrorCode.ERR_BadArgType, "a.E").WithArguments("1", "method group", "A").WithLocation(14, 15),
// (15,15): error CS0119: 'A.E()' is a method, which is not valid in the given context
// a.E.ToString();
Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("A.E()", "method").WithLocation(15, 15),
// (16,17): error CS0023: Operator '!' cannot be applied to operand of type 'method group'
// o = !a.E;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "!a.E").WithArguments("!", "method group").WithLocation(16, 17),
// (17,26): error CS0122: 'A.F()' is inaccessible due to its protection level
// o = a.E ?? a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(17, 26),
// (19,11): error CS0122: 'A.F()' is inaccessible due to its protection level
// a.F += a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(19, 11),
// (19,18): error CS0122: 'A.F()' is inaccessible due to its protection level
// a.F += a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(19, 18),
// (20,15): error CS0122: 'A.F()' is inaccessible due to its protection level
// if (a.F != null)
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(20, 15),
// (22,17): error CS0122: 'A.F()' is inaccessible due to its protection level
// M(a.F);
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(22, 17),
// (23,15): error CS0122: 'A.F()' is inaccessible due to its protection level
// a.F.ToString();
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(23, 15),
// (24,20): error CS0122: 'A.F()' is inaccessible due to its protection level
// o = !a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(24, 20),
// (25,39): error CS0122: 'A.F()' is inaccessible due to its protection level
// o = (o != null) ? a.E : a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(25, 39));
}
[WorkItem(528425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528425")]
[Fact(Skip = "528425")]
public void InaccessibleAndAccessible()
{
var source =
@"using System;
class A
{
void F() { }
internal void F(object o) { }
static void G() { }
internal static void G(object o) { }
void H(object o) { }
}
class B : A
{
static void M(A a)
{
a.F(null);
a.F();
A.G();
M1(a.F);
M2(a.F);
Action<object> a1 = a.F;
Action a2 = a.F;
}
void M()
{
G();
}
static void M1(Action<object> a) { }
static void M2(Action a) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (15,11): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(15, 11),
// (16,11): error CS0122: 'A.G()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(16, 11),
// (18,12): error CS1503: Argument 1: cannot convert from 'method group' to 'System.Action'
Diagnostic(ErrorCode.ERR_BadArgType, "a.F").WithArguments("1", "method group", "System.Action").WithLocation(18, 12),
// (20,23): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(20, 23),
// (24,9): error CS0122: 'A.G()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(24, 9));
}
[Fact]
public void InaccessibleAndAccessibleAndAmbiguous()
{
var source =
@"class A
{
void F(string x) { }
void F(string x, string y) { }
internal void F(object x, string y) { }
internal void F(string x, object y) { }
void G(object x, string y) { }
internal void G(string x, object y) { }
static void M(A a, string s)
{
a.F(s, s); // no error
}
}
class B
{
static void M(A a, string s, object o)
{
a.F(s, s); // accessible ambiguous
a.G(s, s); // accessible and inaccessible ambiguous, no error
a.G(o, o); // accessible and inaccessible invalid
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'A.F(object, string)' and 'A.F(string, object)'
Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("A.F(object, string)", "A.F(string, object)").WithLocation(18, 11),
// (20,13): error CS1503: Argument 1: cannot convert from 'object' to 'string'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("1", "object", "string").WithLocation(20, 13));
}
[Fact]
public void InaccessibleAndAccessibleValid()
{
var source =
@"class A
{
void F(int i) { }
internal void F(long l) { }
static void M(A a)
{
a.F(1); // no error
}
}
class B
{
static void M(A a)
{
a.F(1); // no error
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void ParenthesizedDelegate()
{
var source =
@"class C
{
System.Action<object> F = null;
void M()
{
((this.F))(null);
(new C().F)(null, null);
}
}";
CreateCompilation(source).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(new C().F)").WithArguments("System.Action<object>", "2").WithLocation(7, 9));
}
/// <summary>
/// Report errors for invocation expressions for non-invocable expressions,
/// and bind arguments even though invocation expression was invalid.
/// </summary>
[Fact]
public void NonMethodsWithArgs()
{
var source =
@"namespace N
{
class C<T>
{
object F;
object P { get; set; }
void M()
{
N(a);
C<string>(b);
N.C<int>(c);
N.D(d);
T(e);
(typeof(C<int>))(f);
P(g) = F(h);
this.F(i) = (this).P(j);
null.M(k);
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,15): error CS0103: The name 'a' does not exist in the current context
// N(a);
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a"),
// (9,13): error CS0118: 'N' is a namespace but is used like a variable
// N(a);
Diagnostic(ErrorCode.ERR_BadSKknown, "N").WithArguments("N", "namespace", "variable"),
// (10,23): error CS0103: The name 'b' does not exist in the current context
// C<string>(b);
Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b"),
// (10,13): error CS1955: Non-invocable member 'N.C<T>' cannot be used like a method.
// C<string>(b);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "C<string>").WithArguments("N.C<T>"),
// (11,22): error CS0103: The name 'c' does not exist in the current context
// N.C<int>(c);
Diagnostic(ErrorCode.ERR_NameNotInContext, "c").WithArguments("c"),
// (11,15): error CS1955: Non-invocable member 'N.C<T>' cannot be used like a method.
// N.C<int>(c);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "C<int>").WithArguments("N.C<T>"),
// (12,17): error CS0103: The name 'd' does not exist in the current context
// N.D(d);
Diagnostic(ErrorCode.ERR_NameNotInContext, "d").WithArguments("d"),
// (12,13): error CS0234: The type or namespace name 'D' does not exist in the namespace 'N' (are you missing an assembly reference?)
// N.D(d);
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "N.D").WithArguments("D", "N"),
// (13,15): error CS0103: The name 'e' does not exist in the current context
// T(e);
Diagnostic(ErrorCode.ERR_NameNotInContext, "e").WithArguments("e"),
// (13,13): error CS0103: The name 'T' does not exist in the current context
// T(e);
Diagnostic(ErrorCode.ERR_NameNotInContext, "T").WithArguments("T"),
// (14,30): error CS0103: The name 'f' does not exist in the current context
// (typeof(C<int>))(f);
Diagnostic(ErrorCode.ERR_NameNotInContext, "f").WithArguments("f"),
// (14,13): error CS0149: Method name expected
// (typeof(C<int>))(f);
Diagnostic(ErrorCode.ERR_MethodNameExpected, "(typeof(C<int>))"),
// (15,15): error CS0103: The name 'g' does not exist in the current context
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NameNotInContext, "g").WithArguments("g"),
// (15,13): error CS1955: Non-invocable member 'N.C<T>.P' cannot be used like a method.
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("N.C<T>.P"),
// (15,22): error CS0103: The name 'h' does not exist in the current context
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NameNotInContext, "h").WithArguments("h"),
// (15,20): error CS1955: Non-invocable member 'N.C<T>.F' cannot be used like a method.
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("N.C<T>.F"),
// (16,20): error CS0103: The name 'i' does not exist in the current context
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i"),
// (16,18): error CS1955: Non-invocable member 'N.C<T>.F' cannot be used like a method.
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("N.C<T>.F"),
// (16,34): error CS0103: The name 'j' does not exist in the current context
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NameNotInContext, "j").WithArguments("j"),
// (16,32): error CS1955: Non-invocable member 'N.C<T>.P' cannot be used like a method.
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("N.C<T>.P"),
// (17,20): error CS0103: The name 'k' does not exist in the current context
// null.M(k);
Diagnostic(ErrorCode.ERR_NameNotInContext, "k").WithArguments("k"),
// (17,13): error CS0023: Operator '.' cannot be applied to operand of type '<null>'
// null.M(k);
Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.M").WithArguments(".", "<null>"),
// (5,16): warning CS0649: Field 'N.C<T>.F' is never assigned to, and will always have its default value null
// object F;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("N.C<T>.F", "null")
);
}
[Fact]
public void SimpleDelegates()
{
var source =
@"static class S
{
public static void F(System.Action a) { }
}
class C
{
void M()
{
S.F(this.M);
System.Action a = this.M;
S.F(a);
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void DelegatesFromOverloads()
{
var source =
@"using System;
class C
{
static void A(Action<object> a) { }
static void M(C c)
{
A(C.F);
A(c.G);
Action<object> a;
a = C.F;
a = c.G;
}
static void F() { }
static void F(object o) { }
void G(object o) { }
void G(object x, object y) { }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void NonViableDelegates()
{
var source =
@"using System;
class A
{
static Action F = null;
Action G = null;
}
class B
{
static void M(A a)
{
A.F(x);
a.G(y);
}
}";
CreateCompilation(source).VerifyDiagnostics( // (11,13): error CS0103: The name 'x' does not exist in the current context
// A.F(x);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"),
// (11,11): error CS0122: 'A.F' is inaccessible due to its protection level
// A.F(x);
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F"),
// (12,13): error CS0103: The name 'y' does not exist in the current context
// a.G(y);
Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y"),
// (12,11): error CS0122: 'A.G' is inaccessible due to its protection level
// a.G(y);
Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"),
// (4,19): warning CS0414: The field 'A.F' is assigned but its value is never used
// static Action F = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A.F"),
// (5,12): warning CS0414: The field 'A.G' is assigned but its value is never used
// Action G = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "G").WithArguments("A.G")
);
}
/// <summary>
/// Choose one method if overloaded methods are
/// equally invalid.
/// </summary>
[Fact]
public void ChooseOneMethodIfEquallyInvalid()
{
var source =
@"internal static class S
{
public static void M(double x, A y) { }
public static void M(double x, B y) { }
}
class A { }
class B { }
class C
{
static void M()
{
S.M(1.0, null); // ambiguous
S.M(1.0, 2.0); // equally invalid
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'S.M(double, A)' and 'S.M(double, B)'
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("S.M(double, A)", "S.M(double, B)").WithLocation(12, 11),
// (13,18): error CS1503: Argument 2: cannot convert from 'double' to 'A'
Diagnostic(ErrorCode.ERR_BadArgType, "2.0").WithArguments("2", "double", "A").WithLocation(13, 18));
}
[Fact]
public void ChooseExpandedFormIfBadArgCountAndBadArgument()
{
var source =
@"class C
{
static void M(object o)
{
F();
F(o);
F(1, o);
F(1, 2, o);
}
static void F(int i, params int[] args) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'C.F(int, params int[])'
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "F").WithArguments("i", "C.F(int, params int[])").WithLocation(5, 9),
// (6,11): error CS1503: Argument 1: cannot convert from 'object' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("1", "object", "int").WithLocation(6, 11),
// (7,14): error CS1503: Argument 2: cannot convert from 'object' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("2", "object", "int").WithLocation(7, 14),
// (8,17): error CS1503: Argument 3: cannot convert from 'object' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("3", "object", "int").WithLocation(8, 17));
}
[Fact]
public void AmbiguousAndBadArgument()
{
var source =
@"class C
{
static void F(int x, double y) { }
static void F(double x, int y) { }
static void M()
{
F(1, 2);
F(1.0, 2.0);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.F(int, double)' and 'C.F(double, int)'
Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("C.F(int, double)", "C.F(double, int)").WithLocation(7, 9),
// (8,11): error CS1503: Argument 1: cannot convert from 'double' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "1.0").WithArguments("1", "double", "int").WithLocation(8, 11));
}
[WorkItem(541050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541050")]
[Fact]
public void IncompleteDelegateDecl()
{
var source =
@"namespace nms {
delegate";
CreateCompilation(source).VerifyDiagnostics(
// (3,9): error CS1031: Type expected
// delegate
Diagnostic(ErrorCode.ERR_TypeExpected, ""),
// (3,9): error CS1001: Identifier expected
// delegate
Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
// (3,9): error CS1003: Syntax error, '(' expected
// delegate
Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", ""),
// (3,9): error CS1026: ) expected
// delegate
Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
// (3,9): error CS1002: ; expected
// delegate
Diagnostic(ErrorCode.ERR_SemicolonExpected, ""),
// (3,9): error CS1513: } expected
// delegate
Diagnostic(ErrorCode.ERR_RbraceExpected, ""));
}
[WorkItem(541213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541213")]
[Fact]
public void IncompleteElsePartInIfStmt()
{
var source =
@"public class Test
{
public static int Main(string [] args)
{
if (true)
{
}
else
";
CreateCompilation(source).VerifyDiagnostics(
// (8,13): error CS1733: Expected expression
// else
Diagnostic(ErrorCode.ERR_ExpressionExpected, ""),
// (9,1): error CS1002: ; expected
//
Diagnostic(ErrorCode.ERR_SemicolonExpected, ""),
// (9,1): error CS1513: } expected
//
Diagnostic(ErrorCode.ERR_RbraceExpected, ""),
// (9,1): error CS1513: } expected
//
Diagnostic(ErrorCode.ERR_RbraceExpected, ""),
// (3,23): error CS0161: 'Test.Main(string[])': not all code paths return a value
// public static int Main(string [] args)
Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("Test.Main(string[])")
);
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest01()
{
var baseAssembly = CreateCompilation(
@"
namespace BaseAssembly {
public class BaseClass {
}
}
", assemblyName: "BaseAssembly1").VerifyDiagnostics();
var derivedAssembly = CreateCompilation(
@"
namespace DerivedAssembly {
public class DerivedClass: BaseAssembly.BaseClass {
public static int IntField = 123;
}
}
", assemblyName: "DerivedAssembly1", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics();
var testAssembly = CreateCompilation(
@"
using ClassAlias = DerivedAssembly.DerivedClass;
public class Test
{
static void Main()
{
int a = ClassAlias.IntField;
int b = ClassAlias.IntField;
}
}
", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() })
.VerifyDiagnostics();
// NOTE: Dev10 errors:
// <fine-name>(7,9): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest02()
{
var baseAssembly = CreateCompilation(
@"
namespace BaseAssembly {
public class BaseClass {
}
}
", assemblyName: "BaseAssembly2").VerifyDiagnostics();
var derivedAssembly = CreateCompilation(
@"
namespace DerivedAssembly {
public class DerivedClass: BaseAssembly.BaseClass {
public static int IntField = 123;
}
}
", assemblyName: "DerivedAssembly2", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics();
var testAssembly = CreateCompilation(
@"
using ClassAlias = DerivedAssembly.DerivedClass;
public class Test
{
static void Main()
{
ClassAlias a = new ClassAlias();
ClassAlias b = new ClassAlias();
}
}
", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() })
.VerifyDiagnostics();
// NOTE: Dev10 errors:
// <fine-name>(6,9): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest03()
{
var baseAssembly = CreateCompilation(
@"
namespace BaseAssembly {
public class BaseClass {
}
}
", assemblyName: "BaseAssembly3").VerifyDiagnostics();
var derivedAssembly = CreateCompilation(
@"
namespace DerivedAssembly {
public class DerivedClass: BaseAssembly.BaseClass {
public static int IntField = 123;
}
}
", assemblyName: "DerivedAssembly3", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics();
var testAssembly = CreateCompilation(
@"
using ClassAlias = DerivedAssembly.DerivedClass;
public class Test
{
ClassAlias a = null;
ClassAlias b = null;
ClassAlias m() { return null; }
void m2(ClassAlias p) { }
}", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() })
.VerifyDiagnostics(
// (5,16): warning CS0414: The field 'Test.a' is assigned but its value is never used
// ClassAlias a = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("Test.a"),
// (6,16): warning CS0414: The field 'Test.b' is assigned but its value is never used
// ClassAlias b = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("Test.b")
);
// NOTE: Dev10 errors:
// <fine-name>(4,16): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_Typical()
{
string scenarioCode = @"
public class ITT
: IInterfaceBase
{ }
public interface IInterfaceBase
{
void bar();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.bar()'
// : IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.bar()").WithLocation(3, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_FullyQualified()
{
// Using fully Qualified names
string scenarioCode = @"
public class ITT
: test.IInterfaceBase
{ }
namespace test
{
public interface IInterfaceBase
{
void bar();
}
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.bar()'
// : test.IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "test.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.bar()").WithLocation(3, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithAlias()
{
// Using Alias
string scenarioCode = @"
using a1 = test;
public class ITT
: a1.IInterfaceBase
{ }
namespace test
{
public interface IInterfaceBase
{
void bar();
}
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (5,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.bar()'
// : a1.IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.bar()").WithLocation(5, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario01()
{
// Two interfaces, neither implemented with alias - should have 2 errors each squiggling a different interface type.
string scenarioCode = @"
using a1 = test;
public class ITT
: a1.IInterfaceBase, a1.IInterfaceBase2
{ }
namespace test
{
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void xyz();
}
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (5,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.xyz()'
// : a1.IInterfaceBase, a1.IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.xyz()").WithLocation(5, 7),
// (5,26): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase2.xyz()'
// : a1.IInterfaceBase, a1.IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase2").WithArguments("ITT", "test.IInterfaceBase2.xyz()").WithLocation(5, 26));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario02()
{
// Two interfaces, only the second is implemented
string scenarioCode = @"
public class ITT
: IInterfaceBase, IInterfaceBase2
{
void IInterfaceBase2.abc()
{ }
}
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void abc();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// : IInterfaceBase, IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(3, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario03()
{
// Two interfaces, only the first is implemented
string scenarioCode = @"
public class ITT
: IInterfaceBase, IInterfaceBase2
{
void IInterfaceBase.xyz()
{ }
}
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void abc();
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,23): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase2.abc()'
// : IInterfaceBase, IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase2").WithArguments("ITT", "IInterfaceBase2.abc()").WithLocation(3, 23));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario04()
{
// Two interfaces, neither implemented but formatting of interfaces are on different lines
string scenarioCode = @"
public class ITT
: IInterfaceBase,
IInterfaceBase2
{ }
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void xyz();
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// : IInterfaceBase,
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(3, 7),
// (4,6): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase2.xyz()'
// IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase2").WithArguments("ITT", "IInterfaceBase2.xyz()").WithLocation(4, 6));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario05()
{
// Inherited Interface scenario
// With methods not implemented in both base and derived.
// Should reflect 2 diagnostics but both with be squiggling the derived as we are not
// explicitly implementing base.
string scenarioCode = @"
public class ITT: IDerived
{ }
interface IInterfaceBase
{
void xyzb();
}
interface IDerived : IInterfaceBase
{
void xyzd();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,19): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()'
// public class ITT: IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 19),
// (2,19): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyzb()'
// public class ITT: IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IInterfaceBase.xyzb()").WithLocation(2, 19));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario06()
{
// Inherited Interface scenario
string scenarioCode = @"
public class ITT: IDerived, IInterfaceBase
{ }
interface IInterfaceBase
{
void xyz();
}
interface IDerived : IInterfaceBase
{
void xyzd();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,19): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()'
// public class ITT: IDerived, IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 19),
// (2,29): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// public class ITT: IDerived, IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(2, 29));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario07()
{
// Inherited Interface scenario - different order.
string scenarioCode = @"
public class ITT: IInterfaceBase, IDerived
{ }
interface IDerived : IInterfaceBase
{
void xyzd();
}
interface IInterfaceBase
{
void xyz();
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,35): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()'
// public class ITT: IInterfaceBase, IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 35),
// (2,19): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// public class ITT: IInterfaceBase, IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(2, 19));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario08()
{
// Inherited Interface scenario
string scenarioCode = @"
public class ITT: IDerived2
{}
interface IBase
{
void method1();
}
interface IBase2
{
void Method2();
}
interface IDerived2: IBase, IBase2
{}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,19): error CS0535: 'ITT' does not implement interface member 'IBase.method1()'
// public class ITT: IDerived2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived2").WithArguments("ITT", "IBase.method1()").WithLocation(2, 19),
// (2,19): error CS0535: 'ITT' does not implement interface member 'IBase2.Method2()'
// public class ITT: IDerived2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived2").WithArguments("ITT", "IBase2.Method2()").WithLocation(2, 19));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation13UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario09()
{
// Inherited Interface scenario.
string scenarioCode = @"
public class ITT : IDerived
{
void IBase2.method2()
{ }
void IDerived.method3()
{ }
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IDerived : IBase, IBase2
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,20): error CS0535: 'ITT' does not implement interface member 'IBase.method1()'
// public class ITT : IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IBase.method1()").WithLocation(2, 20));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario10()
{
// Inherited Interface scenario.
string scenarioCode = @"
public class ITT : IDerived
{
void IBase2.method2()
{ }
void IBase3.method3()
{ }
void IDerived.method4()
{ }
}
public interface IBase
{
void method1();
}
public interface IBase2 : IBase
{
void method2();
}
public interface IBase3 : IBase
{
void method3();
}
public interface IDerived : IBase2, IBase3
{
void method4();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,20): error CS0535: 'ITT' does not implement interface member 'IBase.method1()'
// public class ITT : IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IBase.method1()").WithLocation(2, 20));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario11()
{
// Inherited Interface scenario
string scenarioCode = @"
static class Module1
{
public static void Main()
{
}
}
interface Ibase
{
void method1();
}
interface Ibase2
{
void method2();
}
interface Iderived : Ibase
{
void method3();
}
interface Iderived2 : Iderived
{
void method4();
}
class foo : Iderived2, Iderived, Ibase, Ibase2
{
void Ibase.method1()
{ }
void Ibase2.method2()
{ }
void Iderived2.method4()
{ }
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (29,24): error CS0535: 'foo' does not implement interface member 'Iderived.method3()'
// class foo : Iderived2, Iderived, Ibase, Ibase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Iderived").WithArguments("foo", "Iderived.method3()").WithLocation(29, 24));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithPartialClass01()
{
// partial class - missing method.
// each partial implements interface but one is missing method.
string scenarioCode = @"
public partial class Foo : IBase
{
void IBase.method1()
{ }
void IBase2.method2()
{ }
}
public partial class Foo : IBase2
{
}
public partial class Foo : IBase3
{
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IBase3
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (15,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()'
// public partial class Foo : IBase3
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(15, 28));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithPartialClass02()
{
// partial class - missing method. diagnostic is reported in correct partial class
// one partial class specifically does include any inherited interface
string scenarioCode = @"
public partial class Foo : IBase, IBase2
{
void IBase.method1()
{ }
}
public partial class Foo
{
}
public partial class Foo : IBase3
{
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IBase3
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,35): error CS0535: 'Foo' does not implement interface member 'IBase2.method2()'
// public partial class Foo : IBase, IBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase2").WithArguments("Foo", "IBase2.method2()").WithLocation(2, 35),
// (13,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()'
// public partial class Foo : IBase3
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(13, 28));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithPartialClass03()
{
// Partial class scenario
// One class implements multiple interfaces and is missing method.
string scenarioCode = @"
public partial class Foo : IBase, IBase2
{
void IBase.method1()
{ }
}
public partial class Foo : IBase3
{
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IBase3
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,35): error CS0535: 'Foo' does not implement interface member 'IBase2.method2()'
// public partial class Foo : IBase, IBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase2").WithArguments("Foo", "IBase2.method2()").WithLocation(2, 35),
// (9,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()'
// public partial class Foo : IBase3
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(9, 28)
);
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest04()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
void m()
{
int a = ClassAlias.Class1Foo();
int b = ClassAlias.Class1Foo();
}
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (7,28): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// int a = ClassAlias.Class1Foo();
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1Foo").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (8,28): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// int b = ClassAlias.Class1Foo();
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1Foo").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")
);
// NOTE: Dev10 errors:
// <fine-name>(8,28): error CS0117: 'Class1' does not contain a definition for 'Class1Foo'
// <fine-name>(9,28): error CS0117: 'Class1' does not contain a definition for 'Class1Foo'
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest05()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
void m()
{
var a = new ClassAlias();
var b = new ClassAlias();
}
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")
);
// NOTE: Dev10 errors:
// <fine-name>(8,17): error CS0143: The type 'Class1' has no constructors defined
// <fine-name>(9,17): error CS0143: The type 'Class1' has no constructors defined
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest06()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
ClassAlias a = null;
ClassAlias b = null;
ClassAlias m() { return null; }
void m2(ClassAlias p) { }
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (6,16): warning CS0414: The field 'Test.b' is assigned but its value is never used
// ClassAlias b = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("Test.b"),
// (5,16): warning CS0414: The field 'Test.a' is assigned but its value is never used
// ClassAlias a = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("Test.a")
);
// NOTE: Dev10 errors:
// <fine-name>(4,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
// <fine-name>(5,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
// <fine-name>(6,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
// <fine-name>(7,10): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest07()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
void m()
{
ClassAlias a = null;
ClassAlias b = null;
System.Console.WriteLine(a);
System.Console.WriteLine(b);
}
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (9,9): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// System.Console.WriteLine(a);
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "System.Console.WriteLine").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (10,9): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// System.Console.WriteLine(b);
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "System.Console.WriteLine").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"));
// NOTE: Dev10 reports NO ERRORS
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_1()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_1");
var source2 = @"
public interface IBar
{
ImageMoniker? Moniker { get; }
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_1");
var source3 = @"
public class BarImpl : IBar
{
public ImageMoniker? Moniker
{
get { return null; }
}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_2()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_2");
var source2 = @"
public interface IBar
{
ImageMoniker? Moniker { get; }
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_2");
var source3 = @"
public class BarImpl : IBar
{
ImageMoniker? IBar.Moniker
{
get { return null; }
}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (4,24): error CS0539: 'BarImpl.Moniker' in explicit interface declaration is not a member of interface
// ImageMoniker? IBar.Moniker
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Moniker").WithArguments("BarImpl.Moniker").WithLocation(4, 24),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (4,24): error CS0539: 'BarImpl.Moniker' in explicit interface declaration is not a member of interface
// ImageMoniker? IBar.Moniker
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Moniker").WithArguments("BarImpl.Moniker").WithLocation(4, 24),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_3()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_3");
var source2 = @"
public interface IBar
{
void SetMoniker(ImageMoniker? moniker);
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_3");
var source3 = @"
public class BarImpl : IBar
{
public void SetMoniker(ImageMoniker? moniker)
{}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_4()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_4");
var source2 = @"
public interface IBar
{
void SetMoniker(ImageMoniker? moniker);
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_4");
var source3 = @"
public class BarImpl : IBar
{
void IBar.SetMoniker(ImageMoniker? moniker)
{}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (4,15): error CS0539: 'BarImpl.SetMoniker(ImageMoniker?)' in explicit interface declaration is not a member of interface
// void IBar.SetMoniker(ImageMoniker? moniker)
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "SetMoniker").WithArguments("BarImpl.SetMoniker(ImageMoniker?)").WithLocation(4, 15),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (4,15): error CS0539: 'BarImpl.SetMoniker(ImageMoniker?)' in explicit interface declaration is not a member of interface
// void IBar.SetMoniker(ImageMoniker? moniker)
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "SetMoniker").WithArguments("BarImpl.SetMoniker(ImageMoniker?)").WithLocation(4, 15),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(541246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541246")]
[Fact]
public void NamespaceQualifiedGenericTypeName()
{
var source =
@"namespace N
{
public class A<T>
{
public static T F;
}
}
class B
{
static int G = N.A<int>.F;
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void NamespaceQualifiedGenericTypeNameWrongArity()
{
var source =
@"namespace N
{
public class A<T>
{
public static T F;
}
public class B
{
public static int F;
}
public class B<T1, T2>
{
public static System.Tuple<T1, T2> F;
}
}
class C
{
static int TooMany = N.A<int, int>.F;
static int TooFew = N.A.F;
static int TooIndecisive = N.B<int>;
}";
CreateCompilation(source).VerifyDiagnostics(
// (19,28): error CS0305: Using the generic type 'N.A<T>' requires '1' type arguments
//
Diagnostic(ErrorCode.ERR_BadArity, "A<int, int>").WithArguments("N.A<T>", "type", "1"),
// (20,27): error CS0305: Using the generic type 'N.A<T>' requires '1' type arguments
//
Diagnostic(ErrorCode.ERR_BadArity, "A").WithArguments("N.A<T>", "type", "1"),
// (21,34): error CS0308: The non-generic type 'N.B' cannot be used with type arguments
//
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "B<int>").WithArguments("N.B", "type")
);
}
[WorkItem(541570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541570")]
[Fact]
public void EnumNotMemberInConstructor()
{
var source =
@"enum E { A }
class C
{
public C(E e = E.A) { }
public E E { get { return E.A; } }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(541638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541638")]
[Fact]
public void KeywordAsLabelIdentifier()
{
var source =
@"class Program
{
static void Main(string[] args)
{
@int1:
System.Console.WriteLine();
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,5): warning CS0164: This label has not been referenced
//
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "@int1"));
}
[WorkItem(541677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541677")]
[Fact]
public void AssignStaticEventToLocalVariable()
{
var source =
@"delegate void Foo();
class driver
{
public static event Foo e;
static void Main(string[] args)
{
Foo x = e;
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
// Note: The locations for errors on generic methods are
// name only, while Dev11 uses name + type parameters.
[WorkItem(528743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528743")]
[Fact]
public void GenericMethodLocation()
{
var source =
@"interface I
{
void M1<T>() where T : class;
}
class C : I
{
public void M1<T>() { }
void M2<T>(this object o) { }
sealed void M3<T>() { }
internal static virtual void M4<T>() { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,7): error CS1106: Extension method must be defined in a non-generic static class
// class C : I
Diagnostic(ErrorCode.ERR_BadExtensionAgg, "C").WithLocation(5, 7),
// (7,17): error CS0425: The constraints for type parameter 'T' of method 'C.M1<T>()' must match the constraints for type parameter 'T' of interface method 'I.M1<T>()'. Consider using an explicit interface implementation instead.
// public void M1<T>() { }
Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "C.M1<T>()", "T", "I.M1<T>()").WithLocation(7, 17),
// (9,17): error CS0238: 'C.M3<T>()' cannot be sealed because it is not an override
// sealed void M3<T>() { }
Diagnostic(ErrorCode.ERR_SealedNonOverride, "M3").WithArguments("C.M3<T>()").WithLocation(9, 17),
// (10,34): error CS0112: A static member cannot be marked as 'virtual'
// internal static virtual void M4<T>() { }
Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M4").WithArguments("virtual").WithLocation(10, 34)
);
}
[WorkItem(542391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542391")]
[Fact]
public void PartialMethodOptionalParameters()
{
var source =
@"partial class C
{
partial void M1(object o);
partial void M1(object o = null) { }
partial void M2(object o = null);
partial void M2(object o) { }
partial void M3(object o = null);
partial void M3(object o = null) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,28): warning CS1066: The default value specified for parameter 'o' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments
// partial void M1(object o = null) { }
Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "o").WithArguments("o"),
// (8,28): warning CS1066: The default value specified for parameter 'o' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments
// partial void M3(object o = null) { }
Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "o").WithArguments("o")
);
}
[Fact]
[WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")]
public void PartialMethodParameterNamesFromDefinition1()
{
var source = @"
partial class C
{
partial void F(int i);
}
partial class C
{
partial void F(int j) { }
}
";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<MethodSymbol>("F");
Assert.Equal("i", method.Parameters[0].Name);
});
}
[Fact]
[WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")]
public void PartialMethodParameterNamesFromDefinition2()
{
var source = @"
partial class C
{
partial void F(int j) { }
}
partial class C
{
partial void F(int i);
}
";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<MethodSymbol>("F");
Assert.Equal("i", method.Parameters[0].Name);
});
}
/// <summary>
/// Handle a mix of parameter errors for default values,
/// partial methods, and static parameter type.
/// </summary>
[Fact]
public void ParameterErrorsDefaultPartialMethodStaticType()
{
var source =
@"static class S { }
partial class C
{
partial void M(S s = new A());
partial void M(S s = new B()) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,18): error CS0721: 'S': static types cannot be used as parameters
// partial void M(S s = new A());
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M").WithArguments("S").WithLocation(4, 18),
// (5,18): error CS0721: 'S': static types cannot be used as parameters
// partial void M(S s = new B()) { }
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M").WithArguments("S").WithLocation(5, 18),
// (5,30): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)
// partial void M(S s = new B()) { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(5, 30),
// (4,30): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// partial void M(S s = new A());
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(4, 30)
);
}
[WorkItem(543349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543349")]
[Fact]
public void Fixed()
{
var source =
@"class C
{
unsafe static void M(int[] arg)
{
fixed (int* ptr = arg) { }
fixed (int* ptr = arg) *ptr = 0;
fixed (int* ptr = arg) object o = null;
}
}";
CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,32): error CS1023: Embedded statement cannot be a declaration or labeled statement
// fixed (int* ptr = arg) object o = null;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "object o = null;").WithLocation(7, 32),
// (7,39): warning CS0219: The variable 'o' is assigned but its value is never used
// fixed (int* ptr = arg) object o = null;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o").WithArguments("o").WithLocation(7, 39)
);
}
[WorkItem(1040171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040171")]
[Fact]
public void Bug1040171()
{
const string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
foreach (string s in args)
label: c = false;
}
}
";
var compilation = CreateCompilation(sourceCode);
compilation.VerifyDiagnostics(
// (9,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// label: c = false;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "label: c = false;").WithLocation(9, 13),
// (9,13): warning CS0164: This label has not been referenced
// label: c = false;
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(9, 13),
// (6,14): warning CS0219: The variable 'c' is assigned but its value is never used
// bool c = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c").WithLocation(6, 14));
}
[Fact, WorkItem(543426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543426")]
private void NestedInterfaceImplementationWithOuterGenericType()
{
CompileAndVerify(@"
namespace System.ServiceModel
{
class Pipeline<T>
{
interface IStage
{
void Process(T context);
}
class AsyncStage : IStage
{
void IStage.Process(T context) { }
}
}
}");
}
/// <summary>
/// Error types should be allowed as constant types.
/// </summary>
[Fact]
public void ErrorTypeConst()
{
var source =
@"class C
{
const C1 F1 = 0;
const C2 F2 = null;
static void M()
{
const C3 c3 = 0;
const C4 c4 = null;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (3,11): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C1").WithArguments("C1").WithLocation(3, 11),
// (4,11): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C2").WithArguments("C2").WithLocation(4, 11),
// (7,15): error CS0246: The type or namespace name 'C3' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C3").WithArguments("C3").WithLocation(7, 15),
// (8,15): error CS0246: The type or namespace name 'C4' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C4").WithArguments("C4").WithLocation(8, 15));
}
[WorkItem(543777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543777")]
[Fact]
public void DefaultParameterAtEndOfFile()
{
var source =
@"class C
{
static void M(object o = null,";
CreateCompilation(source).VerifyDiagnostics(
// (3,35): error CS1031: Type expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_TypeExpected, ""),
// Cascading:
// (3,35): error CS1001: Identifier expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
// (3,35): error CS1026: ) expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
// (3,35): error CS1002: ; expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_SemicolonExpected, ""),
// (3,35): error CS1513: } expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_RbraceExpected, ""),
// (3,35): error CS1737: Optional parameters must appear after all required parameters
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_DefaultValueBeforeRequiredValue, ""),
// (3,17): error CS0501: 'C.M(object, ?)' must declare a body because it is not
// marked abstract, extern, or partial static void M(object o = null,
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("C.M(object, ?)"));
}
[WorkItem(543814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543814")]
[Fact]
public void DuplicateNamedArgumentNullLiteral()
{
var source =
@"class C
{
static void M()
{
M("""",
arg: 0,
arg: null);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,9): error CS1501: No overload for method 'M' takes 3 arguments
// M("",
Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "3").WithLocation(5, 9));
}
[WorkItem(543820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543820")]
[Fact]
public void GenericAttributeClassWithMultipleParts()
{
var source =
@"class C<T> { }
class C<T> : System.Attribute { }";
CreateCompilation(source).VerifyDiagnostics(
// (2,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'C'
// class C<T> : System.Attribute { }
Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>"),
// (2,14): error CS0698: A generic type cannot derive from 'System.Attribute' because it is an attribute class
// class C<T> : System.Attribute { }
Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "System.Attribute").WithArguments("System.Attribute")
);
}
[WorkItem(543822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543822")]
[Fact]
public void InterfaceWithPartialMethodExplicitImplementation()
{
var source =
@"interface I
{
partial void I.M();
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(
// (3,20): error CS0754: A partial method may not explicitly implement an interface method
// partial void I.M();
Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "M").WithLocation(3, 20),
// (3,20): error CS0751: A partial method must be declared within a partial type
// partial void I.M();
Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 20),
// (3,20): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater.
// partial void I.M();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "M").WithArguments("default interface implementation", "8.0").WithLocation(3, 20),
// (3,18): error CS0540: 'I.M()': containing type does not implement interface 'I'
// partial void I.M();
Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I").WithArguments("I.M()", "I").WithLocation(3, 18)
);
}
[WorkItem(543827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543827")]
[Fact]
public void StructConstructor()
{
var source =
@"struct S
{
private readonly object x;
private readonly object y;
S(object x, object y)
{
try
{
this.x = x;
}
finally
{
this.y = y;
}
}
S(S o) : this(o.x, o.y) {}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(543827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543827")]
[Fact]
public void StructVersusTryFinally()
{
var source =
@"struct S
{
private object x;
private object y;
static void M()
{
S s1;
try { s1.x = null; } finally { s1.y = null; }
S s2 = s1;
s1.x = s1.y; s1.y = s1.x;
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(544513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544513")]
[Fact()]
public void AnonTypesPropSameNameDiffType()
{
var source =
@"public class Test
{
public static void Main()
{
var p1 = new { Price = 495.00 };
var p2 = new { Price = ""36.50"" };
p1 = p2;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (8,14): error CS0029: Cannot implicitly convert type 'AnonymousType#1' to 'AnonymousType#2'
// p1 = p2;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "p2").WithArguments("<anonymous type: string Price>", "<anonymous type: double Price>"));
}
[WorkItem(545869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545869")]
[Fact]
public void TestSealedOverriddenMembers()
{
CompileAndVerify(
@"using System;
internal abstract class Base
{
public virtual int Property
{
get { return 0; }
protected set { }
}
protected virtual event EventHandler Event
{
add { } remove { }
}
protected abstract void Method();
}
internal sealed class Derived : Base
{
public override int Property
{
get { return 1; }
protected set { }
}
protected override event EventHandler Event;
protected override void Method() { }
void UseEvent() { Event(null, null); }
}
internal sealed class Derived2 : Base
{
public override int Property
{
get; protected set;
}
protected override event EventHandler Event
{
add { } remove { }
}
protected override void Method() { }
}
class Program
{
static void Main() { }
}").VerifyDiagnostics();
}
[Fact, WorkItem(1068547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068547")]
public void Bug1068547_01()
{
var source =
@"
class Program
{
[System.Diagnostics.DebuggerDisplay(this)]
static void Main(string[] args)
{
}
}";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.ThisExpression)).Cast<ThisExpressionSyntax>().Single();
var symbolInfo = model.GetSymbolInfo(node);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason);
}
[Fact, WorkItem(1068547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068547")]
public void Bug1068547_02()
{
var source =
@"
[System.Diagnostics.DebuggerDisplay(this)]
";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.ThisExpression)).Cast<ThisExpressionSyntax>().Single();
var symbolInfo = model.GetSymbolInfo(node);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason);
}
[Fact]
public void RefReturningDelegateCreation()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
ref int M()
{
return ref field;
}
void Test()
{
new D(M)();
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefReturningDelegateCreationBad()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
int M()
{
return field;
}
void Test()
{
new D(M)();
}
}
";
CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics(
// (15,15): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// new D(M)();
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(15, 15)
);
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (15,15): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// new D(M)();
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(15, 15)
);
}
[Fact]
public void RefReturningDelegateArgument()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
ref int M()
{
return ref field;
}
void M(D d)
{
}
void Test()
{
M(M);
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefReturningDelegateArgumentBad()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
int M()
{
return field;
}
void M(D d)
{
}
void Test()
{
M(M);
}
}
";
CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics(
// (19,11): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// M(M);
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(19, 11)
);
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (19,11): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// M(M);
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(19, 11)
);
}
[Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")]
public void Bug1078958()
{
const string source = @"
class C
{
static void Foo<T>()
{
T();
}
static void T() { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (6,9): error CS0119: 'T' is a type, which is not valid in the given context
// T();
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 9));
}
[Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")]
public void Bug1078958_2()
{
const string source = @"
class C
{
static void Foo<T>()
{
T<T>();
}
static void T() { }
static void T<U>() { }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961()
{
const string source = @"
class C
{
const int T = 42;
static void Foo<T>(int x = T)
{
System.Console.Write(x);
}
static void Main()
{
Foo<object>();
}
}";
CompileAndVerify(source, expectedOutput: "42");
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_2()
{
const string source = @"
class A : System.Attribute
{
public A(int i) { }
}
class C
{
const int T = 42;
static void Foo<T>([A(T)] int x)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var t = (FieldSymbol)c.GetMembers("T").Single();
var foo = (MethodSymbol)c.GetMembers("Foo").Single();
var x = foo.Parameters[0];
var a = x.GetAttributes()[0];
var i = a.ConstructorArguments.Single();
Assert.Equal((int)i.Value, (int)t.ConstantValue);
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_3()
{
const string source = @"
class A : System.Attribute
{
public A(int i) { }
}
class C
{
const int T = 42;
[A(T)]
static void Foo<T>(int x)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var t = (FieldSymbol)c.GetMembers("T").Single();
var foo = (MethodSymbol)c.GetMembers("Foo").Single();
var a = foo.GetAttributes()[0];
var i = a.ConstructorArguments.Single();
Assert.Equal((int)i.Value, (int)t.ConstantValue);
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_4()
{
const string source = @"
class A : System.Attribute
{
public A(int i) { }
}
class C
{
const int T = 42;
static void Foo<[A(T)] T>(int x)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var t = (FieldSymbol)c.GetMembers("T").Single();
var foo = (MethodSymbol)c.GetMembers("Foo").Single();
var tt = foo.TypeParameters[0];
var a = tt.GetAttributes()[0];
var i = a.ConstructorArguments.Single();
Assert.Equal((int)i.Value, (int)t.ConstantValue);
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_5()
{
const string source = @"
class C
{
class T { }
static void Foo<T>(T x = default(T))
{
System.Console.Write((object)x == null);
}
static void Main()
{
Foo<object>();
}
}";
CompileAndVerify(source, expectedOutput: "True");
}
[Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")]
public void CastToDelegate_01()
{
var sourceText = @"namespace NS
{
public static class A
{
public delegate void Action();
public static void M()
{
RunAction(A.B<string>.M0);
RunAction((Action)A.B<string>.M1);
}
private static void RunAction(Action action) { }
private class B<T>
{
public static void M0() { }
public static void M1() { }
}
}
}";
var compilation = CreateCompilation(sourceText, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var identifierNameM0 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M0"));
Assert.Equal("A.B<string>.M0", identifierNameM0.Parent.ToString());
var m0Symbol = model.GetSymbolInfo(identifierNameM0);
Assert.Equal("void NS.A.B<System.String>.M0()", m0Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m0Symbol.CandidateReason);
var identifierNameM1 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M1"));
Assert.Equal("A.B<string>.M1", identifierNameM1.Parent.ToString());
var m1Symbol = model.GetSymbolInfo(identifierNameM1);
Assert.Equal("void NS.A.B<System.String>.M1()", m1Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m1Symbol.CandidateReason);
}
[Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")]
public void CastToDelegate_02()
{
var sourceText = @"
class A
{
public delegate void MyDelegate<T>(T a);
public void Test()
{
UseMyDelegate((MyDelegate<int>)MyMethod);
UseMyDelegate((MyDelegate<long>)MyMethod);
UseMyDelegate((MyDelegate<float>)MyMethod);
UseMyDelegate((MyDelegate<double>)MyMethod);
}
private void UseMyDelegate<T>(MyDelegate<T> f) { }
private static void MyMethod(int a) { }
private static void MyMethod(long a) { }
private static void MyMethod(float a) { }
private static void MyMethod(double a) { }
}";
var compilation = CreateCompilation(sourceText, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var identifiers = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(x => x.Identifier.ValueText.Equals("MyMethod")).ToArray();
Assert.Equal(4, identifiers.Length);
Assert.Equal("(MyDelegate<int>)MyMethod", identifiers[0].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Int32 a)", model.GetSymbolInfo(identifiers[0]).Symbol.ToTestDisplayString());
Assert.Equal("(MyDelegate<long>)MyMethod", identifiers[1].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Int64 a)", model.GetSymbolInfo(identifiers[1]).Symbol.ToTestDisplayString());
Assert.Equal("(MyDelegate<float>)MyMethod", identifiers[2].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Single a)", model.GetSymbolInfo(identifiers[2]).Symbol.ToTestDisplayString());
Assert.Equal("(MyDelegate<double>)MyMethod", identifiers[3].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Double a)", model.GetSymbolInfo(identifiers[3]).Symbol.ToTestDisplayString());
}
[Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")]
public void CastToDelegate_03()
{
var sourceText = @"namespace NS
{
public static class A
{
public delegate void Action();
public static void M()
{
var b = new A.B<string>();
RunAction(b.M0);
RunAction((Action)b.M1);
}
private static void RunAction(Action action) { }
public class B<T>
{
}
public static void M0<T>(this B<T> x) { }
public static void M1<T>(this B<T> x) { }
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceText, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var identifierNameM0 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M0"));
Assert.Equal("b.M0", identifierNameM0.Parent.ToString());
var m0Symbol = model.GetSymbolInfo(identifierNameM0);
Assert.Equal("void NS.A.B<System.String>.M0<System.String>()", m0Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m0Symbol.CandidateReason);
var identifierNameM1 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M1"));
Assert.Equal("b.M1", identifierNameM1.Parent.ToString());
var m1Symbol = model.GetSymbolInfo(identifierNameM1);
Assert.Equal("void NS.A.B<System.String>.M1<System.String>()", m1Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m1Symbol.CandidateReason);
}
[Fact, WorkItem(5170, "https://github.com/dotnet/roslyn/issues/5170")]
public void TypeOfBinderParameter()
{
var sourceText = @"
using System.Linq;
using System.Text;
public static class LazyToStringExtension
{
public static string LazyToString<T>(this T obj) where T : class
{
StringBuilder sb = new StringBuilder();
typeof(T)
.GetProperties(System.Reflection.BindingFlags.Public)
.Select(x => x.GetValue(obj))
}
}";
var compilation = CreateCompilationWithMscorlib40(sourceText, new[] { TestMetadata.Net40.SystemCore }, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics(
// (12,42): error CS1002: ; expected
// .Select(x => x.GetValue(obj))
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(12, 42),
// (12,28): error CS1501: No overload for method 'GetValue' takes 1 arguments
// .Select(x => x.GetValue(obj))
Diagnostic(ErrorCode.ERR_BadArgCount, "GetValue").WithArguments("GetValue", "1").WithLocation(12, 28),
// (7,26): error CS0161: 'LazyToStringExtension.LazyToString<T>(T)': not all code paths return a value
// public static string LazyToString<T>(this T obj) where T : class
Diagnostic(ErrorCode.ERR_ReturnExpected, "LazyToString").WithArguments("LazyToStringExtension.LazyToString<T>(T)").WithLocation(7, 26));
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single();
var param = node.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single();
Assert.Equal("System.Reflection.PropertyInfo x", model.GetDeclaredSymbol(param).ToTestDisplayString());
}
[Fact, WorkItem(7520, "https://github.com/dotnet/roslyn/issues/7520")]
public void DelegateCreationWithIncompleteLambda()
{
var source =
@"
using System;
class C
{
public void F()
{
var x = new Action<int>(i => i.
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,40): error CS1001: Identifier expected
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(7, 40),
// (7,40): error CS1026: ) expected
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 40),
// (7,40): error CS1002: ; expected
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 40),
// (7,38): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_IllegalStatement, @"i.
").WithLocation(7, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single();
var param = lambda.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single();
var symbol1 = model.GetDeclaredSymbol(param);
Assert.Equal("System.Int32 i", symbol1.ToTestDisplayString());
var id = lambda.DescendantNodes().First(n => n.IsKind(SyntaxKind.IdentifierName));
var symbol2 = model.GetSymbolInfo(id).Symbol;
Assert.Equal("System.Int32 i", symbol2.ToTestDisplayString());
Assert.Same(symbol1, symbol2);
}
[Fact, WorkItem(7520, "https://github.com/dotnet/roslyn/issues/7520")]
public void ImplicitDelegateCreationWithIncompleteLambda()
{
var source =
@"
using System;
class C
{
public void F()
{
Action<int> x = i => i.
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,32): error CS1001: Identifier expected
// Action<int> x = i => i.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(7, 32),
// (7,32): error CS1002: ; expected
// Action<int> x = i => i.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 32),
// (7,30): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// Action<int> x = i => i.
Diagnostic(ErrorCode.ERR_IllegalStatement, @"i.
").WithLocation(7, 30)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single();
var param = lambda.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single();
var symbol1 = model.GetDeclaredSymbol(param);
Assert.Equal("System.Int32 i", symbol1.ToTestDisplayString());
var id = lambda.DescendantNodes().First(n => n.IsKind(SyntaxKind.IdentifierName));
var symbol2 = model.GetSymbolInfo(id).Symbol;
Assert.Equal("System.Int32 i", symbol2.ToTestDisplayString());
Assert.Same(symbol1, symbol2);
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_01()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
}
static class IApplicationBuilderExtensions
{
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware)
{
return app;
}
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore });
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(38, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(1, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_02()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
IApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware);
}
static class IApplicationBuilderExtensions
{
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware)
{
return app;
}
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore });
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(38, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(1, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_03()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
IApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware);
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(31, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(2, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols[1].ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_04()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
}
static class IApplicationBuilderExtensions
{
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware)
{
return app;
}
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware)
{
return app;
}
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore });
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(42, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(2, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols[1].ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(7101, "https://github.com/dotnet/roslyn/issues/7101")]
public void UsingStatic_01()
{
var source =
@"
using System;
using static ClassWithNonStaticMethod;
using static Extension1;
class Program
{
static void Main(string[] args)
{
var instance = new Program();
instance.NonStaticMethod();
}
private void NonStaticMethod()
{
MathMin(0, 1);
MathMax(0, 1);
MathMax2(0, 1);
int x;
x = F1;
x = F2;
x.MathMax2(3);
}
}
class ClassWithNonStaticMethod
{
public static int MathMax(int a, int b)
{
return Math.Max(a, b);
}
public int MathMin(int a, int b)
{
return Math.Min(a, b);
}
public int F2 = 0;
}
static class Extension1
{
public static int MathMax2(this int a, int b)
{
return Math.Max(a, b);
}
public static int F1 = 0;
}
static class Extension2
{
public static int MathMax3(this int a, int b)
{
return Math.Max(a, b);
}
}
";
var comp = CreateCompilationWithMscorlib45(source);
comp.VerifyDiagnostics(
// (16,9): error CS0103: The name 'MathMin' does not exist in the current context
// MathMin(0, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "MathMin").WithArguments("MathMin").WithLocation(16, 9),
// (18,9): error CS0103: The name 'MathMax2' does not exist in the current context
// MathMax2(0, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "MathMax2").WithArguments("MathMax2").WithLocation(18, 9),
// (22,13): error CS0103: The name 'F2' does not exist in the current context
// x = F2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "F2").WithArguments("F2").WithLocation(22, 13)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "MathMin").Single().Parent;
Assert.Equal("MathMin(0, 1)", node1.ToString());
var names = model.LookupNames(node1.SpanStart);
Assert.False(names.Contains("MathMin"));
Assert.True(names.Contains("MathMax"));
Assert.True(names.Contains("F1"));
Assert.False(names.Contains("F2"));
Assert.False(names.Contains("MathMax2"));
Assert.False(names.Contains("MathMax3"));
Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMin").IsEmpty);
Assert.Equal(1, model.LookupSymbols(node1.SpanStart, name: "MathMax").Length);
Assert.Equal(1, model.LookupSymbols(node1.SpanStart, name: "F1").Length);
Assert.True(model.LookupSymbols(node1.SpanStart, name: "F2").IsEmpty);
Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMax2").IsEmpty);
Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMax3").IsEmpty);
var symbols = model.LookupSymbols(node1.SpanStart);
Assert.False(symbols.Where(s => s.Name == "MathMin").Any());
Assert.True(symbols.Where(s => s.Name == "MathMax").Any());
Assert.True(symbols.Where(s => s.Name == "F1").Any());
Assert.False(symbols.Where(s => s.Name == "F2").Any());
Assert.False(symbols.Where(s => s.Name == "MathMax2").Any());
Assert.False(symbols.Where(s => s.Name == "MathMax3").Any());
}
[Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")]
public void UsingStaticGenericConstraint()
{
var code = @"
using static Test<System.String>;
public static class Test<T> where T : struct { }
";
CreateCompilationWithMscorlib45(code).VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using static Test<System.String>;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Test<System.String>;").WithLocation(2, 1),
// (2,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>'
// using static Test<System.String>;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test<System.String>").WithArguments("Test<T>", "T", "string").WithLocation(2, 14));
}
[Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")]
public void UsingStaticGenericConstraintNestedType()
{
var code = @"
using static A<A<int>[]>.B;
class A<T> where T : class
{
internal static class B { }
}
";
CreateCompilationWithMscorlib45(code).VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using static A<A<int>[]>.B;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<A<int>[]>.B;").WithLocation(2, 1),
// (2,14): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'A<T>'
// using static A<A<int>[]>.B;
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "A<A<int>[]>.B").WithArguments("A<T>", "T", "int").WithLocation(2, 14));
}
[Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")]
public void UsingStaticMultipleGenericConstraints()
{
var code = @"
using static A<int, string>;
static class A<T, U> where T : class where U : struct { }
";
CreateCompilationWithMscorlib45(code).VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using static A<int, string>;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<int, string>;").WithLocation(2, 1),
// (2,14): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'A<T, U>'
// using static A<int, string>;
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "A<int, string>").WithArguments("A<T, U>", "T", "int").WithLocation(2, 14),
// (2,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<T, U>'
// using static A<int, string>;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "A<int, string>").WithArguments("A<T, U>", "U", "string").WithLocation(2, 14));
}
[Fact, WorkItem(8234, "https://github.com/dotnet/roslyn/issues/8234")]
public void EventAccessInTypeNameContext()
{
var source =
@"
class Program
{
static void Main() {}
event System.EventHandler E1;
void Test(Program x)
{
System.Console.WriteLine();
x.E1.E
System.Console.WriteLine();
}
void Dummy()
{
E1 = null;
var x = E1;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,15): error CS1001: Identifier expected
// x.E1.E
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(11, 15),
// (11,15): error CS1002: ; expected
// x.E1.E
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 15),
// (11,9): error CS0118: 'x' is a variable but is used like a type
// x.E1.E
Diagnostic(ErrorCode.ERR_BadSKknown, "x").WithArguments("x", "variable", "type").WithLocation(11, 9)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "E").Single().Parent;
Assert.Equal("x.E1.E", node1.ToString());
Assert.Equal(SyntaxKind.QualifiedName, node1.Kind());
var node2 = ((QualifiedNameSyntax)node1).Left;
Assert.Equal("x.E1", node2.ToString());
var symbolInfo2 = model.GetSymbolInfo(node2);
Assert.Null(symbolInfo2.Symbol);
Assert.Equal("event System.EventHandler Program.E1", symbolInfo2.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.NotATypeOrNamespace, symbolInfo2.CandidateReason);
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.True(symbolInfo1.CandidateSymbols.IsEmpty);
}
[Fact, WorkItem(13617, "https://github.com/dotnet/roslyn/issues/13617")]
public void MissingTypeArgumentInGenericExtensionMethod()
{
var source =
@"
public static class FooExtensions
{
public static object ExtensionMethod0(this object obj) => default(object);
public static T ExtensionMethod1<T>(this object obj) => default(T);
public static T1 ExtensionMethod2<T1, T2>(this object obj) => default(T1);
}
public class Class1
{
public void Test()
{
var omittedArg0 = ""string literal"".ExtensionMethod0<>();
var omittedArg1 = ""string literal"".ExtensionMethod1<>();
var omittedArg2 = ""string literal"".ExtensionMethod2<>();
var omittedArgFunc0 = ""string literal"".ExtensionMethod0<>;
var omittedArgFunc1 = ""string literal"".ExtensionMethod1<>;
var omittedArgFunc2 = ""string literal"".ExtensionMethod2<>;
var moreArgs0 = ""string literal"".ExtensionMethod0<int>();
var moreArgs1 = ""string literal"".ExtensionMethod1<int, bool>();
var moreArgs2 = ""string literal"".ExtensionMethod2<int, bool, string>();
var lessArgs1 = ""string literal"".ExtensionMethod1();
var lessArgs2 = ""string literal"".ExtensionMethod2<int>();
var nonExistingMethod0 = ""string literal"".ExtensionMethodNotFound0();
var nonExistingMethod1 = ""string literal"".ExtensionMethodNotFound1<int>();
var nonExistingMethod2 = ""string literal"".ExtensionMethodNotFound2<int, string>();
System.Func<object> delegateConversion0 = ""string literal"".ExtensionMethod0<>;
System.Func<object> delegateConversion1 = ""string literal"".ExtensionMethod1<>;
System.Func<object> delegateConversion2 = ""string literal"".ExtensionMethod2<>;
var exactArgs0 = ""string literal"".ExtensionMethod0();
var exactArgs1 = ""string literal"".ExtensionMethod1<int>();
var exactArgs2 = ""string literal"".ExtensionMethod2<int, bool>();
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (13,27): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArg0 = "string literal".ExtensionMethod0<>();
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(13, 27),
// (13,44): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArg0 = "string literal".ExtensionMethod0<>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(13, 44),
// (14,27): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArg1 = "string literal".ExtensionMethod1<>();
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(14, 27),
// (15,27): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArg2 = "string literal".ExtensionMethod2<>();
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(15, 27),
// (15,44): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArg2 = "string literal".ExtensionMethod2<>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(15, 44),
// (17,31): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArgFunc0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(17, 31),
// (17,48): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArgFunc0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(17, 48),
// (18,31): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArgFunc1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(18, 31),
// (19,31): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArgFunc2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(19, 31),
// (19,48): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArgFunc2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(19, 48),
// (21,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var moreArgs0 = "string literal".ExtensionMethod0<int>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<int>").WithArguments("string", "ExtensionMethod0").WithLocation(21, 42),
// (22,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod1' and no accessible extension method 'ExtensionMethod1' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var moreArgs1 = "string literal".ExtensionMethod1<int, bool>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod1<int, bool>").WithArguments("string", "ExtensionMethod1").WithLocation(22, 42),
// (23,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var moreArgs2 = "string literal".ExtensionMethod2<int, bool, string>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<int, bool, string>").WithArguments("string", "ExtensionMethod2").WithLocation(23, 42),
// (25,42): error CS0411: The type arguments for method 'FooExtensions.ExtensionMethod1<T>(object)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// var lessArgs1 = "string literal".ExtensionMethod1();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "ExtensionMethod1").WithArguments("FooExtensions.ExtensionMethod1<T>(object)").WithLocation(25, 42),
// (26,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var lessArgs2 = "string literal".ExtensionMethod2<int>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<int>").WithArguments("string", "ExtensionMethod2").WithLocation(26, 42),
// (28,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound0' and no accessible extension method 'ExtensionMethodNotFound0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var nonExistingMethod0 = "string literal".ExtensionMethodNotFound0();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound0").WithArguments("string", "ExtensionMethodNotFound0").WithLocation(28, 51),
// (29,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound1' and no accessible extension method 'ExtensionMethodNotFound1' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var nonExistingMethod1 = "string literal".ExtensionMethodNotFound1<int>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound1<int>").WithArguments("string", "ExtensionMethodNotFound1").WithLocation(29, 51),
// (30,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound2' and no accessible extension method 'ExtensionMethodNotFound2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var nonExistingMethod2 = "string literal".ExtensionMethodNotFound2<int, string>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound2<int, string>").WithArguments("string", "ExtensionMethodNotFound2").WithLocation(30, 51),
// (32,51): error CS8389: Omitting the type argument is not allowed in the current context
// System.Func<object> delegateConversion0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(32, 51),
// (32,68): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// System.Func<object> delegateConversion0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(32, 68),
// (33,51): error CS8389: Omitting the type argument is not allowed in the current context
// System.Func<object> delegateConversion1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(33, 51),
// (33,51): error CS0407: '? FooExtensions.ExtensionMethod1<?>(object)' has the wrong return type
// System.Func<object> delegateConversion1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_BadRetType, @"""string literal"".ExtensionMethod1<>").WithArguments("FooExtensions.ExtensionMethod1<?>(object)", "?").WithLocation(33, 51),
// (34,51): error CS8389: Omitting the type argument is not allowed in the current context
// System.Func<object> delegateConversion2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(34, 51),
// (34,68): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// System.Func<object> delegateConversion2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(34, 68));
}
[WorkItem(22757, "https://github.com/dotnet/roslyn/issues/22757")]
[Fact]
public void MethodGroupConversionNoReceiver()
{
var source =
@"using System;
using System.Collections.Generic;
class A
{
class B
{
void F()
{
IEnumerable<string> c = null;
c.S(G);
}
}
object G(string s)
{
return null;
}
}
static class E
{
internal static IEnumerable<U> S<T, U>(this IEnumerable<T> c, Func<T, U> f)
{
throw new NotImplementedException();
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (10,17): error CS0120: An object reference is required for the non-static field, method, or property 'A.G(string)'
// c.S(G);
Diagnostic(ErrorCode.ERR_ObjectRequired, "G").WithArguments("A.G(string)").WithLocation(10, 17));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "G").First();
var info = model.GetSymbolInfo(node);
Assert.Equal("System.Object A.G(System.String s)", info.Symbol.ToTestDisplayString());
}
[Fact]
public void BindingLambdaArguments_DuplicateNamedArguments()
{
var compilation = CreateCompilation(@"
using System;
class X
{
void M<T>(T arg1, Func<T, T> arg2)
{
}
void N()
{
M(arg1: 5, arg2: x => x, arg2: y => y);
}
}").VerifyDiagnostics(
// (10,34): error CS1740: Named argument 'arg2' cannot be specified multiple times
// M(arg1: 5, arg2: x => 0, arg2: y => 0);
Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "arg2").WithArguments("arg2").WithLocation(10, 34));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var lambda = tree.GetRoot().DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(s => s.Parameter.Identifier.Text == "x");
var typeInfo = model.GetTypeInfo(lambda.Body);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Workspaces/Core/Portable/FindSymbols/FindReferences/NoOpStreamingFindReferencesProgress.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Shared.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
/// <summary>
/// A does-nothing version of the <see cref="IStreamingFindReferencesProgress"/>. Useful for
/// clients that have no need to report progress as they work.
/// </summary>
internal class NoOpStreamingFindReferencesProgress : IStreamingFindReferencesProgress
{
public static readonly IStreamingFindReferencesProgress Instance =
new NoOpStreamingFindReferencesProgress();
public IStreamingProgressTracker ProgressTracker { get; } = new NoOpProgressTracker();
private NoOpStreamingFindReferencesProgress()
{
}
#pragma warning disable IDE0060 // Remove unused parameter
public static Task ReportProgressAsync(int current, int maximum) => Task.CompletedTask;
#pragma warning restore IDE0060 // Remove unused parameter
public ValueTask OnCompletedAsync(CancellationToken cancellationToken) => default;
public ValueTask OnStartedAsync(CancellationToken cancellationToken) => default;
public ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken) => default;
public ValueTask OnReferenceFoundAsync(SymbolGroup group, ISymbol symbol, ReferenceLocation location, CancellationToken cancellationToken) => default;
public ValueTask OnFindInDocumentStartedAsync(Document document, CancellationToken cancellationToken) => default;
public ValueTask OnFindInDocumentCompletedAsync(Document document, CancellationToken cancellationToken) => default;
private class NoOpProgressTracker : IStreamingProgressTracker
{
public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => default;
public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => default;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
/// <summary>
/// A does-nothing version of the <see cref="IStreamingFindReferencesProgress"/>. Useful for
/// clients that have no need to report progress as they work.
/// </summary>
internal class NoOpStreamingFindReferencesProgress : IStreamingFindReferencesProgress
{
public static readonly IStreamingFindReferencesProgress Instance =
new NoOpStreamingFindReferencesProgress();
public IStreamingProgressTracker ProgressTracker { get; } = new NoOpProgressTracker();
private NoOpStreamingFindReferencesProgress()
{
}
#pragma warning disable IDE0060 // Remove unused parameter
public static Task ReportProgressAsync(int current, int maximum) => Task.CompletedTask;
#pragma warning restore IDE0060 // Remove unused parameter
public ValueTask OnCompletedAsync(CancellationToken cancellationToken) => default;
public ValueTask OnStartedAsync(CancellationToken cancellationToken) => default;
public ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken) => default;
public ValueTask OnReferenceFoundAsync(SymbolGroup group, ISymbol symbol, ReferenceLocation location, CancellationToken cancellationToken) => default;
public ValueTask OnFindInDocumentStartedAsync(Document document, CancellationToken cancellationToken) => default;
public ValueTask OnFindInDocumentCompletedAsync(Document document, CancellationToken cancellationToken) => default;
private class NoOpProgressTracker : IStreamingProgressTracker
{
public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => default;
public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => default;
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/Core/Portable/Text/SourceTextStream.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// A read-only, non-seekable <see cref="Stream"/> over a <see cref="SourceText"/>.
/// </summary>
internal sealed class SourceTextStream : Stream
{
private readonly SourceText _source;
private readonly Encoding _encoding;
private readonly Encoder _encoder;
private readonly int _minimumTargetBufferCount;
private int _position;
private int _sourceOffset;
private readonly char[] _charBuffer;
private int _bufferOffset;
private int _bufferUnreadChars;
private bool _preambleWritten;
private static readonly Encoding s_utf8EncodingWithNoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false);
public SourceTextStream(SourceText source, int bufferSize = 2048, bool useDefaultEncodingIfNull = false)
{
Debug.Assert(source.Encoding != null || useDefaultEncodingIfNull);
_source = source;
_encoding = source.Encoding ?? s_utf8EncodingWithNoBOM;
_encoder = _encoding.GetEncoder();
_minimumTargetBufferCount = _encoding.GetMaxByteCount(charCount: 1);
_sourceOffset = 0;
_position = 0;
_charBuffer = new char[Math.Min(bufferSize, _source.Length)];
_bufferOffset = 0;
_bufferUnreadChars = 0;
_preambleWritten = false;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
throw new NotSupportedException();
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { return _position; }
set { throw new NotSupportedException(); }
}
public override int Read(byte[] buffer, int offset, int count)
{
if (count < _minimumTargetBufferCount)
{
// The buffer must be able to hold at least one character from the
// SourceText stream. Returning 0 for that case isn't correct because
// that indicates end of stream vs. insufficient buffer.
throw new ArgumentException($"{nameof(count)} must be greater than or equal to {_minimumTargetBufferCount}", nameof(count));
}
int originalCount = count;
if (!_preambleWritten)
{
int bytesWritten = WritePreamble(buffer, offset, count);
offset += bytesWritten;
count -= bytesWritten;
}
while (count >= _minimumTargetBufferCount && _position < _source.Length)
{
if (_bufferUnreadChars == 0)
{
FillBuffer();
}
int charsUsed, bytesUsed;
bool ignored;
_encoder.Convert(_charBuffer, _bufferOffset, _bufferUnreadChars, buffer, offset, count, flush: false, charsUsed: out charsUsed, bytesUsed: out bytesUsed, completed: out ignored);
_position += charsUsed;
_bufferOffset += charsUsed;
_bufferUnreadChars -= charsUsed;
offset += bytesUsed;
count -= bytesUsed;
}
// Return value is the number of bytes read
return originalCount - count;
}
private int WritePreamble(byte[] buffer, int offset, int count)
{
_preambleWritten = true;
byte[] preambleBytes = _encoding.GetPreamble();
if (preambleBytes == null)
{
return 0;
}
int length = Math.Min(count, preambleBytes.Length);
Array.Copy(preambleBytes, 0, buffer, offset, length);
return length;
}
private void FillBuffer()
{
int charsToRead = Math.Min(_charBuffer.Length, _source.Length - _sourceOffset);
_source.CopyTo(_sourceOffset, _charBuffer, 0, charsToRead);
_sourceOffset += charsToRead;
_bufferOffset = 0;
_bufferUnreadChars = charsToRead;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// A read-only, non-seekable <see cref="Stream"/> over a <see cref="SourceText"/>.
/// </summary>
internal sealed class SourceTextStream : Stream
{
private readonly SourceText _source;
private readonly Encoding _encoding;
private readonly Encoder _encoder;
private readonly int _minimumTargetBufferCount;
private int _position;
private int _sourceOffset;
private readonly char[] _charBuffer;
private int _bufferOffset;
private int _bufferUnreadChars;
private bool _preambleWritten;
private static readonly Encoding s_utf8EncodingWithNoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false);
public SourceTextStream(SourceText source, int bufferSize = 2048, bool useDefaultEncodingIfNull = false)
{
Debug.Assert(source.Encoding != null || useDefaultEncodingIfNull);
_source = source;
_encoding = source.Encoding ?? s_utf8EncodingWithNoBOM;
_encoder = _encoding.GetEncoder();
_minimumTargetBufferCount = _encoding.GetMaxByteCount(charCount: 1);
_sourceOffset = 0;
_position = 0;
_charBuffer = new char[Math.Min(bufferSize, _source.Length)];
_bufferOffset = 0;
_bufferUnreadChars = 0;
_preambleWritten = false;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
throw new NotSupportedException();
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { return _position; }
set { throw new NotSupportedException(); }
}
public override int Read(byte[] buffer, int offset, int count)
{
if (count < _minimumTargetBufferCount)
{
// The buffer must be able to hold at least one character from the
// SourceText stream. Returning 0 for that case isn't correct because
// that indicates end of stream vs. insufficient buffer.
throw new ArgumentException($"{nameof(count)} must be greater than or equal to {_minimumTargetBufferCount}", nameof(count));
}
int originalCount = count;
if (!_preambleWritten)
{
int bytesWritten = WritePreamble(buffer, offset, count);
offset += bytesWritten;
count -= bytesWritten;
}
while (count >= _minimumTargetBufferCount && _position < _source.Length)
{
if (_bufferUnreadChars == 0)
{
FillBuffer();
}
int charsUsed, bytesUsed;
bool ignored;
_encoder.Convert(_charBuffer, _bufferOffset, _bufferUnreadChars, buffer, offset, count, flush: false, charsUsed: out charsUsed, bytesUsed: out bytesUsed, completed: out ignored);
_position += charsUsed;
_bufferOffset += charsUsed;
_bufferUnreadChars -= charsUsed;
offset += bytesUsed;
count -= bytesUsed;
}
// Return value is the number of bytes read
return originalCount - count;
}
private int WritePreamble(byte[] buffer, int offset, int count)
{
_preambleWritten = true;
byte[] preambleBytes = _encoding.GetPreamble();
if (preambleBytes == null)
{
return 0;
}
int length = Math.Min(count, preambleBytes.Length);
Array.Copy(preambleBytes, 0, buffer, offset, length);
return length;
}
private void FillBuffer()
{
int charsToRead = Math.Min(_charBuffer.Length, _source.Length - _sourceOffset);
_source.CopyTo(_sourceOffset, _charBuffer, 0, charsToRead);
_sourceOffset += charsToRead;
_bufferOffset = 0;
_bufferUnreadChars = charsToRead;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Features/Core/Portable/ExtractMethod/AbstractSyntaxTriviaService.Result.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal abstract partial class AbstractSyntaxTriviaService
{
private class Result : ITriviaSavedResult
{
private static readonly AnnotationResolver s_defaultAnnotationResolver = ResolveAnnotation;
private static readonly TriviaResolver s_defaultTriviaResolver = ResolveTrivia;
private readonly SyntaxNode _root;
private readonly int _endOfLineKind;
private readonly Dictionary<TriviaLocation, SyntaxAnnotation> _annotations;
private readonly Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> _triviaList;
public Result(
SyntaxNode root,
int endOfLineKind,
Dictionary<TriviaLocation, SyntaxAnnotation> annotations,
Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> triviaList)
{
Contract.ThrowIfNull(root);
Contract.ThrowIfNull(annotations);
Contract.ThrowIfNull(triviaList);
_root = root;
_endOfLineKind = endOfLineKind;
_annotations = annotations;
_triviaList = triviaList;
}
public SyntaxNode Root => _root;
public SyntaxNode RestoreTrivia(
SyntaxNode root,
AnnotationResolver annotationResolver = null,
TriviaResolver triviaResolver = null)
{
var tokens = RecoverTokensAtEdges(root, annotationResolver);
var map = CreateOldToNewTokensMap(tokens, triviaResolver);
return root.ReplaceTokens(map.Keys, (o, n) => map[o]);
}
private static Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap(
Dictionary<TriviaLocation, PreviousNextTokenPair> tokenPairs,
Dictionary<TriviaLocation, LeadingTrailingTriviaPair> triviaPairs)
{
var map = new Dictionary<SyntaxToken, SyntaxToken>();
foreach (var pair in CreateUniqueTokenTriviaPairs(tokenPairs, triviaPairs))
{
var localCopy = pair;
var previousToken = map.GetOrAdd(localCopy.Item1.PreviousToken, _ => localCopy.Item1.PreviousToken);
map[localCopy.Item1.PreviousToken] = previousToken.WithTrailingTrivia(localCopy.Item2.TrailingTrivia);
var nextToken = map.GetOrAdd(localCopy.Item1.NextToken, _ => localCopy.Item1.NextToken);
map[localCopy.Item1.NextToken] = nextToken.WithLeadingTrivia(localCopy.Item2.LeadingTrivia);
}
return map;
}
private LeadingTrailingTriviaPair GetTrailingAndLeadingTrivia(IEnumerable<SyntaxTrivia> trivia)
{
var list = trivia.ToList();
// there are some noisy trivia
var index = GetFirstEndOfLineIndex(list);
return new LeadingTrailingTriviaPair
{
TrailingTrivia = CreateTriviaListFromTo(list, 0, index),
LeadingTrivia = CreateTriviaListFromTo(list, index + 1, list.Count - 1)
};
}
private int GetFirstEndOfLineIndex(List<SyntaxTrivia> list)
{
for (var i = 0; i < list.Count; i++)
{
if (list[i].RawKind == _endOfLineKind)
{
return i;
}
}
return list.Count - 1;
}
private Dictionary<TriviaLocation, SyntaxToken> RecoverTokensAtEdges(
SyntaxNode root,
AnnotationResolver annotationResolver)
{
var resolver = annotationResolver ?? s_defaultAnnotationResolver;
var tokens = Enumerable.Range((int)TriviaLocation.BeforeBeginningOfSpan, TriviaLocationsCount)
.Cast<TriviaLocation>()
.ToDictionary(
location => location,
location => resolver(root, location, _annotations[location]));
Contract.ThrowIfFalse(
tokens[TriviaLocation.AfterBeginningOfSpan].RawKind == 0 /* don't care */ ||
tokens[TriviaLocation.BeforeEndOfSpan].RawKind == 0 /* don't care */ ||
tokens[TriviaLocation.AfterBeginningOfSpan] == tokens[TriviaLocation.BeforeEndOfSpan] ||
tokens[TriviaLocation.AfterBeginningOfSpan].GetPreviousToken(includeZeroWidth: true) == tokens[TriviaLocation.BeforeEndOfSpan] ||
tokens[TriviaLocation.AfterBeginningOfSpan].Span.End <= tokens[TriviaLocation.BeforeEndOfSpan].SpanStart);
return tokens;
}
private Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap(
Dictionary<TriviaLocation, SyntaxToken> tokens,
TriviaResolver triviaResolver)
{
var tokenPairs = CreatePreviousNextTokenPairs(tokens);
var tokenToLeadingTrailingTriviaMap = CreateTokenLeadingTrailingTriviaMap(tokens);
var resolver = triviaResolver ?? s_defaultTriviaResolver;
var triviaPairs = Enumerable.Range((int)TriviaLocation.BeforeBeginningOfSpan, TriviaLocationsCount)
.Cast<TriviaLocation>()
.ToDictionary(
location => location,
location => CreateTriviaPairs(
tokenPairs[location],
resolver(location, tokenPairs[location], tokenToLeadingTrailingTriviaMap)));
return CreateOldToNewTokensMap(tokenPairs, triviaPairs);
}
private LeadingTrailingTriviaPair CreateTriviaPairs(
PreviousNextTokenPair tokenPair,
IEnumerable<SyntaxTrivia> trivia)
{
// beginning of the tree
if (tokenPair.PreviousToken.RawKind == 0)
{
return new LeadingTrailingTriviaPair { TrailingTrivia = SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(), LeadingTrivia = trivia };
}
return GetTrailingAndLeadingTrivia(trivia);
}
private static IEnumerable<Tuple<PreviousNextTokenPair, LeadingTrailingTriviaPair>> CreateUniqueTokenTriviaPairs(
Dictionary<TriviaLocation, PreviousNextTokenPair> tokenPairs,
Dictionary<TriviaLocation, LeadingTrailingTriviaPair> triviaPairs)
{
// if there are dup, duplicated one will be ignored.
var set = new HashSet<PreviousNextTokenPair>();
for (var i = (int)TriviaLocation.BeforeBeginningOfSpan; i <= (int)TriviaLocation.AfterEndOfSpan; i++)
{
var location = (TriviaLocation)i;
var key = tokenPairs[location];
if (set.Contains(key))
{
continue;
}
yield return Tuple.Create(key, triviaPairs[location]);
set.Add(key);
}
}
private Dictionary<SyntaxToken, LeadingTrailingTriviaPair> CreateTokenLeadingTrailingTriviaMap(
Dictionary<TriviaLocation, SyntaxToken> tokens)
{
var tuple = default(LeadingTrailingTriviaPair);
var map = new Dictionary<SyntaxToken, LeadingTrailingTriviaPair>();
tuple = map.GetOrAdd(tokens[TriviaLocation.BeforeBeginningOfSpan], _ => default);
map[tokens[TriviaLocation.BeforeBeginningOfSpan]] = new LeadingTrailingTriviaPair
{
LeadingTrivia = tuple.LeadingTrivia,
TrailingTrivia = _triviaList[TriviaLocation.BeforeBeginningOfSpan]
};
tuple = map.GetOrAdd(tokens[TriviaLocation.AfterBeginningOfSpan], _ => default);
map[tokens[TriviaLocation.AfterBeginningOfSpan]] = new LeadingTrailingTriviaPair
{
LeadingTrivia = _triviaList[TriviaLocation.AfterBeginningOfSpan],
TrailingTrivia = tuple.TrailingTrivia
};
tuple = map.GetOrAdd(tokens[TriviaLocation.BeforeEndOfSpan], _ => default);
map[tokens[TriviaLocation.BeforeEndOfSpan]] = new LeadingTrailingTriviaPair
{
LeadingTrivia = tuple.LeadingTrivia,
TrailingTrivia = _triviaList[TriviaLocation.BeforeEndOfSpan]
};
tuple = map.GetOrAdd(tokens[TriviaLocation.AfterEndOfSpan], _ => default);
map[tokens[TriviaLocation.AfterEndOfSpan]] = new LeadingTrailingTriviaPair
{
LeadingTrivia = _triviaList[TriviaLocation.AfterEndOfSpan],
TrailingTrivia = tuple.TrailingTrivia
};
return map;
}
private static Dictionary<TriviaLocation, PreviousNextTokenPair> CreatePreviousNextTokenPairs(
Dictionary<TriviaLocation, SyntaxToken> tokens)
{
var tokenPairs = new Dictionary<TriviaLocation, PreviousNextTokenPair>();
tokenPairs[TriviaLocation.BeforeBeginningOfSpan] = new PreviousNextTokenPair
{
PreviousToken = tokens[TriviaLocation.BeforeBeginningOfSpan],
NextToken = tokens[TriviaLocation.BeforeBeginningOfSpan].GetNextToken(includeZeroWidth: true)
};
tokenPairs[TriviaLocation.AfterBeginningOfSpan] = new PreviousNextTokenPair
{
PreviousToken = tokens[TriviaLocation.AfterBeginningOfSpan].GetPreviousToken(includeZeroWidth: true),
NextToken = tokens[TriviaLocation.AfterBeginningOfSpan]
};
tokenPairs[TriviaLocation.BeforeEndOfSpan] = new PreviousNextTokenPair
{
PreviousToken = tokens[TriviaLocation.BeforeEndOfSpan],
NextToken = tokens[TriviaLocation.BeforeEndOfSpan].GetNextToken(includeZeroWidth: true)
};
tokenPairs[TriviaLocation.AfterEndOfSpan] = new PreviousNextTokenPair
{
PreviousToken = tokens[TriviaLocation.AfterEndOfSpan].GetPreviousToken(includeZeroWidth: true),
NextToken = tokens[TriviaLocation.AfterEndOfSpan]
};
return tokenPairs;
}
private static IEnumerable<SyntaxTrivia> CreateTriviaListFromTo(
List<SyntaxTrivia> list,
int startIndex,
int endIndex)
{
if (startIndex > endIndex)
{
yield break;
}
for (var i = startIndex; i <= endIndex; i++)
{
yield return list[i];
}
}
private static SyntaxToken ResolveAnnotation(
SyntaxNode root,
TriviaLocation location,
SyntaxAnnotation annotation)
{
return root.GetAnnotatedNodesAndTokens(annotation).FirstOrDefault().AsToken();
}
private static IEnumerable<SyntaxTrivia> ResolveTrivia(
TriviaLocation location,
PreviousNextTokenPair tokenPair,
Dictionary<SyntaxToken, LeadingTrailingTriviaPair> triviaMap)
{
var previousTriviaPair = triviaMap.ContainsKey(tokenPair.PreviousToken) ? triviaMap[tokenPair.PreviousToken] : default;
var nextTriviaPair = triviaMap.ContainsKey(tokenPair.NextToken) ? triviaMap[tokenPair.NextToken] : default;
var trailingTrivia = previousTriviaPair.TrailingTrivia ?? SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
var leadingTrivia = nextTriviaPair.LeadingTrivia ?? SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
return tokenPair.PreviousToken.TrailingTrivia.Concat(trailingTrivia).Concat(leadingTrivia).Concat(tokenPair.NextToken.LeadingTrivia);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal abstract partial class AbstractSyntaxTriviaService
{
private class Result : ITriviaSavedResult
{
private static readonly AnnotationResolver s_defaultAnnotationResolver = ResolveAnnotation;
private static readonly TriviaResolver s_defaultTriviaResolver = ResolveTrivia;
private readonly SyntaxNode _root;
private readonly int _endOfLineKind;
private readonly Dictionary<TriviaLocation, SyntaxAnnotation> _annotations;
private readonly Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> _triviaList;
public Result(
SyntaxNode root,
int endOfLineKind,
Dictionary<TriviaLocation, SyntaxAnnotation> annotations,
Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> triviaList)
{
Contract.ThrowIfNull(root);
Contract.ThrowIfNull(annotations);
Contract.ThrowIfNull(triviaList);
_root = root;
_endOfLineKind = endOfLineKind;
_annotations = annotations;
_triviaList = triviaList;
}
public SyntaxNode Root => _root;
public SyntaxNode RestoreTrivia(
SyntaxNode root,
AnnotationResolver annotationResolver = null,
TriviaResolver triviaResolver = null)
{
var tokens = RecoverTokensAtEdges(root, annotationResolver);
var map = CreateOldToNewTokensMap(tokens, triviaResolver);
return root.ReplaceTokens(map.Keys, (o, n) => map[o]);
}
private static Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap(
Dictionary<TriviaLocation, PreviousNextTokenPair> tokenPairs,
Dictionary<TriviaLocation, LeadingTrailingTriviaPair> triviaPairs)
{
var map = new Dictionary<SyntaxToken, SyntaxToken>();
foreach (var pair in CreateUniqueTokenTriviaPairs(tokenPairs, triviaPairs))
{
var localCopy = pair;
var previousToken = map.GetOrAdd(localCopy.Item1.PreviousToken, _ => localCopy.Item1.PreviousToken);
map[localCopy.Item1.PreviousToken] = previousToken.WithTrailingTrivia(localCopy.Item2.TrailingTrivia);
var nextToken = map.GetOrAdd(localCopy.Item1.NextToken, _ => localCopy.Item1.NextToken);
map[localCopy.Item1.NextToken] = nextToken.WithLeadingTrivia(localCopy.Item2.LeadingTrivia);
}
return map;
}
private LeadingTrailingTriviaPair GetTrailingAndLeadingTrivia(IEnumerable<SyntaxTrivia> trivia)
{
var list = trivia.ToList();
// there are some noisy trivia
var index = GetFirstEndOfLineIndex(list);
return new LeadingTrailingTriviaPair
{
TrailingTrivia = CreateTriviaListFromTo(list, 0, index),
LeadingTrivia = CreateTriviaListFromTo(list, index + 1, list.Count - 1)
};
}
private int GetFirstEndOfLineIndex(List<SyntaxTrivia> list)
{
for (var i = 0; i < list.Count; i++)
{
if (list[i].RawKind == _endOfLineKind)
{
return i;
}
}
return list.Count - 1;
}
private Dictionary<TriviaLocation, SyntaxToken> RecoverTokensAtEdges(
SyntaxNode root,
AnnotationResolver annotationResolver)
{
var resolver = annotationResolver ?? s_defaultAnnotationResolver;
var tokens = Enumerable.Range((int)TriviaLocation.BeforeBeginningOfSpan, TriviaLocationsCount)
.Cast<TriviaLocation>()
.ToDictionary(
location => location,
location => resolver(root, location, _annotations[location]));
Contract.ThrowIfFalse(
tokens[TriviaLocation.AfterBeginningOfSpan].RawKind == 0 /* don't care */ ||
tokens[TriviaLocation.BeforeEndOfSpan].RawKind == 0 /* don't care */ ||
tokens[TriviaLocation.AfterBeginningOfSpan] == tokens[TriviaLocation.BeforeEndOfSpan] ||
tokens[TriviaLocation.AfterBeginningOfSpan].GetPreviousToken(includeZeroWidth: true) == tokens[TriviaLocation.BeforeEndOfSpan] ||
tokens[TriviaLocation.AfterBeginningOfSpan].Span.End <= tokens[TriviaLocation.BeforeEndOfSpan].SpanStart);
return tokens;
}
private Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap(
Dictionary<TriviaLocation, SyntaxToken> tokens,
TriviaResolver triviaResolver)
{
var tokenPairs = CreatePreviousNextTokenPairs(tokens);
var tokenToLeadingTrailingTriviaMap = CreateTokenLeadingTrailingTriviaMap(tokens);
var resolver = triviaResolver ?? s_defaultTriviaResolver;
var triviaPairs = Enumerable.Range((int)TriviaLocation.BeforeBeginningOfSpan, TriviaLocationsCount)
.Cast<TriviaLocation>()
.ToDictionary(
location => location,
location => CreateTriviaPairs(
tokenPairs[location],
resolver(location, tokenPairs[location], tokenToLeadingTrailingTriviaMap)));
return CreateOldToNewTokensMap(tokenPairs, triviaPairs);
}
private LeadingTrailingTriviaPair CreateTriviaPairs(
PreviousNextTokenPair tokenPair,
IEnumerable<SyntaxTrivia> trivia)
{
// beginning of the tree
if (tokenPair.PreviousToken.RawKind == 0)
{
return new LeadingTrailingTriviaPair { TrailingTrivia = SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(), LeadingTrivia = trivia };
}
return GetTrailingAndLeadingTrivia(trivia);
}
private static IEnumerable<Tuple<PreviousNextTokenPair, LeadingTrailingTriviaPair>> CreateUniqueTokenTriviaPairs(
Dictionary<TriviaLocation, PreviousNextTokenPair> tokenPairs,
Dictionary<TriviaLocation, LeadingTrailingTriviaPair> triviaPairs)
{
// if there are dup, duplicated one will be ignored.
var set = new HashSet<PreviousNextTokenPair>();
for (var i = (int)TriviaLocation.BeforeBeginningOfSpan; i <= (int)TriviaLocation.AfterEndOfSpan; i++)
{
var location = (TriviaLocation)i;
var key = tokenPairs[location];
if (set.Contains(key))
{
continue;
}
yield return Tuple.Create(key, triviaPairs[location]);
set.Add(key);
}
}
private Dictionary<SyntaxToken, LeadingTrailingTriviaPair> CreateTokenLeadingTrailingTriviaMap(
Dictionary<TriviaLocation, SyntaxToken> tokens)
{
var tuple = default(LeadingTrailingTriviaPair);
var map = new Dictionary<SyntaxToken, LeadingTrailingTriviaPair>();
tuple = map.GetOrAdd(tokens[TriviaLocation.BeforeBeginningOfSpan], _ => default);
map[tokens[TriviaLocation.BeforeBeginningOfSpan]] = new LeadingTrailingTriviaPair
{
LeadingTrivia = tuple.LeadingTrivia,
TrailingTrivia = _triviaList[TriviaLocation.BeforeBeginningOfSpan]
};
tuple = map.GetOrAdd(tokens[TriviaLocation.AfterBeginningOfSpan], _ => default);
map[tokens[TriviaLocation.AfterBeginningOfSpan]] = new LeadingTrailingTriviaPair
{
LeadingTrivia = _triviaList[TriviaLocation.AfterBeginningOfSpan],
TrailingTrivia = tuple.TrailingTrivia
};
tuple = map.GetOrAdd(tokens[TriviaLocation.BeforeEndOfSpan], _ => default);
map[tokens[TriviaLocation.BeforeEndOfSpan]] = new LeadingTrailingTriviaPair
{
LeadingTrivia = tuple.LeadingTrivia,
TrailingTrivia = _triviaList[TriviaLocation.BeforeEndOfSpan]
};
tuple = map.GetOrAdd(tokens[TriviaLocation.AfterEndOfSpan], _ => default);
map[tokens[TriviaLocation.AfterEndOfSpan]] = new LeadingTrailingTriviaPair
{
LeadingTrivia = _triviaList[TriviaLocation.AfterEndOfSpan],
TrailingTrivia = tuple.TrailingTrivia
};
return map;
}
private static Dictionary<TriviaLocation, PreviousNextTokenPair> CreatePreviousNextTokenPairs(
Dictionary<TriviaLocation, SyntaxToken> tokens)
{
var tokenPairs = new Dictionary<TriviaLocation, PreviousNextTokenPair>();
tokenPairs[TriviaLocation.BeforeBeginningOfSpan] = new PreviousNextTokenPair
{
PreviousToken = tokens[TriviaLocation.BeforeBeginningOfSpan],
NextToken = tokens[TriviaLocation.BeforeBeginningOfSpan].GetNextToken(includeZeroWidth: true)
};
tokenPairs[TriviaLocation.AfterBeginningOfSpan] = new PreviousNextTokenPair
{
PreviousToken = tokens[TriviaLocation.AfterBeginningOfSpan].GetPreviousToken(includeZeroWidth: true),
NextToken = tokens[TriviaLocation.AfterBeginningOfSpan]
};
tokenPairs[TriviaLocation.BeforeEndOfSpan] = new PreviousNextTokenPair
{
PreviousToken = tokens[TriviaLocation.BeforeEndOfSpan],
NextToken = tokens[TriviaLocation.BeforeEndOfSpan].GetNextToken(includeZeroWidth: true)
};
tokenPairs[TriviaLocation.AfterEndOfSpan] = new PreviousNextTokenPair
{
PreviousToken = tokens[TriviaLocation.AfterEndOfSpan].GetPreviousToken(includeZeroWidth: true),
NextToken = tokens[TriviaLocation.AfterEndOfSpan]
};
return tokenPairs;
}
private static IEnumerable<SyntaxTrivia> CreateTriviaListFromTo(
List<SyntaxTrivia> list,
int startIndex,
int endIndex)
{
if (startIndex > endIndex)
{
yield break;
}
for (var i = startIndex; i <= endIndex; i++)
{
yield return list[i];
}
}
private static SyntaxToken ResolveAnnotation(
SyntaxNode root,
TriviaLocation location,
SyntaxAnnotation annotation)
{
return root.GetAnnotatedNodesAndTokens(annotation).FirstOrDefault().AsToken();
}
private static IEnumerable<SyntaxTrivia> ResolveTrivia(
TriviaLocation location,
PreviousNextTokenPair tokenPair,
Dictionary<SyntaxToken, LeadingTrailingTriviaPair> triviaMap)
{
var previousTriviaPair = triviaMap.ContainsKey(tokenPair.PreviousToken) ? triviaMap[tokenPair.PreviousToken] : default;
var nextTriviaPair = triviaMap.ContainsKey(tokenPair.NextToken) ? triviaMap[tokenPair.NextToken] : default;
var trailingTrivia = previousTriviaPair.TrailingTrivia ?? SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
var leadingTrivia = nextTriviaPair.LeadingTrivia ?? SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
return tokenPair.PreviousToken.TrailingTrivia.Concat(trailingTrivia).Concat(leadingTrivia).Concat(tokenPair.NextToken.LeadingTrivia);
}
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/CSharp/Test/Semantic/Semantics/ImplicitObjectCreationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class ImplicitObjectCreationTests : CSharpTestBase
{
private static readonly CSharpParseOptions ImplicitObjectCreationTestOptions = TestOptions.Regular9;
private static CSharpCompilation CreateCompilation(string source, CSharpCompilationOptions options = null, IEnumerable<MetadataReference> references = null)
{
return CSharpTestBase.CreateCompilation(source, options: options, parseOptions: ImplicitObjectCreationTestOptions, references: references);
}
[Fact]
public void TestInLocal()
{
var source = @"
using System;
struct S
{
}
class C
{
public static void Main()
{
C v1 = new();
S v2 = new();
S? v3 = new();
Console.Write(v1);
Console.Write(v2);
Console.Write(v3);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CSS");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
assert(0, type: "C", convertedType: "C", symbol: "C..ctor()", ConversionKind.Identity);
assert(1, type: "S", convertedType: "S", symbol: "S..ctor()", ConversionKind.Identity);
assert(2, type: "S", convertedType: "S?", symbol: "S..ctor()", ConversionKind.ImplicitNullable);
void assert(int index, string type, string convertedType, string symbol, ConversionKind conversionKind)
{
var @new = nodes[index];
Assert.Equal(type, model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal(symbol, model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(conversionKind, model.GetConversion(@new).Kind);
}
}
[Fact]
public void TestInLocal_LangVersion8()
{
var source = @"
struct S
{
}
class C
{
public static void Main()
{
C v1 = new();
S v2 = new();
S? v3 = new();
C v4 = new(missing);
S v5 = new(missing);
S? v6 = new(missing);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (10,16): error CS8400: Feature 'target-typed object creation' is not available in C# 8.0. Please use language version 9.0 or greater.
// C v1 = new();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new").WithArguments("target-typed object creation", "9.0").WithLocation(10, 16),
// (11,16): error CS8400: Feature 'target-typed object creation' is not available in C# 8.0. Please use language version 9.0 or greater.
// S v2 = new();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new").WithArguments("target-typed object creation", "9.0").WithLocation(11, 16),
// (12,17): error CS8400: Feature 'target-typed object creation' is not available in C# 8.0. Please use language version 9.0 or greater.
// S? v3 = new();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new").WithArguments("target-typed object creation", "9.0").WithLocation(12, 17),
// (13,16): error CS8400: Feature 'target-typed object creation' is not available in C# 8.0. Please use language version 9.0 or greater.
// C v4 = new(missing);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new").WithArguments("target-typed object creation", "9.0").WithLocation(13, 16),
// (13,20): error CS0103: The name 'missing' does not exist in the current context
// C v4 = new(missing);
Diagnostic(ErrorCode.ERR_NameNotInContext, "missing").WithArguments("missing").WithLocation(13, 20),
// (14,16): error CS8400: Feature 'target-typed object creation' is not available in C# 8.0. Please use language version 9.0 or greater.
// S v5 = new(missing);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new").WithArguments("target-typed object creation", "9.0").WithLocation(14, 16),
// (14,20): error CS0103: The name 'missing' does not exist in the current context
// S v5 = new(missing);
Diagnostic(ErrorCode.ERR_NameNotInContext, "missing").WithArguments("missing").WithLocation(14, 20),
// (15,17): error CS8400: Feature 'target-typed object creation' is not available in C# 8.0. Please use language version 9.0 or greater.
// S? v6 = new(missing);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new").WithArguments("target-typed object creation", "9.0").WithLocation(15, 17),
// (15,21): error CS0103: The name 'missing' does not exist in the current context
// S? v6 = new(missing);
Diagnostic(ErrorCode.ERR_NameNotInContext, "missing").WithArguments("missing").WithLocation(15, 21)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
assert(0, type: "C", convertedType: "C", symbol: "C..ctor()", ConversionKind.Identity);
assert(1, type: "S", convertedType: "S", symbol: "S..ctor()", ConversionKind.Identity);
assert(2, type: "S", convertedType: "S?", symbol: "S..ctor()", ConversionKind.ImplicitNullable);
void assert(int index, string type, string convertedType, string symbol, ConversionKind conversionKind)
{
var @new = nodes[index];
Assert.Equal(type, model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal(symbol, model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(conversionKind, model.GetConversion(@new).Kind);
}
}
[Fact]
public void TestInExpressionTree()
{
var source = @"
using System;
using System.Linq.Expressions;
struct S
{
}
class C
{
public static void Main()
{
Expression<Func<C>> expr1 = () => new();
Expression<Func<S>> expr2 = () => new();
Expression<Func<S?>> expr3 = () => new();
Console.Write(expr1.Compile()());
Console.Write(expr2.Compile()());
Console.Write(expr3.Compile()());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CSS");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
assert(0, type: "C", convertedType: "C", symbol: "C..ctor()", ConversionKind.Identity);
assert(1, type: "S", convertedType: "S", symbol: "S..ctor()", ConversionKind.Identity);
assert(2, type: "S", convertedType: "S?", symbol: "S..ctor()", ConversionKind.ImplicitNullable);
void assert(int index, string type, string convertedType, string symbol, ConversionKind conversionKind)
{
var @new = nodes[index];
Assert.Equal(type, model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal(symbol, model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(conversionKind, model.GetConversion(@new).Kind);
}
}
[Fact]
public void TestInParameterDefaultValue()
{
var source = @"
struct S
{
}
class C
{
void M(
C p1 = new(),
S p2 = new(), // ok
S? p3 = new(),
int p4 = new(), // ok
bool? p5 = new() // ok
)
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,16): error CS1736: Default parameter value for 'p1' must be a compile-time constant
// C p1 = new(),
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new()").WithArguments("p1").WithLocation(9, 16),
// (11,17): error CS1736: Default parameter value for 'p3' must be a compile-time constant
// S? p3 = new()
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new()").WithArguments("p3").WithLocation(11, 17)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
assert(0, type: "C", convertedType: "C", symbol: "C..ctor()", constant: null, ConversionKind.Identity);
assert(1, type: "S", convertedType: "S", symbol: "S..ctor()", constant: null, ConversionKind.Identity);
assert(2, type: "S", convertedType: "S?", symbol: "S..ctor()", constant: null, ConversionKind.ImplicitNullable);
assert(3, type: "System.Int32", convertedType: "System.Int32", symbol: "System.Int32..ctor()", constant: "0", ConversionKind.Identity);
assert(4, type: "System.Boolean", convertedType: "System.Boolean?", symbol: "System.Boolean..ctor()", constant: "False", ConversionKind.ImplicitNullable);
void assert(int index, string type, string convertedType, string symbol, string constant, ConversionKind conversionKind)
{
var @new = nodes[index];
Assert.Equal(type, model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal(symbol, model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(conversionKind, model.GetConversion(@new).Kind);
Assert.Equal(constant, model.GetConstantValue(@new).Value?.ToString());
}
}
[Fact]
public void TestArguments_Out()
{
var source = @"
using System;
class C
{
public int j;
public C(out int i)
{
i = 2;
}
public static void Main()
{
C c = new(out var i) { j = i };
Console.Write(c.j);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "2");
}
[Fact]
public void TestArguments_Params()
{
var source = @"
using System;
class C
{
public C(params int[] p)
{
foreach (var item in p)
{
Console.Write(item);
}
}
public static void Main()
{
C c = new(1, 2, 3);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "123");
}
[Fact]
public void TestArguments_NonTrailingNamedArgs()
{
var source = @"
using System;
class C
{
public C(object c, object o) => Console.Write(1);
public C(int i, object o) => Console.Write(2);
public static void Main()
{
C c = new(c: new(), 2);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "1");
}
[Fact]
public void TestArguments_DynamicArgs()
{
var source = @"
using System;
class C
{
readonly int field;
public C(int field)
{
this.field = field;
}
public C(dynamic c)
{
Console.Write(c.field);
}
public static void Main()
{
dynamic d = 5;
C c = new(new C(d));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe, references: new[] { CSharpRef });
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "5");
}
[Fact]
public void TestInDynamicInvocation()
{
var source = @"
class C
{
public void M(int i) {}
public static void Main()
{
dynamic d = new C();
d.M(new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe, references: new[] { CSharpRef });
comp.VerifyDiagnostics(
// (9,13): error CS8754: There is no target type for 'new()'
// d.M(new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(9, 13)
);
}
[Fact]
public void TestInAsOperator()
{
var source = @"
using System;
struct S
{
}
class C
{
public void M<TClass, TNew>()
where TClass : class
where TNew : new()
{
Console.Write(new() as C);
Console.Write(new() as S?);
Console.Write(new() as TClass);
Console.Write(new() as TNew);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (14,23): error CS8754: There is no target type for 'new()'
// Console.Write(new() as C);
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(14, 23),
// (15,23): error CS8754: There is no target type for 'new()'
// Console.Write(new() as S?);
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(15, 23),
// (16,23): error CS8754: There is no target type for 'new()'
// Console.Write(new() as TClass);
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(16, 23),
// (17,23): error CS8754: There is no target type for 'new()'
// Console.Write(new() as TNew);
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(17, 23)
);
}
[Fact]
public void TestInTupleElement()
{
var source = @"
using System;
class C
{
static void M<T>((T a, T b) t, T c) => Console.Write(t);
public static void Main()
{
M((new(), new()), new C());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "(C, C)");
}
[Fact]
public void TestTargetType_Var()
{
var source = @"
class C
{
void M()
{
var x = new(2, 3);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,17): error CS8754: There is no target type for 'new(int, int)'
// var x = new(5);
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new(2, 3)").WithArguments("new(int, int)").WithLocation(6, 17)
);
}
[Fact]
public void TestTargetType_Discard()
{
var source = @"
class C
{
void M()
{
_ = new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,13): error CS8754: There is no target type for 'new()'
// _ = new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 13)
);
}
[Fact]
public void TestTargetType_Delegate()
{
var source = @"
delegate void D();
class C
{
void M()
{
D x0 = new();
D x1 = new(M); // ok
var x2 = (D)new();
var x3 = (D)new(M); // ok
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,16): error CS1729: 'D' does not contain a constructor that takes 0 arguments
// D x0 = new();
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("D", "0").WithLocation(7, 16),
// (9,21): error CS1729: 'D' does not contain a constructor that takes 0 arguments
// var x2 = (D)new();
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("D", "0").WithLocation(9, 21)
);
}
[Fact]
public void TestTargetType_Static()
{
var source = @"
public static class C {
static void M(object c) {
_ = (C)(new());
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,13): error CS0716: Cannot convert to static type 'C'
// _ = (C)(new());
Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)(new())").WithArguments("C").WithLocation(4, 13),
// (4,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments
// _ = (C)(new());
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("C", "0").WithLocation(4, 17)
);
}
[Fact]
public void TestTargetType_Abstract()
{
var source = @"
abstract class C
{
void M()
{
C x0 = new();
var x1 = (C)new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,16): error CS0144: Cannot create an instance of the abstract type or interface 'C'
// C x0 = new();
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(6, 16),
// (7,21): error CS0144: Cannot create an instance of the abstract type or interface 'C'
// var x1 = (C)new();
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(7, 21)
);
}
[Fact]
public void TestTargetType_Interface()
{
var source = @"
interface I {}
class C
{
void M()
{
I x0 = new();
var x1 = (I)new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,16): error CS0144: Cannot create an instance of the abstract type or interface 'I'
// I x0 = new();
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("I").WithLocation(7, 16),
// (8,21): error CS0144: Cannot create an instance of the abstract type or interface 'I'
// var x1 = (I)new();
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("I").WithLocation(8, 21)
);
}
[Fact]
public void TestTargetType_Enum()
{
var source = @"
using System;
enum E {}
class C
{
static void Main()
{
E x0 = new();
var x1 = (E)new();
Console.Write(x0);
Console.Write(x1);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "00");
}
[Fact]
public void TestTargetType_Primitive()
{
var source = @"
class C
{
void M()
{
int x0 = new();
var x1 = (int)new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,13): warning CS0219: The variable 'x0' is assigned but its value is never used
// int x0 = new();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x0").WithArguments("x0").WithLocation(6, 13),
// (7,13): warning CS0219: The variable 'x1' is assigned but its value is never used
// var x1 = (int)new();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(7, 13)
);
}
[Fact]
public void TestTargetType_TupleType()
{
var source = @"
#pragma warning disable 0219
class C
{
void M()
{
(int, int) x0 = new();
var x1 = ((int, int))new();
(int, C) x2 = new();
var x3 = ((int, C))new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void TestTargetType_ValueTuple()
{
var source = @"
using System;
class C
{
void M()
{
ValueTuple<int, int> x0 = new();
ValueTuple<int, int> x1 = new(2, 3);
var x2 = (ValueTuple<int, int>)new();
var x3 = (ValueTuple<int, int>)new(2, 3);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,30): warning CS0219: The variable 'x0' is assigned but its value is never used
// ValueTuple<int, int> x0 = new();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x0").WithArguments("x0").WithLocation(7, 30),
// (9,13): warning CS0219: The variable 'x2' is assigned but its value is never used
// var x2 = (ValueTuple<int, int>)new();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(9, 13)
);
}
[Fact]
public void TestTypeParameter()
{
var source = @"
using System;
struct S
{
static void M1<T>() where T : struct
{
Console.Write((T)new());
}
static void M2<T>() where T : new()
{
Console.Write((T)new());
}
public static void Main()
{
M1<S>();
M2<S>();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "SS");
}
[Fact]
public void TestTypeParameter_ErrorCases()
{
var source = @"
class C
{
void M<T, TClass, TStruct, TNew>()
where TClass : class
where TStruct : struct
where TNew : new()
{
{
T x0 = new();
var x1 = (T)new();
}
{
TClass x0 = new();
var x1 = (TClass)new();
}
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (10,20): error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint
// T x0 = new();
Diagnostic(ErrorCode.ERR_NoNewTyvar, "new()").WithArguments("T").WithLocation(10, 20),
// (11,25): error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint
// var x1 = (T)new();
Diagnostic(ErrorCode.ERR_NoNewTyvar, "new()").WithArguments("T").WithLocation(11, 25),
// (14,25): error CS0304: Cannot create an instance of the variable type 'TClass' because it does not have the new() constraint
// TClass x0 = new();
Diagnostic(ErrorCode.ERR_NoNewTyvar, "new()").WithArguments("TClass").WithLocation(14, 25),
// (15,30): error CS0304: Cannot create an instance of the variable type 'TClass' because it does not have the new() constraint
// var x1 = (TClass)new();
Diagnostic(ErrorCode.ERR_NoNewTyvar, "new()").WithArguments("TClass").WithLocation(15, 30)
);
}
[Fact]
public void TestTargetType_ErrorType()
{
var source = @"
class C
{
void M()
{
Missing x0 = new();
var x1 = (Missing)new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?)
// Missing x0 = new();
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(6, 9),
// (7,19): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?)
// var x1 = (Missing)new();
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(7, 19)
);
}
[Fact]
public void TestTargetType_Pointer()
{
var source = @"
class C
{
unsafe void M()
{
int* x0 = new();
var x1 = (int*)new();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,19): error CS1919: Unsafe type 'int*' cannot be used in object creation
// int* x0 = new();
Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, "new()").WithArguments("int*").WithLocation(6, 19),
// (7,24): error CS1919: Unsafe type 'int*' cannot be used in object creation
// var x1 = (int*)new();
Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, "new()").WithArguments("int*").WithLocation(7, 24)
);
}
[Fact]
public void TestTargetType_AnonymousType()
{
var source = @"
class C
{
void M()
{
var x0 = new { };
x0 = new();
var x1 = new { X = 1 };
x1 = new(2);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,14): error CS8752: The type '<empty anonymous type>' may not be used as the target-type of 'new()'
// x0 = new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new()").WithArguments("<empty anonymous type>").WithLocation(7, 14),
// (9,14): error CS8752: The type '<anonymous type: int X>' may not be used as the target-type of 'new()'
// x1 = new(2);
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new(2)").WithArguments("<anonymous type: int X>").WithLocation(9, 14));
}
[Fact]
public void TestTargetType_CoClass_01()
{
var source = @"
using System;
using System.Runtime.InteropServices;
class CoClassType : InterfaceType { }
[ComImport, Guid(""00020810-0000-0000-C000-000000000046"")]
[CoClass(typeof(CoClassType))]
interface InterfaceType { }
public class Program
{
public static void Main()
{
InterfaceType a = new() { };
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
var @new = nodes[0];
Assert.Equal("InterfaceType", model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal("InterfaceType", model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal("CoClassType..ctor()", model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, model.GetConversion(@new).Kind);
}
[Fact]
public void TestTargetType_CoClass_02()
{
var source = @"
using System;
using System.Runtime.InteropServices;
public class GenericCoClassType<T, U> : NonGenericInterfaceType
{
public GenericCoClassType(U x) { }
}
[ComImport, Guid(""00020810-0000-0000-C000-000000000046"")]
[CoClass(typeof(GenericCoClassType<int, string>))]
public interface NonGenericInterfaceType
{
}
public class MainClass
{
public static int Main()
{
NonGenericInterfaceType a = new(""string"");
return 0;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
var @new = nodes[0];
Assert.Equal("NonGenericInterfaceType", model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal("NonGenericInterfaceType", model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal("GenericCoClassType<System.Int32, System.String>..ctor(System.String x)", model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, model.GetConversion(@new).Kind);
}
[Fact]
public void TestAmbiguousCall()
{
var source = @"
class C {
public C(object a, C b) {}
public C(C a, object b) {}
public static void Main()
{
C c = new(new(), new());
}
}
";
var comp = CreateCompilation(source).VerifyDiagnostics(
// (9,15): error CS0121: The call is ambiguous between the following methods or properties: 'C.C(object, C)' and 'C.C(C, object)'
// C c = new(new(), new());
Diagnostic(ErrorCode.ERR_AmbigCall, "new(new(), new())").WithArguments("C.C(object, C)", "C.C(C, object)").WithLocation(9, 15)
);
}
[Fact]
public void TestObjectAndCollectionInitializer()
{
var source = @"
using System;
using System.Collections.Generic;
class C
{
public C field;
public int i;
public C(int i) => this.i = i;
public C() {}
public static void Main()
{
Dictionary<C, List<int>> dict1 = new() { { new() { field = new(1) }, new() { 1, 2, 3 } } };
Dictionary<C, List<int>> dict2 = new() { [new() { field = new(2) }] = new() { 4, 5, 6 } };
Dump(dict1);
Dump(dict2);
}
static void Dump(Dictionary<C, List<int>> dict)
{
foreach (C key in dict.Keys)
{
Console.Write($""C({key.field.i}): "");
}
foreach (List<int> value in dict.Values)
{
Console.WriteLine(string.Join("", "", value));
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput:
@"C(1): 1, 2, 3
C(2): 4, 5, 6");
}
[Fact]
public void TestInClassInitializer()
{
var source = @"
using System;
class D
{
}
class C
{
public D field = new();
public D Property1 { get; } = new();
public D Property2 { get; set; } = new();
public static void Main()
{
C c = new();
Console.Write(c.field);
Console.Write(c.Property1);
Console.Write(c.Property2);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "DDD");
}
[Fact]
public void TestDataFlow()
{
var source = @"
using System;
class C
{
public int field;
public static void Main()
{
int i;
C c = new() { field = (i = 42) };
Console.Write(i);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact]
public void TestDotOff()
{
var source = @"
class C
{
public static void Main()
{
_ = (new()).field;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,13): error CS8754: There is no target type for 'new()'
// _ = (new()).field;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 13)
);
}
[Fact]
public void TestConditionalAccess()
{
var source = @"
using System;
class C
{
public static void Main()
{
Console.Write(((int?)new())?.ToString());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "0");
}
[Fact]
public void TestInaccessibleConstructor()
{
var source = @"
class D
{
private D() {}
}
class C
{
public static void Main()
{
D d = new();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (11,15): error CS0122: 'D.D()' is inaccessible due to its protection level
// D d = new();
Diagnostic(ErrorCode.ERR_BadAccess, "new()").WithArguments("D.D()").WithLocation(11, 15)
);
}
[Fact]
public void TestBadArgs()
{
var source = @"
class C
{
public static void Main()
{
C c = new(1);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,15): error CS1729: 'C' does not contain a constructor that takes 1 arguments
// C c = new(1);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new(1)").WithArguments("C", "1").WithLocation(6, 15)
);
}
[Fact]
public void TestNested()
{
var source = @"
using System;
class C
{
public C(C a, C b) => Console.Write(3);
public C(int i) => Console.Write(i);
public static void Main()
{
C x = new(new(1), new(2));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "123");
}
[Fact]
public void TestDeconstruction()
{
var source = @"
class C
{
public static void Main()
{
var (_, _) = new();
(var _, var _) = new();
(C _, C _) = new();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,22): error CS8754: There is no target type for 'new()'
// var (_, _) = new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 22),
// (6,22): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// var (_, _) = new();
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "new()").WithLocation(6, 22),
// (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable '_'.
// var (_, _) = new();
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "_").WithArguments("_").WithLocation(6, 14),
// (6,14): error CS8183: Cannot infer the type of implicitly-typed discard.
// var (_, _) = new();
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(6, 14),
// (6,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable '_'.
// var (_, _) = new();
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "_").WithArguments("_").WithLocation(6, 17),
// (6,17): error CS8183: Cannot infer the type of implicitly-typed discard.
// var (_, _) = new();
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(6, 17),
// (7,26): error CS8754: There is no target type for 'new()'
// (var _, var _) = new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 26),
// (7,26): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// (var _, var _) = new();
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "new()").WithLocation(7, 26),
// (7,10): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable '_'.
// (var _, var _) = new();
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "var _").WithArguments("_").WithLocation(7, 10),
// (7,10): error CS8183: Cannot infer the type of implicitly-typed discard.
// (var _, var _) = new();
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(7, 10),
// (7,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable '_'.
// (var _, var _) = new();
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "var _").WithArguments("_").WithLocation(7, 17),
// (7,17): error CS8183: Cannot infer the type of implicitly-typed discard.
// (var _, var _) = new();
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(7, 17),
// (8,22): error CS8754: There is no target type for 'new()'
// (C _, C _) = new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(8, 22),
// (8,22): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// (C _, C _) = new();
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "new()").WithLocation(8, 22)
);
}
[Fact]
public void TestBestType_NullCoalescing()
{
var source = @"
using System;
class C
{
public static void Main()
{
C c = null;
Console.Write(c ?? new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
}
[Fact]
public void TestBestType_Lambda()
{
var source = @"
using System;
class C
{
public static void M<T>(Func<bool, T> f)
{
Console.Write(f(true));
Console.Write(f(false));
}
public static void Main()
{
M(b => { if (b) return new C(); else return new(); });
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CC");
}
[Fact]
public void TestBestType_SwitchExpression()
{
var source = @"
using System;
class C
{
public static void Main()
{
var b = false;
Console.Write((int)(b switch { true => 1, false => new() }));
b = true;
Console.Write((int)(b switch { true => 1, false => new() }));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "01");
}
[Fact]
public void TestInSwitchExpression()
{
var source = @"
using System;
class C
{
public static void Main()
{
C x = 0 switch { _ => new() };
Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
}
[Fact]
public void TestInNullCoalescingAssignment()
{
var source = @"
using System;
class C
{
public static void Main()
{
C x = null;
x ??= new();
Console.Write(x);
int? i = null;
i ??= new();
Console.Write(i);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C0");
}
[Fact]
public void TestInNullCoalescingAssignment_ErrorCase()
{
var source = @"
class C
{
public static void Main()
{
new() ??= new C();
new() ??= new();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (6,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// new() ??= new C();
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new()").WithLocation(6, 9),
// (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// new() ??= new();
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new()").WithLocation(7, 9)
);
}
[Fact]
public void TestBestType_Lambda_ErrorCase()
{
var source = @"
using System;
class C
{
public static void M<T>(Func<bool, T> f)
{
}
public static void Main()
{
M(b => { if (b) return new(); else return new(); });
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (12,9): error CS0411: The type arguments for method 'C.M<T>(Func<bool, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(b => { if (b) return new(); else return new(); });
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(System.Func<bool, T>)").WithLocation(12, 9)
);
}
[Fact]
public void TestBadTypeParameter()
{
var source = @"
class C
{
static void M<A, B, C>()
where A : struct
where B : new()
{
A v1 = new(1);
B v2 = new(2);
C v3 = new();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(
// (8,16): error CS0417: 'A': cannot provide arguments when creating an instance of a variable type
// A v1 = new(1);
Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new(1)").WithArguments("A").WithLocation(8, 16),
// (9,16): error CS0417: 'B': cannot provide arguments when creating an instance of a variable type
// B v2 = new(2);
Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new(2)").WithArguments("B").WithLocation(9, 16),
// (10,16): error CS0304: Cannot create an instance of the variable type 'C' because it does not have the new() constraint
// C v3 = new();
Diagnostic(ErrorCode.ERR_NoNewTyvar, "new()").WithArguments("C").WithLocation(10, 16)
);
}
[Fact]
public void TestTypeParameterInitializer()
{
var source = @"
using System;
class C
{
public int field;
static void M1<T>() where T : C, new()
{
Console.Write(((T)new(){ field = 42 }).field);
}
public static void Main()
{
M1<C>();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact]
public void TestInitializer_ErrorCase()
{
var source = @"
class C
{
public static void Main()
{
string x = new() { Length = 5 };
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (8,28): error CS0200: Property or indexer 'string.Length' cannot be assigned to -- it is read only
// string x = new() { Length = 5 };
Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Length").WithArguments("string.Length").WithLocation(6, 28),
// (8,20): error CS1729: 'string' does not contain a constructor that takes 0 arguments
// string x = new() { Length = 5 };
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new() { Length = 5 }").WithArguments("string", "0").WithLocation(6, 20)
);
}
[Fact]
public void TestImplicitConversion()
{
var source = @"
public class Dog
{
public Dog() {}
}
public class Animal
{
public Animal() {}
public static implicit operator Animal(Dog dog) => throw null;
}
public class Program
{
public static void M(Animal a) => System.Console.Write(a);
public static void Main()
{
M(new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
);
CompileAndVerify(comp, expectedOutput: "Animal");
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void ArgList()
{
var source = @"
using System;
class C
{
static void Main()
{
C x = new(__arglist(2, 3, true));
}
public C(__arglist)
{
DumpArgs(new(__arglist));
}
static void DumpArgs(ArgIterator args)
{
while(args.GetRemainingCount() > 0)
{
TypedReference tr = args.GetNextArg();
object arg = TypedReference.ToObject(tr);
Console.Write(arg);
}
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "23True");
}
[Fact]
public void TestOverloadResolution01()
{
var source = @"
class C
{
public C(int i) {}
}
class D
{
}
class Program
{
static void M(C c, object o) {}
static void M(D d, int i) {}
public static void Main()
{
M(new(1), 1);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (18,11): error CS1729: 'D' does not contain a constructor that takes 1 arguments
// M(new(1), 1);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new(1)").WithArguments("D", "1").WithLocation(18, 11)
);
}
[Fact]
public void TestOverloadResolution02()
{
var source = @"
using System;
class A
{
public A(int i) {}
}
class B : A
{
public B(int i) : base(i) {}
}
class Program
{
static void M(A a) => Console.Write(""A"");
static void M(B a) => Console.Write(""B"");
public static void Main()
{
M(new(43));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "B");
}
[Fact]
public void TestOverloadResolution03()
{
var source = @"
class A
{
public A(int i) {}
}
class B : A
{
public B(int i) : base(i) {}
}
class Program
{
static void M(A a) {}
static void M(B a) {}
public static void Main()
{
M(new(Missing()));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (18,15): error CS0103: The name 'Missing' does not exist in the current context
// M(new(Missing()));
Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(18, 15)
);
}
[Fact]
public void TestOverloadResolution04()
{
var source = @"
class A
{
public A(int i) {}
}
class B : A
{
public B(int i) : base(i) {}
}
class Program
{
public static void Main()
{
Missing(new(1));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (15,9): error CS0103: The name 'Missing' does not exist in the current context
// Missing(new(1));
Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(15, 9)
);
}
[Fact]
public void TestOverloadResolution05()
{
var source = @"
class A
{
public A(int i) {}
}
class B : A
{
public B(int i) : base(i) {}
}
class Program
{
static void M(A a, int i) {}
static void M(B a, object i) {}
public static void Main()
{
M(new(), 1);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A, int)' and 'Program.M(B, object)'
// M(new(), 1);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A, int)", "Program.M(B, object)").WithLocation(18, 9)
);
}
[Fact]
public void TestOverloadResolution06()
{
var source = @"
class C
{
public C(object a, C b) {}
public C(C a, int b) {}
public static void Main()
{
C c = new(new(), new());
}
}
";
var comp = CreateCompilation(source).VerifyDiagnostics(
// (9,19): error CS1729: 'C' does not contain a constructor that takes 0 arguments
// C c = new(new(), new());
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("C", "0").WithLocation(9, 19)
);
}
[Fact]
public void TestSymbols()
{
var source = @"
class C
{
static C N(int i) => null;
static void M(C c) {}
public static void Main()
{
Missing(new() { X = N(1) });
M(new() { X = N(2) });
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (10,9): error CS0103: The name 'Missing' does not exist in the current context
// Missing(new() { X = N(1) });
Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(10, 9),
// (11,19): error CS0117: 'C' does not contain a definition for 'X'
// M(new() { X = N(2) });
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(11, 19)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray();
assert(1, "N(1)", type: "C", convertedType: "C", symbol: "C C.N(System.Int32 i)", ConversionKind.Identity);
assert(3, "N(2)", type: "C", convertedType: "C", symbol: "C C.N(System.Int32 i)", ConversionKind.Identity);
void assert(int index, string expression, string type, string convertedType, string symbol, ConversionKind conversionKind)
{
var invocation = nodes[index];
Assert.Equal(expression, invocation.ToString());
Assert.Equal(type, model.GetTypeInfo(invocation).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(invocation).ConvertedType.ToTestDisplayString());
Assert.Equal(symbol, model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString());
Assert.Equal(conversionKind, model.GetConversion(invocation).Kind);
}
}
[Fact]
public void TestAssignment()
{
var source = @"
class Program
{
public static void Main()
{
new() = 5;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (6,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// new() = 5;
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new()").WithLocation(6, 9)
);
}
[Fact]
public void TestNullableType01()
{
var source = @"
using System;
struct S
{
public S(int i)
{
Console.Write(i);
}
public static void Main()
{
S? s = new(43);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "43");
}
[Fact]
public void TestNullableType02()
{
var source = @"
using System;
struct S
{
public static T? M<T>() where T : struct
{
return new();
}
public static void Main()
{
Console.Write(M<S>());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "S");
}
[Fact]
public void TestInStatement()
{
var source = @"
struct S
{
public static void Main()
{
new(a) { x };
new() { x };
}
}
";
_ = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// new(a) { x };
Diagnostic(ErrorCode.ERR_IllegalStatement, "new(a) { x }").WithLocation(6, 9),
// (6,13): error CS0103: The name 'a' does not exist in the current context
// new(a) { x };
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(6, 13),
// (6,18): error CS0103: The name 'x' does not exist in the current context
// new(a) { x };
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 18),
// (7,9): error CS8754: There is no target type for 'new()'
// new() { x };
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new() { x }").WithArguments("new()").WithLocation(7, 9),
// (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// new() { x };
Diagnostic(ErrorCode.ERR_IllegalStatement, "new() { x }").WithLocation(7, 9),
// (7,17): error CS0103: The name 'x' does not exist in the current context
// new() { x };
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(7, 17)
);
}
[Fact]
public void TestLangVersion_CSharp7()
{
string source = @"
class C
{
static void Main()
{
C x = new();
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
comp.VerifyDiagnostics(
// (6,15): error CS8107: Feature 'target-typed object creation' is not available in C# 7.0. Please use language version 9.0 or greater.
// C x = new();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "new").WithArguments("target-typed object creation", "9.0").WithLocation(6, 15)
);
}
[Fact]
public void TestAssignmentToClass()
{
string source = @"
class C
{
static void Main()
{
C x = new();
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().Single();
Assert.Equal("C", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("C", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
Assert.Equal("C..ctor()", model.GetSymbolInfo(def).Symbol.ToTestDisplayString());
Assert.False(model.GetConstantValue(def).HasValue);
Assert.True(model.GetConversion(def).IsIdentity);
}
[Fact]
public void TestAssignmentToStruct()
{
string source = @"
struct S
{
public S(int i) {}
static void Main()
{
S x = new(43);
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "S");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().Single();
Assert.Equal("S", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("S", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
Assert.Equal("S..ctor(System.Int32 i)", model.GetSymbolInfo(def).Symbol.ToTestDisplayString());
Assert.False(model.GetConstantValue(def).HasValue);
Assert.True(model.GetConversion(def).IsIdentity);
}
[Fact]
public void AssignmentToNullableStruct()
{
string source = @"
struct S
{
public S(int i) {}
static void Main()
{
S? x = new(43);
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "S");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().Single();
Assert.Equal("S", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("S?", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
Assert.Equal("S..ctor(System.Int32 i)", model.GetSymbolInfo(def).Symbol.ToTestDisplayString());
Assert.False(model.GetConstantValue(def).HasValue);
Assert.True(model.GetConversion(def).IsNullable);
Assert.True(model.GetConversion(def).IsImplicit);
}
[Fact]
public void AssignmentToThisOnRefType()
{
string source = @"
public class C
{
public int field;
public C() => this = new();
public static void Main()
{
new C();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (5,19): error CS1604: Cannot assign to 'this' because it is read-only
// public C() => this = new();
Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this").WithLocation(5, 19)
);
}
[Fact]
public void AssignmentToThisOnStructType()
{
string source = @"
public struct S
{
public int field;
public S(int x) => this = new(x);
public static void Main()
{
new S(1);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().ElementAt(0);
Assert.Equal("new(x)", def.ToString());
Assert.Equal("S", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("S", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
}
[Fact]
public void InAttributeParameter()
{
string source = @"
[Custom(z: new(), y: new(), x: new())]
class C
{
[Custom(new(1), new('s', 2))]
void M()
{
}
}
public class CustomAttribute : System.Attribute
{
public CustomAttribute(int x, string y, byte z = 0) { }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (2,22): error CS1729: 'string' does not contain a constructor that takes 0 arguments
// [Custom(z: new(), y: new(), x: new())]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(2, 22),
// (5,13): error CS1729: 'int' does not contain a constructor that takes 1 arguments
// [Custom(new(1), new('s', 2))]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new(1)").WithArguments("int", "1").WithLocation(5, 13),
// (5,21): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Custom(new(1), new('s', 2))]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new('s', 2)").WithLocation(5, 21)
);
}
[Fact]
public void InStringInterpolation()
{
string source = @"
class C
{
static void Main()
{
System.Console.Write($""({new()}) ({new object()})"");
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "(System.Object) (System.Object)");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var @new = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().Single();
Assert.Equal("new()", @new.ToString());
Assert.Equal("System.Object", model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal("System.Object", model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal("System.Object..ctor()", model.GetSymbolInfo(@new).Symbol?.ToTestDisplayString());
Assert.False(model.GetConstantValue(@new).HasValue);
var newObject = nodes.OfType<ObjectCreationExpressionSyntax>().Single();
Assert.Equal("new object()", newObject.ToString());
Assert.Equal("System.Object", model.GetTypeInfo(newObject).Type.ToTestDisplayString());
Assert.Equal("System.Object", model.GetTypeInfo(newObject).ConvertedType.ToTestDisplayString());
Assert.Equal("System.Object..ctor()", model.GetSymbolInfo(newObject).Symbol?.ToTestDisplayString());
}
[Fact]
public void InUsing01()
{
string source = @"
class C
{
static void Main()
{
using (new())
{
}
using (var x = new())
{
}
using (System.IDisposable x = new())
{
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,16): error CS8754: There is no target type for 'new()'
// using (new())
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 16),
// (10,24): error CS8754: There is no target type for 'new()'
// using (var x = new())
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(10, 24),
// (14,39): error CS0144: Cannot create an instance of the abstract type or interface 'IDisposable'
// using (System.IDisposable x = new())
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("System.IDisposable").WithLocation(14, 39)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
assert(0, type: "?", convertedType: "?", ConversionKind.Identity);
assert(1, type: "?", convertedType: "?", ConversionKind.Identity);
assert(2, type: "System.IDisposable", convertedType: "System.IDisposable", ConversionKind.Identity);
void assert(int index, string type, string convertedType, ConversionKind conversionKind)
{
var @new = nodes[index];
Assert.Equal(type, model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(@new).Symbol);
Assert.Equal(conversionKind, model.GetConversion(@new).Kind);
}
}
[Fact]
public void InUsing02()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
Console.Write(""C.Dispose"");
}
static void Main()
{
using (C c = new())
{
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C.Dispose");
}
[Fact]
public void TestInAwait()
{
string source = @"
class C
{
async System.Threading.Tasks.Task M1()
{
await new();
}
async System.Threading.Tasks.Task M2()
{
await new(a);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,15): error CS8754: There is no target type for 'new()'
// await new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 15),
// (11,19): error CS0103: The name 'a' does not exist in the current context
// await new(a);
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(11, 19)
);
}
[Fact]
public void ReturningFromAsyncMethod()
{
string source = @"
using System.Threading.Tasks;
class C
{
async Task<T> M2<T>() where T : new()
{
await Task.Delay(0);
return new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().ElementAt(0);
Assert.Equal("new()", def.ToString());
Assert.Equal("T", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("T", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(def).Symbol);
Assert.False(model.GetConstantValue(def).HasValue);
Assert.True(model.GetConversion(def).IsIdentity);
}
[Fact]
public void TestInAsyncLambda_01()
{
string source = @"
class C
{
static void F<T>(System.Threading.Tasks.Task<T> t) { }
static void M()
{
F(async () => await new());
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,9): error CS0411: The type arguments for method 'C.F<T>(Task<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F(async () => await new());
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("C.F<T>(System.Threading.Tasks.Task<T>)").WithLocation(8, 9)
);
}
[Fact]
public void TestInAsyncLambda_02()
{
string source = @"
class C
{
static void F<T>(System.Threading.Tasks.Task<T> t) { }
static void M()
{
F(async () => new());
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,9): error CS0411: The type arguments for method 'C.F<T>(Task<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F(async () => new());
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("C.F<T>(System.Threading.Tasks.Task<T>)").WithLocation(8, 9),
// (8,20): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// F(async () => new());
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(8, 20)
);
}
[Fact]
public void RefReturnValue1()
{
string source = @"
class C
{
ref int M()
{
return new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS8150: By-value returns may only be used in methods that return by value
// return new();
Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(6, 9)
);
}
[Fact]
public void RefReturnValue2()
{
string source = @"
class C
{
ref C M()
{
return ref new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// return ref new();
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "new()").WithLocation(6, 20)
);
}
[Fact]
public void InAnonType()
{
string source = @"
class C
{
static void M()
{
var x = new { Prop = new() };
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,30): error CS8754: There is no target type for 'new()'
// var x = new { Prop = new() };
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 30)
);
}
[Fact]
public void BadUnaryOperator()
{
string source = @"
class C
{
static void M()
{
C v1 = +new();
C v2 = -new();
C v3 = ~new();
C v4 = !new();
C v5 = ++new();
C v6 = --new();
C v7 = new()++;
C v8 = new()--;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,17): error CS8754: There is no target type for 'new()'
// C v1 = +new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 17),
// (7,17): error CS8754: There is no target type for 'new()'
// C v2 = -new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 17),
// (8,17): error CS8754: There is no target type for 'new()'
// C v3 = ~new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(8, 17),
// (9,17): error CS8754: There is no target type for 'new()'
// C v4 = !new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(9, 17),
// (10,18): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer
// C v5 = ++new();
Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "new()").WithLocation(10, 18),
// (11,18): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer
// C v6 = --new();
Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "new()").WithLocation(11, 18),
// (12,16): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer
// C v7 = new()++;
Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "new()").WithLocation(12, 16),
// (13,16): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer
// C v8 = new()--;
Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "new()").WithLocation(13, 16)
);
}
[Fact]
public void AmbiguousMethod()
{
string source = @"
class C
{
static void Main()
{
M(new());
}
static void M(int x) { }
static void M(string x) { }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(int)' and 'C.M(string)'
// M(new());
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(int)", "C.M(string)").WithLocation(6, 9)
);
}
[Fact]
public void MethodWithNullableParameters()
{
string source = @"
struct S
{
public S(int i) {}
static void Main()
{
M(new(43));
}
static void M(S? x) => System.Console.Write(x);
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "S");
}
[Fact]
public void CannotInferTypeArg()
{
string source = @"
class C
{
static void Main()
{
M(new());
}
static void M<T>(T x) { }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,9): error CS0411: The type arguments for method 'C.M<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(new());
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T)").WithLocation(6, 9)
);
}
[Fact]
public void CannotInferTypeArg2()
{
string source = @"
class C
{
static void Main()
{
M(new(), null);
}
static void M<T>(T x, T y) where T : class { }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,9): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(new(), null);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(6, 9)
);
}
[Fact]
public void Invocation()
{
string source = @"
class C
{
static void Main()
{
new().ToString();
new()[0].ToString();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,9): error CS8754: There is no target type for 'new()'
// new().ToString();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 9),
// (7,9): error CS8754: There is no target type for 'new()'
// new()[0].ToString();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 9)
);
}
[Fact]
public void InThrow()
{
string source = @"
class C
{
static void Main()
{
throw new(""message"");
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().First();
Assert.Equal("System.Exception", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("System.Exception", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
Assert.Equal("System.Exception..ctor(System.String message)", model.GetSymbolInfo(def).Symbol.ToTestDisplayString());
}
[Fact]
public void TestConst()
{
string source = @"
class C
{
static void M()
{
const object x = new();
const int y = new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,26): error CS0133: The expression being assigned to 'x' must be constant
// const object x = new();
Diagnostic(ErrorCode.ERR_NotConstantExpression, "new()").WithArguments("x").WithLocation(6, 26),
// (7,19): warning CS0219: The variable 'y' is assigned but its value is never used
// const int y = new();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(7, 19)
);
}
[Fact]
public void ImplicitlyTypedArray()
{
string source = @"
class C
{
static void Main()
{
var t = new[] { new C(), new() };
System.Console.Write(t[1]);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().First();
Assert.Equal("new()", def.ToString());
Assert.Equal("C", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("C", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
Assert.Equal("C..ctor()", model.GetSymbolInfo(def).Symbol.ToTestDisplayString());
Assert.False(model.GetConstantValue(def).HasValue);
}
[Fact]
public void InSwitch1()
{
string source = @"
class C
{
static void Main()
{
switch (new())
{
case new() when new():
case (new()) when (new()):
break;
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,17): error CS8754: There is no target type for 'new()'
// switch (new())
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 17),
// (10,17): warning CS0162: Unreachable code detected
// break;
Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(10, 17)
);
}
[Fact]
public void InSwitch2()
{
string source = @"
class C
{
static void Main()
{
switch (new C())
{
case new():
case (new()):
break;
}
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,18): error CS0150: A constant value is expected
// case new():
Diagnostic(ErrorCode.ERR_ConstantExpected, "new()").WithLocation(8, 18),
// (9,19): error CS0150: A constant value is expected
// case (new()):
Diagnostic(ErrorCode.ERR_ConstantExpected, "new()").WithLocation(9, 19)
);
}
[Fact]
public void InSwitch3()
{
string source = @"
class C
{
static void Main()
{
int i = 0;
bool b = true;
switch (i)
{
case new() when b:
System.Console.Write(0);
break;
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "0");
}
[Fact]
public void InGoToCase()
{
string source = @"
using System;
class C
{
static int Get(int i)
{
switch (i)
{
case new():
return 1;
case 1:
goto case new();
default:
return 2;
}
}
static void Main()
{
Console.Write(Get(0));
Console.Write(Get(1));
Console.Write(Get(2));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "112");
}
[Fact]
public void InCatchFilter()
{
string source = @"
class C
{
static void Main()
{
try
{
}
catch when (new())
{
}
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,21): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block
// catch when (new())
Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "new()").WithLocation(9, 21)
);
}
[Fact]
public void InLock()
{
string source = @"
class C
{
static void Main()
{
lock (new())
{
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,15): error CS8754: There is no target type for 'new()'
// lock (new())
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 15)
);
}
[Fact]
public void InMakeRef()
{
string source = @"
class C
{
static void Main()
{
System.TypedReference tr = __makeref(new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,46): error CS1510: A ref or out value must be an assignable variable
// System.TypedReference tr = __makeref(new());
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new()").WithLocation(6, 46)
);
}
[Fact]
public void InNameOf()
{
string source = @"
class C
{
static void Main()
{
_ = nameof(new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,20): error CS8081: Expression does not have a name.
// _ = nameof(new());
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "new()").WithLocation(6, 20)
);
}
[Fact]
public void InOutArgument()
{
string source = @"
class C
{
static void M(out int i)
{
i = 0;
M(out new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (7,15): error CS1510: A ref or out value must be an assignable variable
// M(out new());
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new()").WithLocation(7, 15)
);
}
[Fact]
public void InSizeOf()
{
string source = @"
class C
{
static void Main()
{
_ = sizeof(new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,20): error CS1031: Type expected
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_TypeExpected, "new").WithLocation(6, 20),
// (6,20): error CS1026: ) expected
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_CloseParenExpected, "new").WithLocation(6, 20),
// (6,20): error CS1002: ; expected
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_SemicolonExpected, "new").WithLocation(6, 20),
// (6,25): error CS1002: ; expected
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(6, 25),
// (6,25): error CS1513: } expected
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(6, 25),
// (6,13): error CS0233: '?' does not have a predefined size, therefore sizeof can only be used in an unsafe context
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(").WithArguments("?").WithLocation(6, 13),
// (6,20): error CS8754: There is no target type for 'new()'
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 20)
);
}
[Fact]
public void InTypeOf()
{
string source = @"
class C
{
static void Main()
{
_ = typeof(new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,20): error CS1031: Type expected
// _ = typeof(new());
Diagnostic(ErrorCode.ERR_TypeExpected, "new").WithLocation(6, 20),
// (6,20): error CS1026: ) expected
// _ = typeof(new());
Diagnostic(ErrorCode.ERR_CloseParenExpected, "new").WithLocation(6, 20),
// (6,20): error CS1002: ; expected
// _ = typeof(new());
Diagnostic(ErrorCode.ERR_SemicolonExpected, "new").WithLocation(6, 20),
// (6,20): error CS8754: There is no target type for 'new()'
// _ = typeof(new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 20),
// (6,25): error CS1002: ; expected
// _ = typeof(new());
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(6, 25),
// (6,25): error CS1513: } expected
// _ = typeof(new());
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(6, 25)
);
}
[Fact]
public void InChecked()
{
string source = @"
class C
{
static void Main()
{
int i = checked(new(a));
int j = checked(new()); // ok
C k = unchecked(new()); // ok
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,29): error CS0103: The name 'a' does not exist in the current context
// int i = checked(new(a));
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(6, 29),
// (7,13): warning CS0219: The variable 'j' is assigned but its value is never used
// int j = checked(new());
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "j").WithArguments("j").WithLocation(7, 13)
);
}
[Fact]
public void InRange()
{
string source = @"
using System;
class C
{
static void Main()
{
Range x0 = new()..new();
Range x1 = 1..new();
Range x2 = new()..1;
Console.WriteLine($""{x0.Start.Value}..{x0.End.Value}"");
Console.WriteLine($""{x1.Start.Value}..{x1.End.Value}"");
Console.WriteLine($""{x2.Start.Value}..{x2.End.Value}"");
}
}
";
var comp = CreateCompilationWithIndexAndRange(source, options: TestOptions.DebugExe, parseOptions: ImplicitObjectCreationTestOptions);
comp.VerifyDiagnostics();
var expectedOutput =
@"0..0
1..0
0..1";
CompileAndVerify(comp, expectedOutput: expectedOutput);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
assert(0, type: "System.Index", convertedType: "System.Index", symbol: "System.Index..ctor()", ConversionKind.Identity);
assert(1, type: "System.Index", convertedType: "System.Index", symbol: "System.Index..ctor()", ConversionKind.Identity);
assert(2, type: "System.Index", convertedType: "System.Index", symbol: "System.Index..ctor()", ConversionKind.Identity);
assert(3, type: "System.Index", convertedType: "System.Index", symbol: "System.Index..ctor()", ConversionKind.Identity);
void assert(int index, string type, string convertedType, string symbol, ConversionKind conversionKind)
{
var @new = nodes[index];
Assert.Equal(type, model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal(symbol, model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(conversionKind, model.GetConversion(@new).Kind);
}
}
[Fact]
public void RefTypeAndValue()
{
string source = @"
class C
{
static void Main()
{
var t = __reftype(new());
int rv = __refvalue(new(), int);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
}
[Fact]
public void ConditionalOnNew()
{
string source = @"
class C
{
static void Main()
{
if (new())
{
System.Console.Write(""if"");
}
while (new())
{
System.Console.Write(""while"");
}
for (int i = 0; new(); i++)
{
System.Console.Write(""for"");
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (8,13): warning CS0162: Unreachable code detected
// System.Console.Write("if");
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(8, 13),
// (13,13): warning CS0162: Unreachable code detected
// System.Console.Write("while");
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(13, 13),
// (18,13): warning CS0162: Unreachable code detected
// System.Console.Write("for");
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(18, 13));
}
[Fact]
public void InFixed()
{
string source = @"
class C
{
static unsafe void Main()
{
fixed (byte* p = new())
{
}
fixed (byte* p = &new())
{
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
comp.VerifyDiagnostics(
// (6,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (byte* p = new())
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new()").WithLocation(6, 26),
// (9,27): error CS0211: Cannot take the address of the given expression
// fixed (byte* p = &new())
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "new()").WithLocation(9, 27)
);
}
[Fact]
public void Dereference()
{
string source = @"
class C
{
static void M()
{
var p = *new();
var q = new()->F;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,18): error CS8754: There is no target type for 'new()'
// var p = *new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 18),
// (7,17): error CS8754: There is no target type for 'new()'
// var q = new()->F;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 17)
);
}
[Fact]
public void FailedImplicitlyTypedArray()
{
string source = @"
class C
{
static void Main()
{
var t = new[] { new(), new() };
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,17): error CS0826: No best type found for implicitly-typed array
// var t = new[] { new(), new() };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { new(), new() }").WithLocation(6, 17)
);
}
[Fact]
public void ArrayConstruction()
{
string source = @"
class C
{
static void Main()
{
var t = new object[new()];
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void Tuple()
{
string source = @"
class C
{
static void Main()
{
(int, C) t = (1, new());
System.Console.Write(t.Item2);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
}
[Fact]
public void TypeInferenceSucceeds()
{
string source = @"
class C
{
static void Main()
{
M(new(), new C());
}
static void M<T>(T x, T y) { System.Console.Write(x); }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
}
[Fact]
public void ArrayTypeInferredFromParams()
{
string source = @"
class C
{
static void Main()
{
M(new());
}
static void M(params object[] x) { }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,11): error CS9366: The type 'object[]' may not be used as the target-type of 'new()'
// M(new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new()").WithArguments("object[]").WithLocation(6, 11)
);
}
[Fact]
public void ParamsAmbiguity01()
{
string source = @"
class C
{
static void Main()
{
M(new());
}
static void M(params object[] x) { }
static void M(params int[] x) { }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(params object[])' and 'C.M(params int[])'
// M(new());
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(params object[])", "C.M(params int[])").WithLocation(6, 9)
);
}
[Fact]
public void ParamsAmbiguity02()
{
string source = @"
class C
{
static void Main()
{
M(new());
}
static void M(params object[] x) { }
static void M(C x) { }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(params object[])' and 'C.M(C)'
// M(new());
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(params object[])", "C.M(C)").WithLocation(6, 9)
);
}
[Fact]
public void ParamsAmbiguity03()
{
string source = @"
class C
{
static void Main()
{
object o = null;
C c = new();
M(o, new());
M(new(), o);
M(c, new());
M(new(), c);
}
static void M<T>(T x, params T[] y) { }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (8,14): error CS9366: The type 'object[]' may not be used as the target-type of 'new'.
// M(o, new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new()").WithArguments("object[]").WithLocation(8, 14),
// (10,14): error CS9366: The type 'C[]' may not be used as the target-type of 'new'.
// M(c, new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new()").WithArguments("C[]").WithLocation(10, 14)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var first = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().ElementAt(1);
Assert.Equal("(o, new())", first.Parent.Parent.ToString());
Assert.Equal("System.Object[]", model.GetTypeInfo(first).Type.ToTestDisplayString());
var second = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().ElementAt(2);
Assert.Equal("(new(), o)", second.Parent.Parent.ToString());
Assert.Equal("System.Object", model.GetTypeInfo(second).Type.ToTestDisplayString());
var third = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().ElementAt(3);
Assert.Equal("(c, new())", third.Parent.Parent.ToString());
Assert.Equal("C[]", model.GetTypeInfo(third).Type.ToTestDisplayString());
var fourth = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().ElementAt(4);
Assert.Equal("(new(), c)", fourth.Parent.Parent.ToString());
Assert.Equal("C", model.GetTypeInfo(fourth).Type.ToTestDisplayString());
}
[Fact]
public void NewIdentifier()
{
string source = @"
class C
{
static void Main()
{
int @new = 2;
C x = new();
System.Console.Write($""{x} {@new}"");
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C 2");
}
[Fact]
public void Return()
{
string source = @"
class C
{
static C M()
{
return new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void NewInEnum()
{
string source = @"
enum E : byte
{
A = new(),
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void YieldReturn()
{
string source = @"
using System.Collections;
using System.Collections.Generic;
class C
{
static IEnumerable<C> M()
{
yield return new();
}
static IEnumerable M2()
{
yield return new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void InvocationOnDynamic()
{
string source = @"
class C
{
static void M1()
{
dynamic d = null;
d.M2(new());
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,14): error CS8754: There is no target type for 'new()'
// d.M2(new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 14)
);
}
[Fact]
public void DynamicInvocation()
{
string source = @"
class C
{
static void Main()
{
F(new());
}
static void F(dynamic x)
{
System.Console.Write(x == null);
}
}
";
var comp = CreateCompilation(source, references: new[] { CSharpRef }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,11): error CS8752: The type 'dynamic' may not be used as the target type of new()
// F(new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new()").WithArguments("dynamic").WithLocation(6, 11)
);
}
[Fact]
public void TestBinaryOperators01()
{
string source = @"
class C
{
static void Main()
{
var a = new() + new();
var b = new() - new();
var c = new() & new();
var d = new() | new();
var e = new() ^ new();
var f = new() * new();
var g = new() / new();
var h = new() % new();
var i = new() >> new();
var j = new() << new();
var k = new() > new();
var l = new() < new();
var m = new() >= new();
var n = new() <= new();
var o = new() == new();
var p = new() != new();
var q = new() && new();
var r = new() || new();
var s = new() ?? new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,17): error CS8310: Operator '+' cannot be applied to operand 'new()'
// var a = new() + new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() + new()").WithArguments("+", "new()").WithLocation(6, 17),
// (7,17): error CS8310: Operator '-' cannot be applied to operand 'new()'
// var b = new() - new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() - new()").WithArguments("-", "new()").WithLocation(7, 17),
// (8,17): error CS8310: Operator '&' cannot be applied to operand 'new()'
// var c = new() & new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() & new()").WithArguments("&", "new()").WithLocation(8, 17),
// (9,17): error CS8310: Operator '|' cannot be applied to operand 'new()'
// var d = new() | new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() | new()").WithArguments("|", "new()").WithLocation(9, 17),
// (10,17): error CS8310: Operator '^' cannot be applied to operand 'new()'
// var e = new() ^ new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() ^ new()").WithArguments("^", "new()").WithLocation(10, 17),
// (11,17): error CS8310: Operator '*' cannot be applied to operand 'new()'
// var f = new() * new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() * new()").WithArguments("*", "new()").WithLocation(11, 17),
// (12,17): error CS8310: Operator '/' cannot be applied to operand 'new()'
// var g = new() / new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() / new()").WithArguments("/", "new()").WithLocation(12, 17),
// (13,17): error CS8310: Operator '%' cannot be applied to operand 'new()'
// var h = new() % new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() % new()").WithArguments("%", "new()").WithLocation(13, 17),
// (14,17): error CS8310: Operator '>>' cannot be applied to operand 'new()'
// var i = new() >> new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() >> new()").WithArguments(">>", "new()").WithLocation(14, 17),
// (15,17): error CS8310: Operator '<<' cannot be applied to operand 'new()'
// var j = new() << new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() << new()").WithArguments("<<", "new()").WithLocation(15, 17),
// (16,17): error CS8310: Operator '>' cannot be applied to operand 'new()'
// var k = new() > new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() > new()").WithArguments(">", "new()").WithLocation(16, 17),
// (17,17): error CS8310: Operator '<' cannot be applied to operand 'new()'
// var l = new() < new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() < new()").WithArguments("<", "new()").WithLocation(17, 17),
// (18,17): error CS8310: Operator '>=' cannot be applied to operand 'new()'
// var m = new() >= new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() >= new()").WithArguments(">=", "new()").WithLocation(18, 17),
// (19,17): error CS8310: Operator '<=' cannot be applied to operand 'new()'
// var n = new() <= new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() <= new()").WithArguments("<=", "new()").WithLocation(19, 17),
// (20,17): error CS8310: Operator '==' cannot be applied to operand 'new()'
// var o = new() == new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == new()").WithArguments("==", "new()").WithLocation(20, 17),
// (21,17): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// var p = new() != new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != new()").WithArguments("!=", "new()").WithLocation(21, 17),
// (22,17): error CS8754: There is no target type for 'new()'
// var q = new() && new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(22, 17),
// (22,26): error CS8754: There is no target type for 'new()'
// var q = new() && new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(22, 26),
// (23,17): error CS8754: There is no target type for 'new()'
// var r = new() || new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(23, 17),
// (23,26): error CS8754: There is no target type for 'new()'
// var r = new() || new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(23, 26),
// (24,17): error CS8754: There is no target type for 'new()'
// var s = new() ?? new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(24, 17)
);
}
[Fact]
public void TestBinaryOperators02()
{
string source = @"
class C
{
static void Main()
{
_ = new() + 1;
_ = new() - 1;
_ = new() & 1;
_ = new() | 1;
_ = new() ^ 1;
_ = new() * 1;
_ = new() / 1;
_ = new() % 1;
_ = new() >> 1;
_ = new() << 1;
_ = new() > 1;
_ = new() < 1;
_ = new() >= 1;
_ = new() <= 1;
_ = new() == 1;
_ = new() != 1;
_ = new() && 1;
_ = new() || 1;
_ = new() ?? 1;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,13): error CS8310: Operator '+' cannot be applied to operand 'new()'
// _ = new() + 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() + 1").WithArguments("+", "new()").WithLocation(6, 13),
// (7,13): error CS8310: Operator '-' cannot be applied to operand 'new()'
// _ = new() - 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() - 1").WithArguments("-", "new()").WithLocation(7, 13),
// (8,13): error CS8310: Operator '&' cannot be applied to operand 'new()'
// _ = new() & 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() & 1").WithArguments("&", "new()").WithLocation(8, 13),
// (9,13): error CS8310: Operator '|' cannot be applied to operand 'new()'
// _ = new() | 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() | 1").WithArguments("|", "new()").WithLocation(9, 13),
// (10,13): error CS8310: Operator '^' cannot be applied to operand 'new()'
// _ = new() ^ 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() ^ 1").WithArguments("^", "new()").WithLocation(10, 13),
// (11,13): error CS8310: Operator '*' cannot be applied to operand 'new()'
// _ = new() * 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() * 1").WithArguments("*", "new()").WithLocation(11, 13),
// (12,13): error CS8310: Operator '/' cannot be applied to operand 'new()'
// _ = new() / 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() / 1").WithArguments("/", "new()").WithLocation(12, 13),
// (13,13): error CS8310: Operator '%' cannot be applied to operand 'new()'
// _ = new() % 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() % 1").WithArguments("%", "new()").WithLocation(13, 13),
// (14,13): error CS8310: Operator '>>' cannot be applied to operand 'new()'
// _ = new() >> 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() >> 1").WithArguments(">>", "new()").WithLocation(14, 13),
// (15,13): error CS8310: Operator '<<' cannot be applied to operand 'new()'
// _ = new() << 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() << 1").WithArguments("<<", "new()").WithLocation(15, 13),
// (16,13): error CS8310: Operator '>' cannot be applied to operand 'new()'
// _ = new() > 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() > 1").WithArguments(">", "new()").WithLocation(16, 13),
// (17,13): error CS8310: Operator '<' cannot be applied to operand 'new()'
// _ = new() < 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() < 1").WithArguments("<", "new()").WithLocation(17, 13),
// (18,13): error CS8310: Operator '>=' cannot be applied to operand 'new()'
// _ = new() >= 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() >= 1").WithArguments(">=", "new()").WithLocation(18, 13),
// (19,13): error CS8310: Operator '<=' cannot be applied to operand 'new()'
// _ = new() <= 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() <= 1").WithArguments("<=", "new()").WithLocation(19, 13),
// (20,13): error CS8310: Operator '==' cannot be applied to operand 'new()'
// _ = new() == 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == 1").WithArguments("==", "new()").WithLocation(20, 13),
// (21,13): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// _ = new() != 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != 1").WithArguments("!=", "new()").WithLocation(21, 13),
// (22,13): error CS8754: There is no target type for 'new()'
// _ = new() && 1;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(22, 13),
// (23,13): error CS8754: There is no target type for 'new()'
// _ = new() || 1;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(23, 13),
// (24,13): error CS8754: There is no target type for 'new()'
// _ = new() ?? 1;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(24, 13)
);
}
[Fact]
public void TestBinaryOperators03()
{
string source = @"
class C
{
static void Main()
{
_ = 1 + new();
_ = 1 - new();
_ = 1 & new();
_ = 1 | new();
_ = 1 ^ new();
_ = 1 * new();
_ = 1 / new();
_ = 1 % new();
_ = 1 >> new();
_ = 1 << new();
_ = 1 > new();
_ = 1 < new();
_ = 1 >= new();
_ = 1 <= new();
_ = 1 == new();
_ = 1 != new();
_ = 1 && new();
_ = 1 || new();
_ = 1 ?? new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,13): error CS8310: Operator '+' cannot be applied to operand 'new()'
// _ = 1 + new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 + new()").WithArguments("+", "new()").WithLocation(6, 13),
// (7,13): error CS8310: Operator '-' cannot be applied to operand 'new()'
// _ = 1 - new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 - new()").WithArguments("-", "new()").WithLocation(7, 13),
// (8,13): error CS8310: Operator '&' cannot be applied to operand 'new()'
// _ = 1 & new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 & new()").WithArguments("&", "new()").WithLocation(8, 13),
// (9,13): error CS8310: Operator '|' cannot be applied to operand 'new()'
// _ = 1 | new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 | new()").WithArguments("|", "new()").WithLocation(9, 13),
// (10,13): error CS8310: Operator '^' cannot be applied to operand 'new()'
// _ = 1 ^ new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 ^ new()").WithArguments("^", "new()").WithLocation(10, 13),
// (11,13): error CS8310: Operator '*' cannot be applied to operand 'new()'
// _ = 1 * new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 * new()").WithArguments("*", "new()").WithLocation(11, 13),
// (12,13): error CS8310: Operator '/' cannot be applied to operand 'new()'
// _ = 1 / new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 / new()").WithArguments("/", "new()").WithLocation(12, 13),
// (13,13): error CS8310: Operator '%' cannot be applied to operand 'new()'
// _ = 1 % new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 % new()").WithArguments("%", "new()").WithLocation(13, 13),
// (14,13): error CS8310: Operator '>>' cannot be applied to operand 'new()'
// _ = 1 >> new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 >> new()").WithArguments(">>", "new()").WithLocation(14, 13),
// (15,13): error CS8310: Operator '<<' cannot be applied to operand 'new()'
// _ = 1 << new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 << new()").WithArguments("<<", "new()").WithLocation(15, 13),
// (16,13): error CS8310: Operator '>' cannot be applied to operand 'new()'
// _ = 1 > new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 > new()").WithArguments(">", "new()").WithLocation(16, 13),
// (17,13): error CS8310: Operator '<' cannot be applied to operand 'new()'
// _ = 1 < new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 < new()").WithArguments("<", "new()").WithLocation(17, 13),
// (18,13): error CS8310: Operator '>=' cannot be applied to operand 'new()'
// _ = 1 >= new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 >= new()").WithArguments(">=", "new()").WithLocation(18, 13),
// (19,13): error CS8310: Operator '<=' cannot be applied to operand 'new()'
// _ = 1 <= new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 <= new()").WithArguments("<=", "new()").WithLocation(19, 13),
// (20,13): error CS8310: Operator '==' cannot be applied to operand 'new()'
// _ = 1 == new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 == new()").WithArguments("==", "new()").WithLocation(20, 13),
// (21,13): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// _ = 1 != new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 != new()").WithArguments("!=", "new()").WithLocation(21, 13),
// (22,18): error CS8754: There is no target type for 'new()'
// _ = 1 && new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(22, 18),
// (23,18): error CS8754: There is no target type for 'new()'
// _ = 1 || new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(23, 18),
// (24,13): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'new()'
// _ = 1 ?? new();
Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 ?? new()").WithArguments("??", "int", "new()").WithLocation(24, 13)
);
}
[Fact]
public void InForeach()
{
var text = @"
class C
{
static void Main()
{
foreach (int x in new()) { }
}
}";
var comp = CreateCompilation(text, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,27): error CS8754: There is no target type for 'new()'
// foreach (int x in new()) { }
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 27)
);
}
[Fact]
public void Query()
{
string source =
@"using System.Linq;
static class C
{
static void Main()
{
var q = from x in new() select x;
var p = from x in new int[] { 1 } select new();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (6,27): error CS8754: There is no target type for 'new()'
// var q = from x in new() select x;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 27),
// (7,43): error CS1942: The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'.
// var p = from x in new int[] { 1 } select new();
Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailed, "select").WithArguments("select", "Select").WithLocation(7, 43)
);
}
[Fact]
public void InIsOperator()
{
var text = @"
class C
{
void M()
{
bool v1 = new() is long;
bool v2 = new() is string;
bool v3 = new() is new();
bool v4 = v1 is new();
bool v5 = this is new();
}
}";
var comp = CreateCompilation(text, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (6,19): error CS8754: There is no target type for 'new()'
// bool v1 = new() is long;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 19),
// (7,19): error CS8754: There is no target type for 'new()'
// bool v2 = new() is string;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 19),
// (8,19): error CS8754: There is no target type for 'new()'
// bool v3 = new() is new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(8, 19),
// (10,27): error CS0150: A constant value is expected
// bool v5 = this is new();
Diagnostic(ErrorCode.ERR_ConstantExpected, "new()").WithLocation(10, 27)
);
}
[Fact]
public void InNullCoalescing()
{
var text =
@"using System;
class Program
{
static void Main()
{
Func<object> f = () => new() ?? ""hello"";
}
}";
var comp = CreateCompilation(text).VerifyDiagnostics(
// (7,32): error CS8754: There is no target type for 'new()'
// Func<object> f = () => new() ?? "hello";
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 32)
);
}
[Fact]
public void Lambda()
{
string source = @"
class C
{
static void Main()
{
System.Console.Write(M()());
}
static System.Func<C> M()
{
return () => new();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
}
[Fact]
public void TestTupleEquality01()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.Write(new() == (1, 2L) ? 1 : 0);
Console.Write(new() != (1, 2L) ? 1 : 0);
Console.Write((1, 2L) == new() ? 1 : 0);
Console.Write((1, 2L) != new() ? 1 : 0);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (7,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write(new() == (1, 2L) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == (1, 2L)").WithArguments("==", "new()").WithLocation(7, 23),
// (8,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write(new() != (1, 2L) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != (1, 2L)").WithArguments("!=", "new()").WithLocation(8, 23),
// (9,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write((1, 2L) == new() ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(1, 2L) == new()").WithArguments("==", "new()").WithLocation(9, 23),
// (10,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write((1, 2L) != new() ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(1, 2L) != new()").WithArguments("!=", "new()").WithLocation(10, 23)
);
}
[Fact]
public void TestTupleEquality02()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.Write((new(), new()) == (1, 2L) ? 1 : 0);
Console.Write((new(), new()) != (1, 2L) ? 1 : 0);
Console.Write((1, 2L) == (new(), new()) ? 1 : 0);
Console.Write((1, 2L) != (new(), new()) ? 1 : 0);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (8,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write((new(), new()) == (1, 2L) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(new(), new()) == (1, 2L)").WithArguments("==", "new()").WithLocation(8, 23),
// (8,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write((new(), new()) == (1, 2L) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(new(), new()) == (1, 2L)").WithArguments("==", "new()").WithLocation(8, 23),
// (9,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write((new(), new()) != (1, 2L) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(new(), new()) != (1, 2L)").WithArguments("!=", "new()").WithLocation(9, 23),
// (9,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write((new(), new()) != (1, 2L) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(new(), new()) != (1, 2L)").WithArguments("!=", "new()").WithLocation(9, 23),
// (10,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write((1, 2L) == (new(), new()) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(1, 2L) == (new(), new())").WithArguments("==", "new()").WithLocation(10, 23),
// (10,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write((1, 2L) == (new(), new()) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(1, 2L) == (new(), new())").WithArguments("==", "new()").WithLocation(10, 23),
// (11,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write((1, 2L) != (new(), new()) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(1, 2L) != (new(), new())").WithArguments("!=", "new()").WithLocation(11, 23),
// (11,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write((1, 2L) != (new(), new()) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(1, 2L) != (new(), new())").WithArguments("!=", "new()").WithLocation(11, 23)
);
}
[Fact]
public void TestEquality_Class()
{
string source = @"
using System;
class C
{
static void Main()
{
Console.Write(new C() == new() ? 1 : 0);
Console.Write(new C() != new() ? 1 : 0);
Console.Write(new() == new C() ? 1 : 0);
Console.Write(new() != new C() ? 1 : 0);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (8,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write(new C() == new() ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new C() == new()").WithArguments("==", "new()").WithLocation(8, 23),
// (9,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write(new C() != new() ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new C() != new()").WithArguments("!=", "new()").WithLocation(9, 23),
// (10,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write(new() == new C() ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == new C()").WithArguments("==", "new()").WithLocation(10, 23),
// (11,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write(new() != new C() ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != new C()").WithArguments("!=", "new()").WithLocation(11, 23)
);
}
[Fact]
public void TestEquality_Class_UserDefinedOperator()
{
string source = @"
#pragma warning disable CS0660, CS0661
using System;
class D
{
}
class C
{
public static bool operator ==(C o1, C o2) => default;
public static bool operator !=(C o1, C o2) => default;
public static bool operator ==(C o1, D o2) => default;
public static bool operator !=(C o1, D o2) => default;
static void Main()
{
Console.WriteLine(new C() == new());
Console.WriteLine(new() == new C());
Console.WriteLine(new C() != new());
Console.WriteLine(new() != new C());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (18,27): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.WriteLine(new C() == new());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new C() == new()").WithArguments("==", "new()").WithLocation(18, 27),
// (19,27): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.WriteLine(new() == new C());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == new C()").WithArguments("==", "new()").WithLocation(19, 27),
// (20,27): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.WriteLine(new C() != new());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new C() != new()").WithArguments("!=", "new()").WithLocation(20, 27),
// (21,27): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.WriteLine(new() != new C());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != new C()").WithArguments("!=", "new()").WithLocation(21, 27)
);
}
[Fact]
public void TestEquality_Struct()
{
string source = @"
using System;
struct S
{
static void Main()
{
Console.WriteLine(new S() == new());
Console.WriteLine(new() == new S());
Console.WriteLine(new S() != new());
Console.WriteLine(new() != new S());
Console.WriteLine(new S?() == new());
Console.WriteLine(new() == new S?());
Console.WriteLine(new S?() != new());
Console.WriteLine(new() != new S?());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (8,27): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.WriteLine(new S() == new());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S() == new()").WithArguments("==", "new()").WithLocation(8, 27),
// (9,27): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.WriteLine(new() == new S());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == new S()").WithArguments("==", "new()").WithLocation(9, 27),
// (10,27): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.WriteLine(new S() != new());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S() != new()").WithArguments("!=", "new()").WithLocation(10, 27),
// (11,27): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.WriteLine(new() != new S());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != new S()").WithArguments("!=", "new()").WithLocation(11, 27),
// (13,27): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.WriteLine(new S?() == new());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S?() == new()").WithArguments("==", "new()").WithLocation(13, 27),
// (14,27): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.WriteLine(new() == new S?());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == new S?()").WithArguments("==", "new()").WithLocation(14, 27),
// (15,27): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.WriteLine(new S?() != new());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S?() != new()").WithArguments("!=", "new()").WithLocation(15, 27),
// (16,27): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.WriteLine(new() != new S?());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != new S?()").WithArguments("!=", "new()").WithLocation(16, 27)
);
}
[Fact]
public void TestEquality_Struct_UserDefinedOperator()
{
string source = @"
#pragma warning disable CS0660, CS0661
using System;
struct S
{
public S(int i)
{
}
public static bool operator ==(S o1, S o2) => default;
public static bool operator !=(S o1, S o2) => default;
static void Main()
{
Console.WriteLine(new S(42) == new(42));
Console.WriteLine(new(42) == new S(42));
Console.WriteLine(new S(42) != new(42));
Console.WriteLine(new(42) != new S(42));
Console.WriteLine(new S?(new(42)) == new(42));
Console.WriteLine(new(42) == new S?(new(42)));
Console.WriteLine(new S?(new(42)) != new(42));
Console.WriteLine(new(42) != new S?(new(42)));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (16,27): error CS8310: Operator '==' cannot be applied to operand 'new(int)'
// Console.WriteLine(new S(42) == new(42));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S(42) == new(42)").WithArguments("==", "new(int)").WithLocation(16, 27),
// (17,27): error CS8310: Operator '==' cannot be applied to operand 'new(int)'
// Console.WriteLine(new(42) == new S(42));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new(42) == new S(42)").WithArguments("==", "new(int)").WithLocation(17, 27),
// (18,27): error CS8310: Operator '!=' cannot be applied to operand 'new(int)'
// Console.WriteLine(new S(42) != new(42));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S(42) != new(42)").WithArguments("!=", "new(int)").WithLocation(18, 27),
// (19,27): error CS8310: Operator '!=' cannot be applied to operand 'new(int)'
// Console.WriteLine(new(42) != new S(42));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new(42) != new S(42)").WithArguments("!=", "new(int)").WithLocation(19, 27),
// (21,27): error CS8310: Operator '==' cannot be applied to operand 'new(int)'
// Console.WriteLine(new S?(new(42)) == new(42));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S?(new(42)) == new(42)").WithArguments("==", "new(int)").WithLocation(21, 27),
// (22,27): error CS8310: Operator '==' cannot be applied to operand 'new(int)'
// Console.WriteLine(new(42) == new S?(new(42)));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new(42) == new S?(new(42))").WithArguments("==", "new(int)").WithLocation(22, 27),
// (23,27): error CS8310: Operator '!=' cannot be applied to operand 'new(int)'
// Console.WriteLine(new S?(new(42)) != new(42));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S?(new(42)) != new(42)").WithArguments("!=", "new(int)").WithLocation(23, 27),
// (24,27): error CS8310: Operator '!=' cannot be applied to operand 'new(int)'
// Console.WriteLine(new(42) != new S?(new(42)));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new(42) != new S?(new(42))").WithArguments("!=", "new(int)").WithLocation(24, 27)
);
}
[Fact]
public void ArraySize()
{
string source = @"
class C
{
static void Main()
{
var a = new int[new()];
System.Console.Write(a.Length);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "0");
}
[Fact]
public void TernaryOperator01()
{
string source = @"
class C
{
static void Main()
{
bool flag = true;
var x = flag ? new() : 1;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
}
[Fact]
public void TernaryOperator02()
{
string source = @"
class C
{
static void Main()
{
bool flag = true;
System.Console.Write(flag ? new() : new C());
System.Console.Write(flag ? new C() : new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CC");
}
[Fact]
public void TernaryOperator03()
{
string source = @"
class C
{
static void Main()
{
bool flag = true;
System.Console.Write(flag ? new() : new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (7,24): error CS0121: The call is ambiguous between the following methods or properties: 'Console.Write(bool)' and 'Console.Write(char)'
// System.Console.Write(flag ? new() : new());
Diagnostic(ErrorCode.ERR_AmbigCall, "Write").WithArguments("System.Console.Write(bool)", "System.Console.Write(char)").WithLocation(7, 24)
);
}
[Fact]
public void NotAType()
{
string source = @"
class C
{
static void Main()
{
((System)new()).ToString();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,11): error CS0118: 'System' is a namespace but is used like a type
// ((System)new()).ToString();
Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "type").WithLocation(6, 11)
);
}
[Fact]
public void TestSpeculativeModel01()
{
string source = @"
class C
{
static void Main()
{
int i = 2;
}
}
";
var comp = CreateCompilation(source, parseOptions: ImplicitObjectCreationTestOptions);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var node = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single();
int nodeLocation = node.Location.SourceSpan.Start;
var newExpression = SyntaxFactory.ParseExpression("new()");
var typeInfo = model.GetSpeculativeTypeInfo(nodeLocation, newExpression, SpeculativeBindingOption.BindAsExpression);
Assert.Null(typeInfo.Type);
var symbolInfo = model.GetSpeculativeSymbolInfo(nodeLocation, newExpression, SpeculativeBindingOption.BindAsExpression);
Assert.True(symbolInfo.IsEmpty);
}
[Fact]
public void TestSpeculativeModel02()
{
string source = @"
class C
{
static void M(int i) {}
static void Main()
{
M(42);
}
}
";
var comp = CreateCompilation(source, parseOptions: ImplicitObjectCreationTestOptions);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var node = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ExpressionStatementSyntax>().Single();
int nodeLocation = node.Location.SourceSpan.Start;
var modifiedNode = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement("M(new());", options: ImplicitObjectCreationTestOptions);
Assert.False(modifiedNode.HasErrors);
bool success = model.TryGetSpeculativeSemanticModel(nodeLocation, modifiedNode, out var speculativeModel);
Assert.True(success);
Assert.NotNull(speculativeModel);
var newExpression = ((InvocationExpressionSyntax)modifiedNode.Expression).ArgumentList.Arguments[0].Expression;
var symbolInfo = speculativeModel.GetSymbolInfo(newExpression);
Assert.Equal("System.Int32..ctor()", symbolInfo.Symbol.ToTestDisplayString());
var typeInfo = speculativeModel.GetTypeInfo(newExpression);
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
}
[Fact]
public void TestInOverloadWithIllegalConversion()
{
var source = @"
class C
{
public static void Main()
{
M(new());
M(array: new());
}
static void M(int[] array) { }
static void M(int i) { }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(int[])' and 'C.M(int)'
// M(new());
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(int[])", "C.M(int)").WithLocation(6, 9),
// (7,18): error CS8752: The type 'int[]' may not be used as the target type of new()
// M(array: new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new()").WithArguments("int[]").WithLocation(7, 18)
);
}
[Fact]
public void TestInOverloadWithUseSiteError()
{
var missing = @"public class Missing { }";
var missingComp = CreateCompilation(missing, assemblyName: "missing");
var lib = @"
public class C
{
public void M(Missing m) { }
public void M(C c) { }
}";
var libComp = CreateCompilation(lib, references: new[] { missingComp.EmitToImageReference() });
var source = @"
class D
{
public void M2(C c)
{
c.M(new());
c.M(default);
c.M(null);
}
}
";
var comp = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() });
comp.VerifyDiagnostics(
// (6,9): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// c.M(new());
Diagnostic(ErrorCode.ERR_NoTypeDef, "c.M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 9),
// (7,9): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// c.M(default);
Diagnostic(ErrorCode.ERR_NoTypeDef, "c.M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 9),
// (8,9): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// c.M(null);
Diagnostic(ErrorCode.ERR_NoTypeDef, "c.M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 9)
);
}
[Fact]
public void TestInConstructorOverloadWithUseSiteError()
{
var missing = @"public class Missing { }";
var missingComp = CreateCompilation(missing, assemblyName: "missing");
var lib = @"
public class C
{
public C(Missing m) => throw null;
public C(D d) => throw null;
}
public class D { }
";
var libComp = CreateCompilation(lib, references: new[] { missingComp.EmitToImageReference() });
var source = @"
class D
{
public void M()
{
new C(new());
new C(default);
new C(null);
C c = new(null);
}
}
";
var comp = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() });
comp.VerifyDiagnostics(
// (6,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// new C(new());
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 13),
// (7,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// new C(default);
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 13),
// (8,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// new C(null);
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 13),
// (9,15): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// C c = new(null);
Diagnostic(ErrorCode.ERR_NoTypeDef, "new(null)").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 15)
);
}
[Fact]
public void ImplicitObjectCreationHasUseSiteError()
{
var missing = @"public class Missing { }";
var missingComp = CreateCompilation(missing, assemblyName: "missing");
var lib = @"
public class C
{
public static void M(Missing m) => throw null;
}
";
var libComp = CreateCompilation(lib, references: new[] { missingComp.EmitToImageReference() });
libComp.VerifyDiagnostics();
var source = @"
class D
{
public void M2()
{
C.M(new());
}
}
";
var comp = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() });
comp.VerifyDiagnostics(
// (6,9): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// C.M(new());
Diagnostic(ErrorCode.ERR_NoTypeDef, "C.M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 9)
);
}
[Fact]
public void ArgumentOfImplicitObjectCreationHasUseSiteError()
{
var missing = @"public class Missing { }";
var missingComp = CreateCompilation(missing, assemblyName: "missing");
var lib = @"
public class C
{
public C(Missing m) => throw null;
}
";
var libComp = CreateCompilation(lib, references: new[] { missingComp.EmitToImageReference() });
libComp.VerifyDiagnostics();
var source = @"
class D
{
public void M(C c) { }
public void M2()
{
M(new(null));
}
}
";
var comp = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() });
comp.VerifyDiagnostics(
// (7,11): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// M(new(null));
Diagnostic(ErrorCode.ERR_NoTypeDef, "new(null)").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 11)
);
}
[Fact]
public void UseSiteWarning()
{
var signedDll = TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2);
var libBTemplate = @"
[assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")]
public class B {{ }}
";
var libBv1 = CreateCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: signedDll);
var libBv2 = CreateCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: signedDll);
var libASource = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")]
public class A
{
public void M(B b) { }
public void M(string s) { }
}
";
var libAv1 = CreateCompilation(
libASource,
new[] { new CSharpCompilationReference(libBv1) },
assemblyName: "A",
options: signedDll);
var source = @"
public class Source
{
public void Test(A a)
{
a.M(new());
a.M(default);
a.M(null);
}
}
";
var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) },
parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1),
// (6,11): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(B)' and 'A.M(string)'
// a.M(new());
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(B)", "A.M(string)").WithLocation(6, 11),
// warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1),
// (7,11): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(B)' and 'A.M(string)'
// a.M(default);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(B)", "A.M(string)").WithLocation(7, 11),
// warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1),
// (8,11): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(B)' and 'A.M(string)'
// a.M(null);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(B)", "A.M(string)").WithLocation(8, 11)
);
}
[Fact, WorkItem(49547, "https://github.com/dotnet/roslyn/issues/49547")]
public void CallerMemberNameAttributeWithImplicitObjectCreation()
{
string source = @"
using System;
using System.Runtime.CompilerServices;
class Test
{
public string Caller { get; set; }
public Test([CallerMemberName] string caller = ""?"") => Caller = caller;
public void PrintCaller() => Console.WriteLine(Caller);
}
class Program
{
static void Main()
{
Test f1 = new Test();
f1.PrintCaller();
Test f2 = new();
f2.PrintCaller();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput:
@"Main
Main").VerifyDiagnostics();
}
[Fact]
public void CallerLineNumberAttributeWithImplicitObjectCreation()
{
string source = @"
using System;
using System.Runtime.CompilerServices;
class Test
{
public int LineNumber { get; set; }
public Test([CallerLineNumber] int lineNumber = -1) => LineNumber = lineNumber;
public void PrintLineNumber() => Console.WriteLine(LineNumber);
}
class Program
{
static void Main()
{
Test f1 = new Test();
f1.PrintLineNumber();
Test f2 = new();
f2.PrintLineNumber();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput:
@"16
19").VerifyDiagnostics();
}
[Fact]
[WorkItem(50030, "https://github.com/dotnet/roslyn/issues/50030")]
public void GetCollectionInitializerSymbolInfo()
{
var source = @"
using System;
using System.Collections.Generic;
class X : List<int>
{
new void Add(int x) { }
void Add(string x) {}
static void Main()
{
X z = new() { String.Empty, 12 };
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
where node.IsKind(SyntaxKind.CollectionInitializerExpression)
select (InitializerExpressionSyntax)node).Single().Expressions;
SymbolInfo symbolInfo;
symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(nodes[0]);
Assert.NotNull(symbolInfo.Symbol);
Assert.Equal("void X.Add(System.String x)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(nodes[1]);
Assert.NotNull(symbolInfo.Symbol);
Assert.Equal("void X.Add(System.Int32 x)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
}
[Fact]
public void GetNamedParameterSymbolInfo()
{
var source = @"
class X
{
X(int aParameter)
{}
static void Main()
{
X z = new(aParameter: 1);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "aParameter").Single();
SymbolInfo symbolInfo;
symbolInfo = semanticModel.GetSymbolInfo(node);
Assert.NotNull(symbolInfo.Symbol);
Assert.Equal("System.Int32 aParameter", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
}
[Fact]
[WorkItem(50489, "https://github.com/dotnet/roslyn/issues/50489")]
public void InEarlyWellknownAttribute_01()
{
var source1 = @"
public class C
{
static void Main()
{
M1();
M2();
}
[System.Obsolete(""reported 1"", new bool())]
static public void M1()
{
}
[System.Obsolete(""reported 2"", new())]
static public void M2()
{
}
}";
var compilation1 = CreateCompilation(source1);
compilation1.VerifyDiagnostics(
// (6,9): warning CS0618: 'C.M1()' is obsolete: 'reported 1'
// M1();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "M1()").WithArguments("C.M1()", "reported 1").WithLocation(6, 9),
// (7,9): warning CS0618: 'C.M2()' is obsolete: 'reported 2'
// M2();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "M2()").WithArguments("C.M2()", "reported 2").WithLocation(7, 9)
);
var source2 = @"
public class B
{
static void Main()
{
C.M1();
C.M2();
}
}";
var compilation2 = CreateCompilation(source2, references: new[] { compilation1.EmitToImageReference() });
compilation2.VerifyDiagnostics(
// (6,9): warning CS0618: 'C.M1()' is obsolete: 'reported 1'
// C.M1();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "C.M1()").WithArguments("C.M1()", "reported 1").WithLocation(6, 9),
// (7,9): warning CS0618: 'C.M2()' is obsolete: 'reported 2'
// C.M2();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "C.M2()").WithArguments("C.M2()", "reported 2").WithLocation(7, 9)
);
}
[Fact]
public void InEarlyWellknownAttribute_02()
{
var source1 = @"
using System.Runtime.InteropServices;
public class C
{
public void M1([DefaultParameterValue(new())] object o)
{
}
public void M2([DefaultParameterValue(new object())] object o)
{
}
}
";
var compilation1 = CreateCompilation(source1);
compilation1.VerifyDiagnostics(
// (6,43): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// public void M1([DefaultParameterValue(new())] object o)
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new()").WithLocation(6, 43),
// (10,43): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// public void M2([DefaultParameterValue(new object())] object o)
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new object()").WithLocation(10, 43)
);
}
[Fact]
public void InEarlyWellknownAttribute_03()
{
var source1 = @"
using System;
[AttributeUsage(new AttributeTargets())]
public class Attr1 : Attribute {}
[AttributeUsage(new())]
public class Attr2 : Attribute {}
";
var compilation1 = CreateCompilation(source1);
compilation1.VerifyDiagnostics(
// (4,17): error CS0591: Invalid value for argument to 'AttributeUsage' attribute
// [AttributeUsage(new AttributeTargets())]
Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "new AttributeTargets()").WithArguments("AttributeUsage").WithLocation(4, 17),
// (7,17): error CS0591: Invalid value for argument to 'AttributeUsage' attribute
// [AttributeUsage(new())]
Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "new()").WithArguments("AttributeUsage").WithLocation(7, 17)
);
}
[Fact]
public void InAttributes()
{
var source = @"
[C(new())]
public class C : System.Attribute
{
public C(C c) {}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (2,2): error CS0181: Attribute constructor parameter 'c' has type 'C', which is not a valid attribute parameter type
// [C(new())]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "C").WithArguments("c", "C").WithLocation(2, 2),
// (2,4): error CS7036: There is no argument given that corresponds to the required formal parameter 'c' of 'C.C(C)'
// [C(new())]
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "new()").WithArguments("c", "C.C(C)").WithLocation(2, 4)
);
}
[Fact, WorkItem(54193, "https://github.com/dotnet/roslyn/issues/54193")]
public void InSwitchExpression()
{
var source = @"
using static System.Console;
var c0 = 0 switch { 1 => new C(), int n => new() { n = n } };
C c1 = 1 switch { int n => new() { n = n } };
C c2 = 2 switch { int n => n switch { int u => new() { n = n + u } } };
Write(c0.n);
Write(c1.n);
Write(c2.n);
class C
{
public int n;
}
";
var compilation = CreateCompilation(source);
CompileAndVerify(compilation, expectedOutput: "014")
.VerifyDiagnostics();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class ImplicitObjectCreationTests : CSharpTestBase
{
private static readonly CSharpParseOptions ImplicitObjectCreationTestOptions = TestOptions.Regular9;
private static CSharpCompilation CreateCompilation(string source, CSharpCompilationOptions options = null, IEnumerable<MetadataReference> references = null)
{
return CSharpTestBase.CreateCompilation(source, options: options, parseOptions: ImplicitObjectCreationTestOptions, references: references);
}
[Fact]
public void TestInLocal()
{
var source = @"
using System;
struct S
{
}
class C
{
public static void Main()
{
C v1 = new();
S v2 = new();
S? v3 = new();
Console.Write(v1);
Console.Write(v2);
Console.Write(v3);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CSS");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
assert(0, type: "C", convertedType: "C", symbol: "C..ctor()", ConversionKind.Identity);
assert(1, type: "S", convertedType: "S", symbol: "S..ctor()", ConversionKind.Identity);
assert(2, type: "S", convertedType: "S?", symbol: "S..ctor()", ConversionKind.ImplicitNullable);
void assert(int index, string type, string convertedType, string symbol, ConversionKind conversionKind)
{
var @new = nodes[index];
Assert.Equal(type, model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal(symbol, model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(conversionKind, model.GetConversion(@new).Kind);
}
}
[Fact]
public void TestInLocal_LangVersion8()
{
var source = @"
struct S
{
}
class C
{
public static void Main()
{
C v1 = new();
S v2 = new();
S? v3 = new();
C v4 = new(missing);
S v5 = new(missing);
S? v6 = new(missing);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (10,16): error CS8400: Feature 'target-typed object creation' is not available in C# 8.0. Please use language version 9.0 or greater.
// C v1 = new();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new").WithArguments("target-typed object creation", "9.0").WithLocation(10, 16),
// (11,16): error CS8400: Feature 'target-typed object creation' is not available in C# 8.0. Please use language version 9.0 or greater.
// S v2 = new();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new").WithArguments("target-typed object creation", "9.0").WithLocation(11, 16),
// (12,17): error CS8400: Feature 'target-typed object creation' is not available in C# 8.0. Please use language version 9.0 or greater.
// S? v3 = new();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new").WithArguments("target-typed object creation", "9.0").WithLocation(12, 17),
// (13,16): error CS8400: Feature 'target-typed object creation' is not available in C# 8.0. Please use language version 9.0 or greater.
// C v4 = new(missing);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new").WithArguments("target-typed object creation", "9.0").WithLocation(13, 16),
// (13,20): error CS0103: The name 'missing' does not exist in the current context
// C v4 = new(missing);
Diagnostic(ErrorCode.ERR_NameNotInContext, "missing").WithArguments("missing").WithLocation(13, 20),
// (14,16): error CS8400: Feature 'target-typed object creation' is not available in C# 8.0. Please use language version 9.0 or greater.
// S v5 = new(missing);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new").WithArguments("target-typed object creation", "9.0").WithLocation(14, 16),
// (14,20): error CS0103: The name 'missing' does not exist in the current context
// S v5 = new(missing);
Diagnostic(ErrorCode.ERR_NameNotInContext, "missing").WithArguments("missing").WithLocation(14, 20),
// (15,17): error CS8400: Feature 'target-typed object creation' is not available in C# 8.0. Please use language version 9.0 or greater.
// S? v6 = new(missing);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new").WithArguments("target-typed object creation", "9.0").WithLocation(15, 17),
// (15,21): error CS0103: The name 'missing' does not exist in the current context
// S? v6 = new(missing);
Diagnostic(ErrorCode.ERR_NameNotInContext, "missing").WithArguments("missing").WithLocation(15, 21)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
assert(0, type: "C", convertedType: "C", symbol: "C..ctor()", ConversionKind.Identity);
assert(1, type: "S", convertedType: "S", symbol: "S..ctor()", ConversionKind.Identity);
assert(2, type: "S", convertedType: "S?", symbol: "S..ctor()", ConversionKind.ImplicitNullable);
void assert(int index, string type, string convertedType, string symbol, ConversionKind conversionKind)
{
var @new = nodes[index];
Assert.Equal(type, model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal(symbol, model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(conversionKind, model.GetConversion(@new).Kind);
}
}
[Fact]
public void TestInExpressionTree()
{
var source = @"
using System;
using System.Linq.Expressions;
struct S
{
}
class C
{
public static void Main()
{
Expression<Func<C>> expr1 = () => new();
Expression<Func<S>> expr2 = () => new();
Expression<Func<S?>> expr3 = () => new();
Console.Write(expr1.Compile()());
Console.Write(expr2.Compile()());
Console.Write(expr3.Compile()());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CSS");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
assert(0, type: "C", convertedType: "C", symbol: "C..ctor()", ConversionKind.Identity);
assert(1, type: "S", convertedType: "S", symbol: "S..ctor()", ConversionKind.Identity);
assert(2, type: "S", convertedType: "S?", symbol: "S..ctor()", ConversionKind.ImplicitNullable);
void assert(int index, string type, string convertedType, string symbol, ConversionKind conversionKind)
{
var @new = nodes[index];
Assert.Equal(type, model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal(symbol, model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(conversionKind, model.GetConversion(@new).Kind);
}
}
[Fact]
public void TestInParameterDefaultValue()
{
var source = @"
struct S
{
}
class C
{
void M(
C p1 = new(),
S p2 = new(), // ok
S? p3 = new(),
int p4 = new(), // ok
bool? p5 = new() // ok
)
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,16): error CS1736: Default parameter value for 'p1' must be a compile-time constant
// C p1 = new(),
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new()").WithArguments("p1").WithLocation(9, 16),
// (11,17): error CS1736: Default parameter value for 'p3' must be a compile-time constant
// S? p3 = new()
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new()").WithArguments("p3").WithLocation(11, 17)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
assert(0, type: "C", convertedType: "C", symbol: "C..ctor()", constant: null, ConversionKind.Identity);
assert(1, type: "S", convertedType: "S", symbol: "S..ctor()", constant: null, ConversionKind.Identity);
assert(2, type: "S", convertedType: "S?", symbol: "S..ctor()", constant: null, ConversionKind.ImplicitNullable);
assert(3, type: "System.Int32", convertedType: "System.Int32", symbol: "System.Int32..ctor()", constant: "0", ConversionKind.Identity);
assert(4, type: "System.Boolean", convertedType: "System.Boolean?", symbol: "System.Boolean..ctor()", constant: "False", ConversionKind.ImplicitNullable);
void assert(int index, string type, string convertedType, string symbol, string constant, ConversionKind conversionKind)
{
var @new = nodes[index];
Assert.Equal(type, model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal(symbol, model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(conversionKind, model.GetConversion(@new).Kind);
Assert.Equal(constant, model.GetConstantValue(@new).Value?.ToString());
}
}
[Fact]
public void TestArguments_Out()
{
var source = @"
using System;
class C
{
public int j;
public C(out int i)
{
i = 2;
}
public static void Main()
{
C c = new(out var i) { j = i };
Console.Write(c.j);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "2");
}
[Fact]
public void TestArguments_Params()
{
var source = @"
using System;
class C
{
public C(params int[] p)
{
foreach (var item in p)
{
Console.Write(item);
}
}
public static void Main()
{
C c = new(1, 2, 3);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "123");
}
[Fact]
public void TestArguments_NonTrailingNamedArgs()
{
var source = @"
using System;
class C
{
public C(object c, object o) => Console.Write(1);
public C(int i, object o) => Console.Write(2);
public static void Main()
{
C c = new(c: new(), 2);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "1");
}
[Fact]
public void TestArguments_DynamicArgs()
{
var source = @"
using System;
class C
{
readonly int field;
public C(int field)
{
this.field = field;
}
public C(dynamic c)
{
Console.Write(c.field);
}
public static void Main()
{
dynamic d = 5;
C c = new(new C(d));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe, references: new[] { CSharpRef });
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "5");
}
[Fact]
public void TestInDynamicInvocation()
{
var source = @"
class C
{
public void M(int i) {}
public static void Main()
{
dynamic d = new C();
d.M(new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe, references: new[] { CSharpRef });
comp.VerifyDiagnostics(
// (9,13): error CS8754: There is no target type for 'new()'
// d.M(new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(9, 13)
);
}
[Fact]
public void TestInAsOperator()
{
var source = @"
using System;
struct S
{
}
class C
{
public void M<TClass, TNew>()
where TClass : class
where TNew : new()
{
Console.Write(new() as C);
Console.Write(new() as S?);
Console.Write(new() as TClass);
Console.Write(new() as TNew);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (14,23): error CS8754: There is no target type for 'new()'
// Console.Write(new() as C);
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(14, 23),
// (15,23): error CS8754: There is no target type for 'new()'
// Console.Write(new() as S?);
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(15, 23),
// (16,23): error CS8754: There is no target type for 'new()'
// Console.Write(new() as TClass);
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(16, 23),
// (17,23): error CS8754: There is no target type for 'new()'
// Console.Write(new() as TNew);
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(17, 23)
);
}
[Fact]
public void TestInTupleElement()
{
var source = @"
using System;
class C
{
static void M<T>((T a, T b) t, T c) => Console.Write(t);
public static void Main()
{
M((new(), new()), new C());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "(C, C)");
}
[Fact]
public void TestTargetType_Var()
{
var source = @"
class C
{
void M()
{
var x = new(2, 3);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,17): error CS8754: There is no target type for 'new(int, int)'
// var x = new(5);
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new(2, 3)").WithArguments("new(int, int)").WithLocation(6, 17)
);
}
[Fact]
public void TestTargetType_Discard()
{
var source = @"
class C
{
void M()
{
_ = new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,13): error CS8754: There is no target type for 'new()'
// _ = new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 13)
);
}
[Fact]
public void TestTargetType_Delegate()
{
var source = @"
delegate void D();
class C
{
void M()
{
D x0 = new();
D x1 = new(M); // ok
var x2 = (D)new();
var x3 = (D)new(M); // ok
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,16): error CS1729: 'D' does not contain a constructor that takes 0 arguments
// D x0 = new();
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("D", "0").WithLocation(7, 16),
// (9,21): error CS1729: 'D' does not contain a constructor that takes 0 arguments
// var x2 = (D)new();
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("D", "0").WithLocation(9, 21)
);
}
[Fact]
public void TestTargetType_Static()
{
var source = @"
public static class C {
static void M(object c) {
_ = (C)(new());
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,13): error CS0716: Cannot convert to static type 'C'
// _ = (C)(new());
Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)(new())").WithArguments("C").WithLocation(4, 13),
// (4,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments
// _ = (C)(new());
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("C", "0").WithLocation(4, 17)
);
}
[Fact]
public void TestTargetType_Abstract()
{
var source = @"
abstract class C
{
void M()
{
C x0 = new();
var x1 = (C)new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,16): error CS0144: Cannot create an instance of the abstract type or interface 'C'
// C x0 = new();
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(6, 16),
// (7,21): error CS0144: Cannot create an instance of the abstract type or interface 'C'
// var x1 = (C)new();
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(7, 21)
);
}
[Fact]
public void TestTargetType_Interface()
{
var source = @"
interface I {}
class C
{
void M()
{
I x0 = new();
var x1 = (I)new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,16): error CS0144: Cannot create an instance of the abstract type or interface 'I'
// I x0 = new();
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("I").WithLocation(7, 16),
// (8,21): error CS0144: Cannot create an instance of the abstract type or interface 'I'
// var x1 = (I)new();
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("I").WithLocation(8, 21)
);
}
[Fact]
public void TestTargetType_Enum()
{
var source = @"
using System;
enum E {}
class C
{
static void Main()
{
E x0 = new();
var x1 = (E)new();
Console.Write(x0);
Console.Write(x1);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "00");
}
[Fact]
public void TestTargetType_Primitive()
{
var source = @"
class C
{
void M()
{
int x0 = new();
var x1 = (int)new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,13): warning CS0219: The variable 'x0' is assigned but its value is never used
// int x0 = new();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x0").WithArguments("x0").WithLocation(6, 13),
// (7,13): warning CS0219: The variable 'x1' is assigned but its value is never used
// var x1 = (int)new();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(7, 13)
);
}
[Fact]
public void TestTargetType_TupleType()
{
var source = @"
#pragma warning disable 0219
class C
{
void M()
{
(int, int) x0 = new();
var x1 = ((int, int))new();
(int, C) x2 = new();
var x3 = ((int, C))new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void TestTargetType_ValueTuple()
{
var source = @"
using System;
class C
{
void M()
{
ValueTuple<int, int> x0 = new();
ValueTuple<int, int> x1 = new(2, 3);
var x2 = (ValueTuple<int, int>)new();
var x3 = (ValueTuple<int, int>)new(2, 3);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,30): warning CS0219: The variable 'x0' is assigned but its value is never used
// ValueTuple<int, int> x0 = new();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x0").WithArguments("x0").WithLocation(7, 30),
// (9,13): warning CS0219: The variable 'x2' is assigned but its value is never used
// var x2 = (ValueTuple<int, int>)new();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(9, 13)
);
}
[Fact]
public void TestTypeParameter()
{
var source = @"
using System;
struct S
{
static void M1<T>() where T : struct
{
Console.Write((T)new());
}
static void M2<T>() where T : new()
{
Console.Write((T)new());
}
public static void Main()
{
M1<S>();
M2<S>();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "SS");
}
[Fact]
public void TestTypeParameter_ErrorCases()
{
var source = @"
class C
{
void M<T, TClass, TStruct, TNew>()
where TClass : class
where TStruct : struct
where TNew : new()
{
{
T x0 = new();
var x1 = (T)new();
}
{
TClass x0 = new();
var x1 = (TClass)new();
}
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (10,20): error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint
// T x0 = new();
Diagnostic(ErrorCode.ERR_NoNewTyvar, "new()").WithArguments("T").WithLocation(10, 20),
// (11,25): error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint
// var x1 = (T)new();
Diagnostic(ErrorCode.ERR_NoNewTyvar, "new()").WithArguments("T").WithLocation(11, 25),
// (14,25): error CS0304: Cannot create an instance of the variable type 'TClass' because it does not have the new() constraint
// TClass x0 = new();
Diagnostic(ErrorCode.ERR_NoNewTyvar, "new()").WithArguments("TClass").WithLocation(14, 25),
// (15,30): error CS0304: Cannot create an instance of the variable type 'TClass' because it does not have the new() constraint
// var x1 = (TClass)new();
Diagnostic(ErrorCode.ERR_NoNewTyvar, "new()").WithArguments("TClass").WithLocation(15, 30)
);
}
[Fact]
public void TestTargetType_ErrorType()
{
var source = @"
class C
{
void M()
{
Missing x0 = new();
var x1 = (Missing)new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?)
// Missing x0 = new();
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(6, 9),
// (7,19): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?)
// var x1 = (Missing)new();
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(7, 19)
);
}
[Fact]
public void TestTargetType_Pointer()
{
var source = @"
class C
{
unsafe void M()
{
int* x0 = new();
var x1 = (int*)new();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,19): error CS1919: Unsafe type 'int*' cannot be used in object creation
// int* x0 = new();
Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, "new()").WithArguments("int*").WithLocation(6, 19),
// (7,24): error CS1919: Unsafe type 'int*' cannot be used in object creation
// var x1 = (int*)new();
Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, "new()").WithArguments("int*").WithLocation(7, 24)
);
}
[Fact]
public void TestTargetType_AnonymousType()
{
var source = @"
class C
{
void M()
{
var x0 = new { };
x0 = new();
var x1 = new { X = 1 };
x1 = new(2);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,14): error CS8752: The type '<empty anonymous type>' may not be used as the target-type of 'new()'
// x0 = new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new()").WithArguments("<empty anonymous type>").WithLocation(7, 14),
// (9,14): error CS8752: The type '<anonymous type: int X>' may not be used as the target-type of 'new()'
// x1 = new(2);
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new(2)").WithArguments("<anonymous type: int X>").WithLocation(9, 14));
}
[Fact]
public void TestTargetType_CoClass_01()
{
var source = @"
using System;
using System.Runtime.InteropServices;
class CoClassType : InterfaceType { }
[ComImport, Guid(""00020810-0000-0000-C000-000000000046"")]
[CoClass(typeof(CoClassType))]
interface InterfaceType { }
public class Program
{
public static void Main()
{
InterfaceType a = new() { };
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
var @new = nodes[0];
Assert.Equal("InterfaceType", model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal("InterfaceType", model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal("CoClassType..ctor()", model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, model.GetConversion(@new).Kind);
}
[Fact]
public void TestTargetType_CoClass_02()
{
var source = @"
using System;
using System.Runtime.InteropServices;
public class GenericCoClassType<T, U> : NonGenericInterfaceType
{
public GenericCoClassType(U x) { }
}
[ComImport, Guid(""00020810-0000-0000-C000-000000000046"")]
[CoClass(typeof(GenericCoClassType<int, string>))]
public interface NonGenericInterfaceType
{
}
public class MainClass
{
public static int Main()
{
NonGenericInterfaceType a = new(""string"");
return 0;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
var @new = nodes[0];
Assert.Equal("NonGenericInterfaceType", model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal("NonGenericInterfaceType", model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal("GenericCoClassType<System.Int32, System.String>..ctor(System.String x)", model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, model.GetConversion(@new).Kind);
}
[Fact]
public void TestAmbiguousCall()
{
var source = @"
class C {
public C(object a, C b) {}
public C(C a, object b) {}
public static void Main()
{
C c = new(new(), new());
}
}
";
var comp = CreateCompilation(source).VerifyDiagnostics(
// (9,15): error CS0121: The call is ambiguous between the following methods or properties: 'C.C(object, C)' and 'C.C(C, object)'
// C c = new(new(), new());
Diagnostic(ErrorCode.ERR_AmbigCall, "new(new(), new())").WithArguments("C.C(object, C)", "C.C(C, object)").WithLocation(9, 15)
);
}
[Fact]
public void TestObjectAndCollectionInitializer()
{
var source = @"
using System;
using System.Collections.Generic;
class C
{
public C field;
public int i;
public C(int i) => this.i = i;
public C() {}
public static void Main()
{
Dictionary<C, List<int>> dict1 = new() { { new() { field = new(1) }, new() { 1, 2, 3 } } };
Dictionary<C, List<int>> dict2 = new() { [new() { field = new(2) }] = new() { 4, 5, 6 } };
Dump(dict1);
Dump(dict2);
}
static void Dump(Dictionary<C, List<int>> dict)
{
foreach (C key in dict.Keys)
{
Console.Write($""C({key.field.i}): "");
}
foreach (List<int> value in dict.Values)
{
Console.WriteLine(string.Join("", "", value));
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput:
@"C(1): 1, 2, 3
C(2): 4, 5, 6");
}
[Fact]
public void TestInClassInitializer()
{
var source = @"
using System;
class D
{
}
class C
{
public D field = new();
public D Property1 { get; } = new();
public D Property2 { get; set; } = new();
public static void Main()
{
C c = new();
Console.Write(c.field);
Console.Write(c.Property1);
Console.Write(c.Property2);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "DDD");
}
[Fact]
public void TestDataFlow()
{
var source = @"
using System;
class C
{
public int field;
public static void Main()
{
int i;
C c = new() { field = (i = 42) };
Console.Write(i);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact]
public void TestDotOff()
{
var source = @"
class C
{
public static void Main()
{
_ = (new()).field;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,13): error CS8754: There is no target type for 'new()'
// _ = (new()).field;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 13)
);
}
[Fact]
public void TestConditionalAccess()
{
var source = @"
using System;
class C
{
public static void Main()
{
Console.Write(((int?)new())?.ToString());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "0");
}
[Fact]
public void TestInaccessibleConstructor()
{
var source = @"
class D
{
private D() {}
}
class C
{
public static void Main()
{
D d = new();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (11,15): error CS0122: 'D.D()' is inaccessible due to its protection level
// D d = new();
Diagnostic(ErrorCode.ERR_BadAccess, "new()").WithArguments("D.D()").WithLocation(11, 15)
);
}
[Fact]
public void TestBadArgs()
{
var source = @"
class C
{
public static void Main()
{
C c = new(1);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,15): error CS1729: 'C' does not contain a constructor that takes 1 arguments
// C c = new(1);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new(1)").WithArguments("C", "1").WithLocation(6, 15)
);
}
[Fact]
public void TestNested()
{
var source = @"
using System;
class C
{
public C(C a, C b) => Console.Write(3);
public C(int i) => Console.Write(i);
public static void Main()
{
C x = new(new(1), new(2));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "123");
}
[Fact]
public void TestDeconstruction()
{
var source = @"
class C
{
public static void Main()
{
var (_, _) = new();
(var _, var _) = new();
(C _, C _) = new();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,22): error CS8754: There is no target type for 'new()'
// var (_, _) = new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 22),
// (6,22): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// var (_, _) = new();
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "new()").WithLocation(6, 22),
// (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable '_'.
// var (_, _) = new();
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "_").WithArguments("_").WithLocation(6, 14),
// (6,14): error CS8183: Cannot infer the type of implicitly-typed discard.
// var (_, _) = new();
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(6, 14),
// (6,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable '_'.
// var (_, _) = new();
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "_").WithArguments("_").WithLocation(6, 17),
// (6,17): error CS8183: Cannot infer the type of implicitly-typed discard.
// var (_, _) = new();
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(6, 17),
// (7,26): error CS8754: There is no target type for 'new()'
// (var _, var _) = new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 26),
// (7,26): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// (var _, var _) = new();
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "new()").WithLocation(7, 26),
// (7,10): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable '_'.
// (var _, var _) = new();
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "var _").WithArguments("_").WithLocation(7, 10),
// (7,10): error CS8183: Cannot infer the type of implicitly-typed discard.
// (var _, var _) = new();
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(7, 10),
// (7,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable '_'.
// (var _, var _) = new();
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "var _").WithArguments("_").WithLocation(7, 17),
// (7,17): error CS8183: Cannot infer the type of implicitly-typed discard.
// (var _, var _) = new();
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(7, 17),
// (8,22): error CS8754: There is no target type for 'new()'
// (C _, C _) = new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(8, 22),
// (8,22): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// (C _, C _) = new();
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "new()").WithLocation(8, 22)
);
}
[Fact]
public void TestBestType_NullCoalescing()
{
var source = @"
using System;
class C
{
public static void Main()
{
C c = null;
Console.Write(c ?? new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
}
[Fact]
public void TestBestType_Lambda()
{
var source = @"
using System;
class C
{
public static void M<T>(Func<bool, T> f)
{
Console.Write(f(true));
Console.Write(f(false));
}
public static void Main()
{
M(b => { if (b) return new C(); else return new(); });
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CC");
}
[Fact]
public void TestBestType_SwitchExpression()
{
var source = @"
using System;
class C
{
public static void Main()
{
var b = false;
Console.Write((int)(b switch { true => 1, false => new() }));
b = true;
Console.Write((int)(b switch { true => 1, false => new() }));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "01");
}
[Fact]
public void TestInSwitchExpression()
{
var source = @"
using System;
class C
{
public static void Main()
{
C x = 0 switch { _ => new() };
Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
}
[Fact]
public void TestInNullCoalescingAssignment()
{
var source = @"
using System;
class C
{
public static void Main()
{
C x = null;
x ??= new();
Console.Write(x);
int? i = null;
i ??= new();
Console.Write(i);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C0");
}
[Fact]
public void TestInNullCoalescingAssignment_ErrorCase()
{
var source = @"
class C
{
public static void Main()
{
new() ??= new C();
new() ??= new();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (6,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// new() ??= new C();
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new()").WithLocation(6, 9),
// (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// new() ??= new();
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new()").WithLocation(7, 9)
);
}
[Fact]
public void TestBestType_Lambda_ErrorCase()
{
var source = @"
using System;
class C
{
public static void M<T>(Func<bool, T> f)
{
}
public static void Main()
{
M(b => { if (b) return new(); else return new(); });
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (12,9): error CS0411: The type arguments for method 'C.M<T>(Func<bool, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(b => { if (b) return new(); else return new(); });
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(System.Func<bool, T>)").WithLocation(12, 9)
);
}
[Fact]
public void TestBadTypeParameter()
{
var source = @"
class C
{
static void M<A, B, C>()
where A : struct
where B : new()
{
A v1 = new(1);
B v2 = new(2);
C v3 = new();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(
// (8,16): error CS0417: 'A': cannot provide arguments when creating an instance of a variable type
// A v1 = new(1);
Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new(1)").WithArguments("A").WithLocation(8, 16),
// (9,16): error CS0417: 'B': cannot provide arguments when creating an instance of a variable type
// B v2 = new(2);
Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new(2)").WithArguments("B").WithLocation(9, 16),
// (10,16): error CS0304: Cannot create an instance of the variable type 'C' because it does not have the new() constraint
// C v3 = new();
Diagnostic(ErrorCode.ERR_NoNewTyvar, "new()").WithArguments("C").WithLocation(10, 16)
);
}
[Fact]
public void TestTypeParameterInitializer()
{
var source = @"
using System;
class C
{
public int field;
static void M1<T>() where T : C, new()
{
Console.Write(((T)new(){ field = 42 }).field);
}
public static void Main()
{
M1<C>();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact]
public void TestInitializer_ErrorCase()
{
var source = @"
class C
{
public static void Main()
{
string x = new() { Length = 5 };
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (8,28): error CS0200: Property or indexer 'string.Length' cannot be assigned to -- it is read only
// string x = new() { Length = 5 };
Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Length").WithArguments("string.Length").WithLocation(6, 28),
// (8,20): error CS1729: 'string' does not contain a constructor that takes 0 arguments
// string x = new() { Length = 5 };
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new() { Length = 5 }").WithArguments("string", "0").WithLocation(6, 20)
);
}
[Fact]
public void TestImplicitConversion()
{
var source = @"
public class Dog
{
public Dog() {}
}
public class Animal
{
public Animal() {}
public static implicit operator Animal(Dog dog) => throw null;
}
public class Program
{
public static void M(Animal a) => System.Console.Write(a);
public static void Main()
{
M(new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
);
CompileAndVerify(comp, expectedOutput: "Animal");
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void ArgList()
{
var source = @"
using System;
class C
{
static void Main()
{
C x = new(__arglist(2, 3, true));
}
public C(__arglist)
{
DumpArgs(new(__arglist));
}
static void DumpArgs(ArgIterator args)
{
while(args.GetRemainingCount() > 0)
{
TypedReference tr = args.GetNextArg();
object arg = TypedReference.ToObject(tr);
Console.Write(arg);
}
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "23True");
}
[Fact]
public void TestOverloadResolution01()
{
var source = @"
class C
{
public C(int i) {}
}
class D
{
}
class Program
{
static void M(C c, object o) {}
static void M(D d, int i) {}
public static void Main()
{
M(new(1), 1);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (18,11): error CS1729: 'D' does not contain a constructor that takes 1 arguments
// M(new(1), 1);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new(1)").WithArguments("D", "1").WithLocation(18, 11)
);
}
[Fact]
public void TestOverloadResolution02()
{
var source = @"
using System;
class A
{
public A(int i) {}
}
class B : A
{
public B(int i) : base(i) {}
}
class Program
{
static void M(A a) => Console.Write(""A"");
static void M(B a) => Console.Write(""B"");
public static void Main()
{
M(new(43));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "B");
}
[Fact]
public void TestOverloadResolution03()
{
var source = @"
class A
{
public A(int i) {}
}
class B : A
{
public B(int i) : base(i) {}
}
class Program
{
static void M(A a) {}
static void M(B a) {}
public static void Main()
{
M(new(Missing()));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (18,15): error CS0103: The name 'Missing' does not exist in the current context
// M(new(Missing()));
Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(18, 15)
);
}
[Fact]
public void TestOverloadResolution04()
{
var source = @"
class A
{
public A(int i) {}
}
class B : A
{
public B(int i) : base(i) {}
}
class Program
{
public static void Main()
{
Missing(new(1));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (15,9): error CS0103: The name 'Missing' does not exist in the current context
// Missing(new(1));
Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(15, 9)
);
}
[Fact]
public void TestOverloadResolution05()
{
var source = @"
class A
{
public A(int i) {}
}
class B : A
{
public B(int i) : base(i) {}
}
class Program
{
static void M(A a, int i) {}
static void M(B a, object i) {}
public static void Main()
{
M(new(), 1);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A, int)' and 'Program.M(B, object)'
// M(new(), 1);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A, int)", "Program.M(B, object)").WithLocation(18, 9)
);
}
[Fact]
public void TestOverloadResolution06()
{
var source = @"
class C
{
public C(object a, C b) {}
public C(C a, int b) {}
public static void Main()
{
C c = new(new(), new());
}
}
";
var comp = CreateCompilation(source).VerifyDiagnostics(
// (9,19): error CS1729: 'C' does not contain a constructor that takes 0 arguments
// C c = new(new(), new());
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("C", "0").WithLocation(9, 19)
);
}
[Fact]
public void TestSymbols()
{
var source = @"
class C
{
static C N(int i) => null;
static void M(C c) {}
public static void Main()
{
Missing(new() { X = N(1) });
M(new() { X = N(2) });
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (10,9): error CS0103: The name 'Missing' does not exist in the current context
// Missing(new() { X = N(1) });
Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(10, 9),
// (11,19): error CS0117: 'C' does not contain a definition for 'X'
// M(new() { X = N(2) });
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(11, 19)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray();
assert(1, "N(1)", type: "C", convertedType: "C", symbol: "C C.N(System.Int32 i)", ConversionKind.Identity);
assert(3, "N(2)", type: "C", convertedType: "C", symbol: "C C.N(System.Int32 i)", ConversionKind.Identity);
void assert(int index, string expression, string type, string convertedType, string symbol, ConversionKind conversionKind)
{
var invocation = nodes[index];
Assert.Equal(expression, invocation.ToString());
Assert.Equal(type, model.GetTypeInfo(invocation).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(invocation).ConvertedType.ToTestDisplayString());
Assert.Equal(symbol, model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString());
Assert.Equal(conversionKind, model.GetConversion(invocation).Kind);
}
}
[Fact]
public void TestAssignment()
{
var source = @"
class Program
{
public static void Main()
{
new() = 5;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (6,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// new() = 5;
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new()").WithLocation(6, 9)
);
}
[Fact]
public void TestNullableType01()
{
var source = @"
using System;
struct S
{
public S(int i)
{
Console.Write(i);
}
public static void Main()
{
S? s = new(43);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "43");
}
[Fact]
public void TestNullableType02()
{
var source = @"
using System;
struct S
{
public static T? M<T>() where T : struct
{
return new();
}
public static void Main()
{
Console.Write(M<S>());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "S");
}
[Fact]
public void TestInStatement()
{
var source = @"
struct S
{
public static void Main()
{
new(a) { x };
new() { x };
}
}
";
_ = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// new(a) { x };
Diagnostic(ErrorCode.ERR_IllegalStatement, "new(a) { x }").WithLocation(6, 9),
// (6,13): error CS0103: The name 'a' does not exist in the current context
// new(a) { x };
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(6, 13),
// (6,18): error CS0103: The name 'x' does not exist in the current context
// new(a) { x };
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 18),
// (7,9): error CS8754: There is no target type for 'new()'
// new() { x };
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new() { x }").WithArguments("new()").WithLocation(7, 9),
// (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// new() { x };
Diagnostic(ErrorCode.ERR_IllegalStatement, "new() { x }").WithLocation(7, 9),
// (7,17): error CS0103: The name 'x' does not exist in the current context
// new() { x };
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(7, 17)
);
}
[Fact]
public void TestLangVersion_CSharp7()
{
string source = @"
class C
{
static void Main()
{
C x = new();
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
comp.VerifyDiagnostics(
// (6,15): error CS8107: Feature 'target-typed object creation' is not available in C# 7.0. Please use language version 9.0 or greater.
// C x = new();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "new").WithArguments("target-typed object creation", "9.0").WithLocation(6, 15)
);
}
[Fact]
public void TestAssignmentToClass()
{
string source = @"
class C
{
static void Main()
{
C x = new();
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().Single();
Assert.Equal("C", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("C", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
Assert.Equal("C..ctor()", model.GetSymbolInfo(def).Symbol.ToTestDisplayString());
Assert.False(model.GetConstantValue(def).HasValue);
Assert.True(model.GetConversion(def).IsIdentity);
}
[Fact]
public void TestAssignmentToStruct()
{
string source = @"
struct S
{
public S(int i) {}
static void Main()
{
S x = new(43);
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "S");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().Single();
Assert.Equal("S", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("S", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
Assert.Equal("S..ctor(System.Int32 i)", model.GetSymbolInfo(def).Symbol.ToTestDisplayString());
Assert.False(model.GetConstantValue(def).HasValue);
Assert.True(model.GetConversion(def).IsIdentity);
}
[Fact]
public void AssignmentToNullableStruct()
{
string source = @"
struct S
{
public S(int i) {}
static void Main()
{
S? x = new(43);
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "S");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().Single();
Assert.Equal("S", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("S?", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
Assert.Equal("S..ctor(System.Int32 i)", model.GetSymbolInfo(def).Symbol.ToTestDisplayString());
Assert.False(model.GetConstantValue(def).HasValue);
Assert.True(model.GetConversion(def).IsNullable);
Assert.True(model.GetConversion(def).IsImplicit);
}
[Fact]
public void AssignmentToThisOnRefType()
{
string source = @"
public class C
{
public int field;
public C() => this = new();
public static void Main()
{
new C();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (5,19): error CS1604: Cannot assign to 'this' because it is read-only
// public C() => this = new();
Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this").WithLocation(5, 19)
);
}
[Fact]
public void AssignmentToThisOnStructType()
{
string source = @"
public struct S
{
public int field;
public S(int x) => this = new(x);
public static void Main()
{
new S(1);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().ElementAt(0);
Assert.Equal("new(x)", def.ToString());
Assert.Equal("S", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("S", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
}
[Fact]
public void InAttributeParameter()
{
string source = @"
[Custom(z: new(), y: new(), x: new())]
class C
{
[Custom(new(1), new('s', 2))]
void M()
{
}
}
public class CustomAttribute : System.Attribute
{
public CustomAttribute(int x, string y, byte z = 0) { }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (2,22): error CS1729: 'string' does not contain a constructor that takes 0 arguments
// [Custom(z: new(), y: new(), x: new())]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(2, 22),
// (5,13): error CS1729: 'int' does not contain a constructor that takes 1 arguments
// [Custom(new(1), new('s', 2))]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new(1)").WithArguments("int", "1").WithLocation(5, 13),
// (5,21): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Custom(new(1), new('s', 2))]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new('s', 2)").WithLocation(5, 21)
);
}
[Fact]
public void InStringInterpolation()
{
string source = @"
class C
{
static void Main()
{
System.Console.Write($""({new()}) ({new object()})"");
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "(System.Object) (System.Object)");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var @new = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().Single();
Assert.Equal("new()", @new.ToString());
Assert.Equal("System.Object", model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal("System.Object", model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal("System.Object..ctor()", model.GetSymbolInfo(@new).Symbol?.ToTestDisplayString());
Assert.False(model.GetConstantValue(@new).HasValue);
var newObject = nodes.OfType<ObjectCreationExpressionSyntax>().Single();
Assert.Equal("new object()", newObject.ToString());
Assert.Equal("System.Object", model.GetTypeInfo(newObject).Type.ToTestDisplayString());
Assert.Equal("System.Object", model.GetTypeInfo(newObject).ConvertedType.ToTestDisplayString());
Assert.Equal("System.Object..ctor()", model.GetSymbolInfo(newObject).Symbol?.ToTestDisplayString());
}
[Fact]
public void InUsing01()
{
string source = @"
class C
{
static void Main()
{
using (new())
{
}
using (var x = new())
{
}
using (System.IDisposable x = new())
{
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,16): error CS8754: There is no target type for 'new()'
// using (new())
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 16),
// (10,24): error CS8754: There is no target type for 'new()'
// using (var x = new())
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(10, 24),
// (14,39): error CS0144: Cannot create an instance of the abstract type or interface 'IDisposable'
// using (System.IDisposable x = new())
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("System.IDisposable").WithLocation(14, 39)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
assert(0, type: "?", convertedType: "?", ConversionKind.Identity);
assert(1, type: "?", convertedType: "?", ConversionKind.Identity);
assert(2, type: "System.IDisposable", convertedType: "System.IDisposable", ConversionKind.Identity);
void assert(int index, string type, string convertedType, ConversionKind conversionKind)
{
var @new = nodes[index];
Assert.Equal(type, model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(@new).Symbol);
Assert.Equal(conversionKind, model.GetConversion(@new).Kind);
}
}
[Fact]
public void InUsing02()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
Console.Write(""C.Dispose"");
}
static void Main()
{
using (C c = new())
{
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C.Dispose");
}
[Fact]
public void TestInAwait()
{
string source = @"
class C
{
async System.Threading.Tasks.Task M1()
{
await new();
}
async System.Threading.Tasks.Task M2()
{
await new(a);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,15): error CS8754: There is no target type for 'new()'
// await new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 15),
// (11,19): error CS0103: The name 'a' does not exist in the current context
// await new(a);
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(11, 19)
);
}
[Fact]
public void ReturningFromAsyncMethod()
{
string source = @"
using System.Threading.Tasks;
class C
{
async Task<T> M2<T>() where T : new()
{
await Task.Delay(0);
return new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().ElementAt(0);
Assert.Equal("new()", def.ToString());
Assert.Equal("T", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("T", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(def).Symbol);
Assert.False(model.GetConstantValue(def).HasValue);
Assert.True(model.GetConversion(def).IsIdentity);
}
[Fact]
public void TestInAsyncLambda_01()
{
string source = @"
class C
{
static void F<T>(System.Threading.Tasks.Task<T> t) { }
static void M()
{
F(async () => await new());
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,9): error CS0411: The type arguments for method 'C.F<T>(Task<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F(async () => await new());
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("C.F<T>(System.Threading.Tasks.Task<T>)").WithLocation(8, 9)
);
}
[Fact]
public void TestInAsyncLambda_02()
{
string source = @"
class C
{
static void F<T>(System.Threading.Tasks.Task<T> t) { }
static void M()
{
F(async () => new());
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,9): error CS0411: The type arguments for method 'C.F<T>(Task<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F(async () => new());
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("C.F<T>(System.Threading.Tasks.Task<T>)").WithLocation(8, 9),
// (8,20): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// F(async () => new());
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(8, 20)
);
}
[Fact]
public void RefReturnValue1()
{
string source = @"
class C
{
ref int M()
{
return new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS8150: By-value returns may only be used in methods that return by value
// return new();
Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(6, 9)
);
}
[Fact]
public void RefReturnValue2()
{
string source = @"
class C
{
ref C M()
{
return ref new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// return ref new();
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "new()").WithLocation(6, 20)
);
}
[Fact]
public void InAnonType()
{
string source = @"
class C
{
static void M()
{
var x = new { Prop = new() };
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,30): error CS8754: There is no target type for 'new()'
// var x = new { Prop = new() };
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 30)
);
}
[Fact]
public void BadUnaryOperator()
{
string source = @"
class C
{
static void M()
{
C v1 = +new();
C v2 = -new();
C v3 = ~new();
C v4 = !new();
C v5 = ++new();
C v6 = --new();
C v7 = new()++;
C v8 = new()--;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,17): error CS8754: There is no target type for 'new()'
// C v1 = +new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 17),
// (7,17): error CS8754: There is no target type for 'new()'
// C v2 = -new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 17),
// (8,17): error CS8754: There is no target type for 'new()'
// C v3 = ~new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(8, 17),
// (9,17): error CS8754: There is no target type for 'new()'
// C v4 = !new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(9, 17),
// (10,18): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer
// C v5 = ++new();
Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "new()").WithLocation(10, 18),
// (11,18): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer
// C v6 = --new();
Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "new()").WithLocation(11, 18),
// (12,16): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer
// C v7 = new()++;
Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "new()").WithLocation(12, 16),
// (13,16): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer
// C v8 = new()--;
Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "new()").WithLocation(13, 16)
);
}
[Fact]
public void AmbiguousMethod()
{
string source = @"
class C
{
static void Main()
{
M(new());
}
static void M(int x) { }
static void M(string x) { }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(int)' and 'C.M(string)'
// M(new());
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(int)", "C.M(string)").WithLocation(6, 9)
);
}
[Fact]
public void MethodWithNullableParameters()
{
string source = @"
struct S
{
public S(int i) {}
static void Main()
{
M(new(43));
}
static void M(S? x) => System.Console.Write(x);
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "S");
}
[Fact]
public void CannotInferTypeArg()
{
string source = @"
class C
{
static void Main()
{
M(new());
}
static void M<T>(T x) { }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,9): error CS0411: The type arguments for method 'C.M<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(new());
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T)").WithLocation(6, 9)
);
}
[Fact]
public void CannotInferTypeArg2()
{
string source = @"
class C
{
static void Main()
{
M(new(), null);
}
static void M<T>(T x, T y) where T : class { }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,9): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(new(), null);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(6, 9)
);
}
[Fact]
public void Invocation()
{
string source = @"
class C
{
static void Main()
{
new().ToString();
new()[0].ToString();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,9): error CS8754: There is no target type for 'new()'
// new().ToString();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 9),
// (7,9): error CS8754: There is no target type for 'new()'
// new()[0].ToString();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 9)
);
}
[Fact]
public void InThrow()
{
string source = @"
class C
{
static void Main()
{
throw new(""message"");
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().First();
Assert.Equal("System.Exception", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("System.Exception", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
Assert.Equal("System.Exception..ctor(System.String message)", model.GetSymbolInfo(def).Symbol.ToTestDisplayString());
}
[Fact]
public void TestConst()
{
string source = @"
class C
{
static void M()
{
const object x = new();
const int y = new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,26): error CS0133: The expression being assigned to 'x' must be constant
// const object x = new();
Diagnostic(ErrorCode.ERR_NotConstantExpression, "new()").WithArguments("x").WithLocation(6, 26),
// (7,19): warning CS0219: The variable 'y' is assigned but its value is never used
// const int y = new();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(7, 19)
);
}
[Fact]
public void ImplicitlyTypedArray()
{
string source = @"
class C
{
static void Main()
{
var t = new[] { new C(), new() };
System.Console.Write(t[1]);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var def = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().First();
Assert.Equal("new()", def.ToString());
Assert.Equal("C", model.GetTypeInfo(def).Type.ToTestDisplayString());
Assert.Equal("C", model.GetTypeInfo(def).ConvertedType.ToTestDisplayString());
Assert.Equal("C..ctor()", model.GetSymbolInfo(def).Symbol.ToTestDisplayString());
Assert.False(model.GetConstantValue(def).HasValue);
}
[Fact]
public void InSwitch1()
{
string source = @"
class C
{
static void Main()
{
switch (new())
{
case new() when new():
case (new()) when (new()):
break;
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,17): error CS8754: There is no target type for 'new()'
// switch (new())
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 17),
// (10,17): warning CS0162: Unreachable code detected
// break;
Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(10, 17)
);
}
[Fact]
public void InSwitch2()
{
string source = @"
class C
{
static void Main()
{
switch (new C())
{
case new():
case (new()):
break;
}
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,18): error CS0150: A constant value is expected
// case new():
Diagnostic(ErrorCode.ERR_ConstantExpected, "new()").WithLocation(8, 18),
// (9,19): error CS0150: A constant value is expected
// case (new()):
Diagnostic(ErrorCode.ERR_ConstantExpected, "new()").WithLocation(9, 19)
);
}
[Fact]
public void InSwitch3()
{
string source = @"
class C
{
static void Main()
{
int i = 0;
bool b = true;
switch (i)
{
case new() when b:
System.Console.Write(0);
break;
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "0");
}
[Fact]
public void InGoToCase()
{
string source = @"
using System;
class C
{
static int Get(int i)
{
switch (i)
{
case new():
return 1;
case 1:
goto case new();
default:
return 2;
}
}
static void Main()
{
Console.Write(Get(0));
Console.Write(Get(1));
Console.Write(Get(2));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "112");
}
[Fact]
public void InCatchFilter()
{
string source = @"
class C
{
static void Main()
{
try
{
}
catch when (new())
{
}
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,21): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block
// catch when (new())
Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "new()").WithLocation(9, 21)
);
}
[Fact]
public void InLock()
{
string source = @"
class C
{
static void Main()
{
lock (new())
{
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,15): error CS8754: There is no target type for 'new()'
// lock (new())
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 15)
);
}
[Fact]
public void InMakeRef()
{
string source = @"
class C
{
static void Main()
{
System.TypedReference tr = __makeref(new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,46): error CS1510: A ref or out value must be an assignable variable
// System.TypedReference tr = __makeref(new());
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new()").WithLocation(6, 46)
);
}
[Fact]
public void InNameOf()
{
string source = @"
class C
{
static void Main()
{
_ = nameof(new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,20): error CS8081: Expression does not have a name.
// _ = nameof(new());
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "new()").WithLocation(6, 20)
);
}
[Fact]
public void InOutArgument()
{
string source = @"
class C
{
static void M(out int i)
{
i = 0;
M(out new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (7,15): error CS1510: A ref or out value must be an assignable variable
// M(out new());
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new()").WithLocation(7, 15)
);
}
[Fact]
public void InSizeOf()
{
string source = @"
class C
{
static void Main()
{
_ = sizeof(new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,20): error CS1031: Type expected
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_TypeExpected, "new").WithLocation(6, 20),
// (6,20): error CS1026: ) expected
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_CloseParenExpected, "new").WithLocation(6, 20),
// (6,20): error CS1002: ; expected
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_SemicolonExpected, "new").WithLocation(6, 20),
// (6,25): error CS1002: ; expected
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(6, 25),
// (6,25): error CS1513: } expected
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(6, 25),
// (6,13): error CS0233: '?' does not have a predefined size, therefore sizeof can only be used in an unsafe context
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(").WithArguments("?").WithLocation(6, 13),
// (6,20): error CS8754: There is no target type for 'new()'
// _ = sizeof(new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 20)
);
}
[Fact]
public void InTypeOf()
{
string source = @"
class C
{
static void Main()
{
_ = typeof(new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,20): error CS1031: Type expected
// _ = typeof(new());
Diagnostic(ErrorCode.ERR_TypeExpected, "new").WithLocation(6, 20),
// (6,20): error CS1026: ) expected
// _ = typeof(new());
Diagnostic(ErrorCode.ERR_CloseParenExpected, "new").WithLocation(6, 20),
// (6,20): error CS1002: ; expected
// _ = typeof(new());
Diagnostic(ErrorCode.ERR_SemicolonExpected, "new").WithLocation(6, 20),
// (6,20): error CS8754: There is no target type for 'new()'
// _ = typeof(new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 20),
// (6,25): error CS1002: ; expected
// _ = typeof(new());
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(6, 25),
// (6,25): error CS1513: } expected
// _ = typeof(new());
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(6, 25)
);
}
[Fact]
public void InChecked()
{
string source = @"
class C
{
static void Main()
{
int i = checked(new(a));
int j = checked(new()); // ok
C k = unchecked(new()); // ok
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,29): error CS0103: The name 'a' does not exist in the current context
// int i = checked(new(a));
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(6, 29),
// (7,13): warning CS0219: The variable 'j' is assigned but its value is never used
// int j = checked(new());
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "j").WithArguments("j").WithLocation(7, 13)
);
}
[Fact]
public void InRange()
{
string source = @"
using System;
class C
{
static void Main()
{
Range x0 = new()..new();
Range x1 = 1..new();
Range x2 = new()..1;
Console.WriteLine($""{x0.Start.Value}..{x0.End.Value}"");
Console.WriteLine($""{x1.Start.Value}..{x1.End.Value}"");
Console.WriteLine($""{x2.Start.Value}..{x2.End.Value}"");
}
}
";
var comp = CreateCompilationWithIndexAndRange(source, options: TestOptions.DebugExe, parseOptions: ImplicitObjectCreationTestOptions);
comp.VerifyDiagnostics();
var expectedOutput =
@"0..0
1..0
0..1";
CompileAndVerify(comp, expectedOutput: expectedOutput);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().ToArray();
assert(0, type: "System.Index", convertedType: "System.Index", symbol: "System.Index..ctor()", ConversionKind.Identity);
assert(1, type: "System.Index", convertedType: "System.Index", symbol: "System.Index..ctor()", ConversionKind.Identity);
assert(2, type: "System.Index", convertedType: "System.Index", symbol: "System.Index..ctor()", ConversionKind.Identity);
assert(3, type: "System.Index", convertedType: "System.Index", symbol: "System.Index..ctor()", ConversionKind.Identity);
void assert(int index, string type, string convertedType, string symbol, ConversionKind conversionKind)
{
var @new = nodes[index];
Assert.Equal(type, model.GetTypeInfo(@new).Type.ToTestDisplayString());
Assert.Equal(convertedType, model.GetTypeInfo(@new).ConvertedType.ToTestDisplayString());
Assert.Equal(symbol, model.GetSymbolInfo(@new).Symbol.ToTestDisplayString());
Assert.Equal(conversionKind, model.GetConversion(@new).Kind);
}
}
[Fact]
public void RefTypeAndValue()
{
string source = @"
class C
{
static void Main()
{
var t = __reftype(new());
int rv = __refvalue(new(), int);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
}
[Fact]
public void ConditionalOnNew()
{
string source = @"
class C
{
static void Main()
{
if (new())
{
System.Console.Write(""if"");
}
while (new())
{
System.Console.Write(""while"");
}
for (int i = 0; new(); i++)
{
System.Console.Write(""for"");
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (8,13): warning CS0162: Unreachable code detected
// System.Console.Write("if");
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(8, 13),
// (13,13): warning CS0162: Unreachable code detected
// System.Console.Write("while");
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(13, 13),
// (18,13): warning CS0162: Unreachable code detected
// System.Console.Write("for");
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(18, 13));
}
[Fact]
public void InFixed()
{
string source = @"
class C
{
static unsafe void Main()
{
fixed (byte* p = new())
{
}
fixed (byte* p = &new())
{
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
comp.VerifyDiagnostics(
// (6,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (byte* p = new())
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new()").WithLocation(6, 26),
// (9,27): error CS0211: Cannot take the address of the given expression
// fixed (byte* p = &new())
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "new()").WithLocation(9, 27)
);
}
[Fact]
public void Dereference()
{
string source = @"
class C
{
static void M()
{
var p = *new();
var q = new()->F;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,18): error CS8754: There is no target type for 'new()'
// var p = *new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 18),
// (7,17): error CS8754: There is no target type for 'new()'
// var q = new()->F;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 17)
);
}
[Fact]
public void FailedImplicitlyTypedArray()
{
string source = @"
class C
{
static void Main()
{
var t = new[] { new(), new() };
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,17): error CS0826: No best type found for implicitly-typed array
// var t = new[] { new(), new() };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { new(), new() }").WithLocation(6, 17)
);
}
[Fact]
public void ArrayConstruction()
{
string source = @"
class C
{
static void Main()
{
var t = new object[new()];
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void Tuple()
{
string source = @"
class C
{
static void Main()
{
(int, C) t = (1, new());
System.Console.Write(t.Item2);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
}
[Fact]
public void TypeInferenceSucceeds()
{
string source = @"
class C
{
static void Main()
{
M(new(), new C());
}
static void M<T>(T x, T y) { System.Console.Write(x); }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
}
[Fact]
public void ArrayTypeInferredFromParams()
{
string source = @"
class C
{
static void Main()
{
M(new());
}
static void M(params object[] x) { }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,11): error CS9366: The type 'object[]' may not be used as the target-type of 'new()'
// M(new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new()").WithArguments("object[]").WithLocation(6, 11)
);
}
[Fact]
public void ParamsAmbiguity01()
{
string source = @"
class C
{
static void Main()
{
M(new());
}
static void M(params object[] x) { }
static void M(params int[] x) { }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(params object[])' and 'C.M(params int[])'
// M(new());
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(params object[])", "C.M(params int[])").WithLocation(6, 9)
);
}
[Fact]
public void ParamsAmbiguity02()
{
string source = @"
class C
{
static void Main()
{
M(new());
}
static void M(params object[] x) { }
static void M(C x) { }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(params object[])' and 'C.M(C)'
// M(new());
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(params object[])", "C.M(C)").WithLocation(6, 9)
);
}
[Fact]
public void ParamsAmbiguity03()
{
string source = @"
class C
{
static void Main()
{
object o = null;
C c = new();
M(o, new());
M(new(), o);
M(c, new());
M(new(), c);
}
static void M<T>(T x, params T[] y) { }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (8,14): error CS9366: The type 'object[]' may not be used as the target-type of 'new'.
// M(o, new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new()").WithArguments("object[]").WithLocation(8, 14),
// (10,14): error CS9366: The type 'C[]' may not be used as the target-type of 'new'.
// M(c, new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new()").WithArguments("C[]").WithLocation(10, 14)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var first = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().ElementAt(1);
Assert.Equal("(o, new())", first.Parent.Parent.ToString());
Assert.Equal("System.Object[]", model.GetTypeInfo(first).Type.ToTestDisplayString());
var second = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().ElementAt(2);
Assert.Equal("(new(), o)", second.Parent.Parent.ToString());
Assert.Equal("System.Object", model.GetTypeInfo(second).Type.ToTestDisplayString());
var third = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().ElementAt(3);
Assert.Equal("(c, new())", third.Parent.Parent.ToString());
Assert.Equal("C[]", model.GetTypeInfo(third).Type.ToTestDisplayString());
var fourth = nodes.OfType<ImplicitObjectCreationExpressionSyntax>().ElementAt(4);
Assert.Equal("(new(), c)", fourth.Parent.Parent.ToString());
Assert.Equal("C", model.GetTypeInfo(fourth).Type.ToTestDisplayString());
}
[Fact]
public void NewIdentifier()
{
string source = @"
class C
{
static void Main()
{
int @new = 2;
C x = new();
System.Console.Write($""{x} {@new}"");
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C 2");
}
[Fact]
public void Return()
{
string source = @"
class C
{
static C M()
{
return new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void NewInEnum()
{
string source = @"
enum E : byte
{
A = new(),
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void YieldReturn()
{
string source = @"
using System.Collections;
using System.Collections.Generic;
class C
{
static IEnumerable<C> M()
{
yield return new();
}
static IEnumerable M2()
{
yield return new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void InvocationOnDynamic()
{
string source = @"
class C
{
static void M1()
{
dynamic d = null;
d.M2(new());
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,14): error CS8754: There is no target type for 'new()'
// d.M2(new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 14)
);
}
[Fact]
public void DynamicInvocation()
{
string source = @"
class C
{
static void Main()
{
F(new());
}
static void F(dynamic x)
{
System.Console.Write(x == null);
}
}
";
var comp = CreateCompilation(source, references: new[] { CSharpRef }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,11): error CS8752: The type 'dynamic' may not be used as the target type of new()
// F(new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new()").WithArguments("dynamic").WithLocation(6, 11)
);
}
[Fact]
public void TestBinaryOperators01()
{
string source = @"
class C
{
static void Main()
{
var a = new() + new();
var b = new() - new();
var c = new() & new();
var d = new() | new();
var e = new() ^ new();
var f = new() * new();
var g = new() / new();
var h = new() % new();
var i = new() >> new();
var j = new() << new();
var k = new() > new();
var l = new() < new();
var m = new() >= new();
var n = new() <= new();
var o = new() == new();
var p = new() != new();
var q = new() && new();
var r = new() || new();
var s = new() ?? new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,17): error CS8310: Operator '+' cannot be applied to operand 'new()'
// var a = new() + new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() + new()").WithArguments("+", "new()").WithLocation(6, 17),
// (7,17): error CS8310: Operator '-' cannot be applied to operand 'new()'
// var b = new() - new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() - new()").WithArguments("-", "new()").WithLocation(7, 17),
// (8,17): error CS8310: Operator '&' cannot be applied to operand 'new()'
// var c = new() & new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() & new()").WithArguments("&", "new()").WithLocation(8, 17),
// (9,17): error CS8310: Operator '|' cannot be applied to operand 'new()'
// var d = new() | new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() | new()").WithArguments("|", "new()").WithLocation(9, 17),
// (10,17): error CS8310: Operator '^' cannot be applied to operand 'new()'
// var e = new() ^ new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() ^ new()").WithArguments("^", "new()").WithLocation(10, 17),
// (11,17): error CS8310: Operator '*' cannot be applied to operand 'new()'
// var f = new() * new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() * new()").WithArguments("*", "new()").WithLocation(11, 17),
// (12,17): error CS8310: Operator '/' cannot be applied to operand 'new()'
// var g = new() / new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() / new()").WithArguments("/", "new()").WithLocation(12, 17),
// (13,17): error CS8310: Operator '%' cannot be applied to operand 'new()'
// var h = new() % new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() % new()").WithArguments("%", "new()").WithLocation(13, 17),
// (14,17): error CS8310: Operator '>>' cannot be applied to operand 'new()'
// var i = new() >> new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() >> new()").WithArguments(">>", "new()").WithLocation(14, 17),
// (15,17): error CS8310: Operator '<<' cannot be applied to operand 'new()'
// var j = new() << new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() << new()").WithArguments("<<", "new()").WithLocation(15, 17),
// (16,17): error CS8310: Operator '>' cannot be applied to operand 'new()'
// var k = new() > new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() > new()").WithArguments(">", "new()").WithLocation(16, 17),
// (17,17): error CS8310: Operator '<' cannot be applied to operand 'new()'
// var l = new() < new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() < new()").WithArguments("<", "new()").WithLocation(17, 17),
// (18,17): error CS8310: Operator '>=' cannot be applied to operand 'new()'
// var m = new() >= new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() >= new()").WithArguments(">=", "new()").WithLocation(18, 17),
// (19,17): error CS8310: Operator '<=' cannot be applied to operand 'new()'
// var n = new() <= new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() <= new()").WithArguments("<=", "new()").WithLocation(19, 17),
// (20,17): error CS8310: Operator '==' cannot be applied to operand 'new()'
// var o = new() == new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == new()").WithArguments("==", "new()").WithLocation(20, 17),
// (21,17): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// var p = new() != new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != new()").WithArguments("!=", "new()").WithLocation(21, 17),
// (22,17): error CS8754: There is no target type for 'new()'
// var q = new() && new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(22, 17),
// (22,26): error CS8754: There is no target type for 'new()'
// var q = new() && new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(22, 26),
// (23,17): error CS8754: There is no target type for 'new()'
// var r = new() || new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(23, 17),
// (23,26): error CS8754: There is no target type for 'new()'
// var r = new() || new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(23, 26),
// (24,17): error CS8754: There is no target type for 'new()'
// var s = new() ?? new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(24, 17)
);
}
[Fact]
public void TestBinaryOperators02()
{
string source = @"
class C
{
static void Main()
{
_ = new() + 1;
_ = new() - 1;
_ = new() & 1;
_ = new() | 1;
_ = new() ^ 1;
_ = new() * 1;
_ = new() / 1;
_ = new() % 1;
_ = new() >> 1;
_ = new() << 1;
_ = new() > 1;
_ = new() < 1;
_ = new() >= 1;
_ = new() <= 1;
_ = new() == 1;
_ = new() != 1;
_ = new() && 1;
_ = new() || 1;
_ = new() ?? 1;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,13): error CS8310: Operator '+' cannot be applied to operand 'new()'
// _ = new() + 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() + 1").WithArguments("+", "new()").WithLocation(6, 13),
// (7,13): error CS8310: Operator '-' cannot be applied to operand 'new()'
// _ = new() - 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() - 1").WithArguments("-", "new()").WithLocation(7, 13),
// (8,13): error CS8310: Operator '&' cannot be applied to operand 'new()'
// _ = new() & 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() & 1").WithArguments("&", "new()").WithLocation(8, 13),
// (9,13): error CS8310: Operator '|' cannot be applied to operand 'new()'
// _ = new() | 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() | 1").WithArguments("|", "new()").WithLocation(9, 13),
// (10,13): error CS8310: Operator '^' cannot be applied to operand 'new()'
// _ = new() ^ 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() ^ 1").WithArguments("^", "new()").WithLocation(10, 13),
// (11,13): error CS8310: Operator '*' cannot be applied to operand 'new()'
// _ = new() * 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() * 1").WithArguments("*", "new()").WithLocation(11, 13),
// (12,13): error CS8310: Operator '/' cannot be applied to operand 'new()'
// _ = new() / 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() / 1").WithArguments("/", "new()").WithLocation(12, 13),
// (13,13): error CS8310: Operator '%' cannot be applied to operand 'new()'
// _ = new() % 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() % 1").WithArguments("%", "new()").WithLocation(13, 13),
// (14,13): error CS8310: Operator '>>' cannot be applied to operand 'new()'
// _ = new() >> 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() >> 1").WithArguments(">>", "new()").WithLocation(14, 13),
// (15,13): error CS8310: Operator '<<' cannot be applied to operand 'new()'
// _ = new() << 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() << 1").WithArguments("<<", "new()").WithLocation(15, 13),
// (16,13): error CS8310: Operator '>' cannot be applied to operand 'new()'
// _ = new() > 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() > 1").WithArguments(">", "new()").WithLocation(16, 13),
// (17,13): error CS8310: Operator '<' cannot be applied to operand 'new()'
// _ = new() < 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() < 1").WithArguments("<", "new()").WithLocation(17, 13),
// (18,13): error CS8310: Operator '>=' cannot be applied to operand 'new()'
// _ = new() >= 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() >= 1").WithArguments(">=", "new()").WithLocation(18, 13),
// (19,13): error CS8310: Operator '<=' cannot be applied to operand 'new()'
// _ = new() <= 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() <= 1").WithArguments("<=", "new()").WithLocation(19, 13),
// (20,13): error CS8310: Operator '==' cannot be applied to operand 'new()'
// _ = new() == 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == 1").WithArguments("==", "new()").WithLocation(20, 13),
// (21,13): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// _ = new() != 1;
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != 1").WithArguments("!=", "new()").WithLocation(21, 13),
// (22,13): error CS8754: There is no target type for 'new()'
// _ = new() && 1;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(22, 13),
// (23,13): error CS8754: There is no target type for 'new()'
// _ = new() || 1;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(23, 13),
// (24,13): error CS8754: There is no target type for 'new()'
// _ = new() ?? 1;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(24, 13)
);
}
[Fact]
public void TestBinaryOperators03()
{
string source = @"
class C
{
static void Main()
{
_ = 1 + new();
_ = 1 - new();
_ = 1 & new();
_ = 1 | new();
_ = 1 ^ new();
_ = 1 * new();
_ = 1 / new();
_ = 1 % new();
_ = 1 >> new();
_ = 1 << new();
_ = 1 > new();
_ = 1 < new();
_ = 1 >= new();
_ = 1 <= new();
_ = 1 == new();
_ = 1 != new();
_ = 1 && new();
_ = 1 || new();
_ = 1 ?? new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,13): error CS8310: Operator '+' cannot be applied to operand 'new()'
// _ = 1 + new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 + new()").WithArguments("+", "new()").WithLocation(6, 13),
// (7,13): error CS8310: Operator '-' cannot be applied to operand 'new()'
// _ = 1 - new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 - new()").WithArguments("-", "new()").WithLocation(7, 13),
// (8,13): error CS8310: Operator '&' cannot be applied to operand 'new()'
// _ = 1 & new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 & new()").WithArguments("&", "new()").WithLocation(8, 13),
// (9,13): error CS8310: Operator '|' cannot be applied to operand 'new()'
// _ = 1 | new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 | new()").WithArguments("|", "new()").WithLocation(9, 13),
// (10,13): error CS8310: Operator '^' cannot be applied to operand 'new()'
// _ = 1 ^ new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 ^ new()").WithArguments("^", "new()").WithLocation(10, 13),
// (11,13): error CS8310: Operator '*' cannot be applied to operand 'new()'
// _ = 1 * new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 * new()").WithArguments("*", "new()").WithLocation(11, 13),
// (12,13): error CS8310: Operator '/' cannot be applied to operand 'new()'
// _ = 1 / new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 / new()").WithArguments("/", "new()").WithLocation(12, 13),
// (13,13): error CS8310: Operator '%' cannot be applied to operand 'new()'
// _ = 1 % new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 % new()").WithArguments("%", "new()").WithLocation(13, 13),
// (14,13): error CS8310: Operator '>>' cannot be applied to operand 'new()'
// _ = 1 >> new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 >> new()").WithArguments(">>", "new()").WithLocation(14, 13),
// (15,13): error CS8310: Operator '<<' cannot be applied to operand 'new()'
// _ = 1 << new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 << new()").WithArguments("<<", "new()").WithLocation(15, 13),
// (16,13): error CS8310: Operator '>' cannot be applied to operand 'new()'
// _ = 1 > new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 > new()").WithArguments(">", "new()").WithLocation(16, 13),
// (17,13): error CS8310: Operator '<' cannot be applied to operand 'new()'
// _ = 1 < new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 < new()").WithArguments("<", "new()").WithLocation(17, 13),
// (18,13): error CS8310: Operator '>=' cannot be applied to operand 'new()'
// _ = 1 >= new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 >= new()").WithArguments(">=", "new()").WithLocation(18, 13),
// (19,13): error CS8310: Operator '<=' cannot be applied to operand 'new()'
// _ = 1 <= new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 <= new()").WithArguments("<=", "new()").WithLocation(19, 13),
// (20,13): error CS8310: Operator '==' cannot be applied to operand 'new()'
// _ = 1 == new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 == new()").WithArguments("==", "new()").WithLocation(20, 13),
// (21,13): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// _ = 1 != new();
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 != new()").WithArguments("!=", "new()").WithLocation(21, 13),
// (22,18): error CS8754: There is no target type for 'new()'
// _ = 1 && new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(22, 18),
// (23,18): error CS8754: There is no target type for 'new()'
// _ = 1 || new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(23, 18),
// (24,13): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'new()'
// _ = 1 ?? new();
Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 ?? new()").WithArguments("??", "int", "new()").WithLocation(24, 13)
);
}
[Fact]
public void InForeach()
{
var text = @"
class C
{
static void Main()
{
foreach (int x in new()) { }
}
}";
var comp = CreateCompilation(text, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,27): error CS8754: There is no target type for 'new()'
// foreach (int x in new()) { }
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 27)
);
}
[Fact]
public void Query()
{
string source =
@"using System.Linq;
static class C
{
static void Main()
{
var q = from x in new() select x;
var p = from x in new int[] { 1 } select new();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (6,27): error CS8754: There is no target type for 'new()'
// var q = from x in new() select x;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 27),
// (7,43): error CS1942: The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'.
// var p = from x in new int[] { 1 } select new();
Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailed, "select").WithArguments("select", "Select").WithLocation(7, 43)
);
}
[Fact]
public void InIsOperator()
{
var text = @"
class C
{
void M()
{
bool v1 = new() is long;
bool v2 = new() is string;
bool v3 = new() is new();
bool v4 = v1 is new();
bool v5 = this is new();
}
}";
var comp = CreateCompilation(text, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (6,19): error CS8754: There is no target type for 'new()'
// bool v1 = new() is long;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(6, 19),
// (7,19): error CS8754: There is no target type for 'new()'
// bool v2 = new() is string;
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 19),
// (8,19): error CS8754: There is no target type for 'new()'
// bool v3 = new() is new();
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(8, 19),
// (10,27): error CS0150: A constant value is expected
// bool v5 = this is new();
Diagnostic(ErrorCode.ERR_ConstantExpected, "new()").WithLocation(10, 27)
);
}
[Fact]
public void InNullCoalescing()
{
var text =
@"using System;
class Program
{
static void Main()
{
Func<object> f = () => new() ?? ""hello"";
}
}";
var comp = CreateCompilation(text).VerifyDiagnostics(
// (7,32): error CS8754: There is no target type for 'new()'
// Func<object> f = () => new() ?? "hello";
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(7, 32)
);
}
[Fact]
public void Lambda()
{
string source = @"
class C
{
static void Main()
{
System.Console.Write(M()());
}
static System.Func<C> M()
{
return () => new();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C");
}
[Fact]
public void TestTupleEquality01()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.Write(new() == (1, 2L) ? 1 : 0);
Console.Write(new() != (1, 2L) ? 1 : 0);
Console.Write((1, 2L) == new() ? 1 : 0);
Console.Write((1, 2L) != new() ? 1 : 0);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (7,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write(new() == (1, 2L) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == (1, 2L)").WithArguments("==", "new()").WithLocation(7, 23),
// (8,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write(new() != (1, 2L) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != (1, 2L)").WithArguments("!=", "new()").WithLocation(8, 23),
// (9,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write((1, 2L) == new() ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(1, 2L) == new()").WithArguments("==", "new()").WithLocation(9, 23),
// (10,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write((1, 2L) != new() ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(1, 2L) != new()").WithArguments("!=", "new()").WithLocation(10, 23)
);
}
[Fact]
public void TestTupleEquality02()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.Write((new(), new()) == (1, 2L) ? 1 : 0);
Console.Write((new(), new()) != (1, 2L) ? 1 : 0);
Console.Write((1, 2L) == (new(), new()) ? 1 : 0);
Console.Write((1, 2L) != (new(), new()) ? 1 : 0);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (8,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write((new(), new()) == (1, 2L) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(new(), new()) == (1, 2L)").WithArguments("==", "new()").WithLocation(8, 23),
// (8,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write((new(), new()) == (1, 2L) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(new(), new()) == (1, 2L)").WithArguments("==", "new()").WithLocation(8, 23),
// (9,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write((new(), new()) != (1, 2L) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(new(), new()) != (1, 2L)").WithArguments("!=", "new()").WithLocation(9, 23),
// (9,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write((new(), new()) != (1, 2L) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(new(), new()) != (1, 2L)").WithArguments("!=", "new()").WithLocation(9, 23),
// (10,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write((1, 2L) == (new(), new()) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(1, 2L) == (new(), new())").WithArguments("==", "new()").WithLocation(10, 23),
// (10,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write((1, 2L) == (new(), new()) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(1, 2L) == (new(), new())").WithArguments("==", "new()").WithLocation(10, 23),
// (11,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write((1, 2L) != (new(), new()) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(1, 2L) != (new(), new())").WithArguments("!=", "new()").WithLocation(11, 23),
// (11,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write((1, 2L) != (new(), new()) ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "(1, 2L) != (new(), new())").WithArguments("!=", "new()").WithLocation(11, 23)
);
}
[Fact]
public void TestEquality_Class()
{
string source = @"
using System;
class C
{
static void Main()
{
Console.Write(new C() == new() ? 1 : 0);
Console.Write(new C() != new() ? 1 : 0);
Console.Write(new() == new C() ? 1 : 0);
Console.Write(new() != new C() ? 1 : 0);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (8,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write(new C() == new() ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new C() == new()").WithArguments("==", "new()").WithLocation(8, 23),
// (9,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write(new C() != new() ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new C() != new()").WithArguments("!=", "new()").WithLocation(9, 23),
// (10,23): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.Write(new() == new C() ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == new C()").WithArguments("==", "new()").WithLocation(10, 23),
// (11,23): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.Write(new() != new C() ? 1 : 0);
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != new C()").WithArguments("!=", "new()").WithLocation(11, 23)
);
}
[Fact]
public void TestEquality_Class_UserDefinedOperator()
{
string source = @"
#pragma warning disable CS0660, CS0661
using System;
class D
{
}
class C
{
public static bool operator ==(C o1, C o2) => default;
public static bool operator !=(C o1, C o2) => default;
public static bool operator ==(C o1, D o2) => default;
public static bool operator !=(C o1, D o2) => default;
static void Main()
{
Console.WriteLine(new C() == new());
Console.WriteLine(new() == new C());
Console.WriteLine(new C() != new());
Console.WriteLine(new() != new C());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (18,27): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.WriteLine(new C() == new());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new C() == new()").WithArguments("==", "new()").WithLocation(18, 27),
// (19,27): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.WriteLine(new() == new C());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == new C()").WithArguments("==", "new()").WithLocation(19, 27),
// (20,27): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.WriteLine(new C() != new());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new C() != new()").WithArguments("!=", "new()").WithLocation(20, 27),
// (21,27): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.WriteLine(new() != new C());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != new C()").WithArguments("!=", "new()").WithLocation(21, 27)
);
}
[Fact]
public void TestEquality_Struct()
{
string source = @"
using System;
struct S
{
static void Main()
{
Console.WriteLine(new S() == new());
Console.WriteLine(new() == new S());
Console.WriteLine(new S() != new());
Console.WriteLine(new() != new S());
Console.WriteLine(new S?() == new());
Console.WriteLine(new() == new S?());
Console.WriteLine(new S?() != new());
Console.WriteLine(new() != new S?());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (8,27): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.WriteLine(new S() == new());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S() == new()").WithArguments("==", "new()").WithLocation(8, 27),
// (9,27): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.WriteLine(new() == new S());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == new S()").WithArguments("==", "new()").WithLocation(9, 27),
// (10,27): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.WriteLine(new S() != new());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S() != new()").WithArguments("!=", "new()").WithLocation(10, 27),
// (11,27): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.WriteLine(new() != new S());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != new S()").WithArguments("!=", "new()").WithLocation(11, 27),
// (13,27): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.WriteLine(new S?() == new());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S?() == new()").WithArguments("==", "new()").WithLocation(13, 27),
// (14,27): error CS8310: Operator '==' cannot be applied to operand 'new()'
// Console.WriteLine(new() == new S?());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() == new S?()").WithArguments("==", "new()").WithLocation(14, 27),
// (15,27): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.WriteLine(new S?() != new());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S?() != new()").WithArguments("!=", "new()").WithLocation(15, 27),
// (16,27): error CS8310: Operator '!=' cannot be applied to operand 'new()'
// Console.WriteLine(new() != new S?());
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() != new S?()").WithArguments("!=", "new()").WithLocation(16, 27)
);
}
[Fact]
public void TestEquality_Struct_UserDefinedOperator()
{
string source = @"
#pragma warning disable CS0660, CS0661
using System;
struct S
{
public S(int i)
{
}
public static bool operator ==(S o1, S o2) => default;
public static bool operator !=(S o1, S o2) => default;
static void Main()
{
Console.WriteLine(new S(42) == new(42));
Console.WriteLine(new(42) == new S(42));
Console.WriteLine(new S(42) != new(42));
Console.WriteLine(new(42) != new S(42));
Console.WriteLine(new S?(new(42)) == new(42));
Console.WriteLine(new(42) == new S?(new(42)));
Console.WriteLine(new S?(new(42)) != new(42));
Console.WriteLine(new(42) != new S?(new(42)));
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (16,27): error CS8310: Operator '==' cannot be applied to operand 'new(int)'
// Console.WriteLine(new S(42) == new(42));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S(42) == new(42)").WithArguments("==", "new(int)").WithLocation(16, 27),
// (17,27): error CS8310: Operator '==' cannot be applied to operand 'new(int)'
// Console.WriteLine(new(42) == new S(42));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new(42) == new S(42)").WithArguments("==", "new(int)").WithLocation(17, 27),
// (18,27): error CS8310: Operator '!=' cannot be applied to operand 'new(int)'
// Console.WriteLine(new S(42) != new(42));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S(42) != new(42)").WithArguments("!=", "new(int)").WithLocation(18, 27),
// (19,27): error CS8310: Operator '!=' cannot be applied to operand 'new(int)'
// Console.WriteLine(new(42) != new S(42));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new(42) != new S(42)").WithArguments("!=", "new(int)").WithLocation(19, 27),
// (21,27): error CS8310: Operator '==' cannot be applied to operand 'new(int)'
// Console.WriteLine(new S?(new(42)) == new(42));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S?(new(42)) == new(42)").WithArguments("==", "new(int)").WithLocation(21, 27),
// (22,27): error CS8310: Operator '==' cannot be applied to operand 'new(int)'
// Console.WriteLine(new(42) == new S?(new(42)));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new(42) == new S?(new(42))").WithArguments("==", "new(int)").WithLocation(22, 27),
// (23,27): error CS8310: Operator '!=' cannot be applied to operand 'new(int)'
// Console.WriteLine(new S?(new(42)) != new(42));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new S?(new(42)) != new(42)").WithArguments("!=", "new(int)").WithLocation(23, 27),
// (24,27): error CS8310: Operator '!=' cannot be applied to operand 'new(int)'
// Console.WriteLine(new(42) != new S?(new(42)));
Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new(42) != new S?(new(42))").WithArguments("!=", "new(int)").WithLocation(24, 27)
);
}
[Fact]
public void ArraySize()
{
string source = @"
class C
{
static void Main()
{
var a = new int[new()];
System.Console.Write(a.Length);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "0");
}
[Fact]
public void TernaryOperator01()
{
string source = @"
class C
{
static void Main()
{
bool flag = true;
var x = flag ? new() : 1;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
}
[Fact]
public void TernaryOperator02()
{
string source = @"
class C
{
static void Main()
{
bool flag = true;
System.Console.Write(flag ? new() : new C());
System.Console.Write(flag ? new C() : new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CC");
}
[Fact]
public void TernaryOperator03()
{
string source = @"
class C
{
static void Main()
{
bool flag = true;
System.Console.Write(flag ? new() : new());
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (7,24): error CS0121: The call is ambiguous between the following methods or properties: 'Console.Write(bool)' and 'Console.Write(char)'
// System.Console.Write(flag ? new() : new());
Diagnostic(ErrorCode.ERR_AmbigCall, "Write").WithArguments("System.Console.Write(bool)", "System.Console.Write(char)").WithLocation(7, 24)
);
}
[Fact]
public void NotAType()
{
string source = @"
class C
{
static void Main()
{
((System)new()).ToString();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,11): error CS0118: 'System' is a namespace but is used like a type
// ((System)new()).ToString();
Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "type").WithLocation(6, 11)
);
}
[Fact]
public void TestSpeculativeModel01()
{
string source = @"
class C
{
static void Main()
{
int i = 2;
}
}
";
var comp = CreateCompilation(source, parseOptions: ImplicitObjectCreationTestOptions);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var node = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single();
int nodeLocation = node.Location.SourceSpan.Start;
var newExpression = SyntaxFactory.ParseExpression("new()");
var typeInfo = model.GetSpeculativeTypeInfo(nodeLocation, newExpression, SpeculativeBindingOption.BindAsExpression);
Assert.Null(typeInfo.Type);
var symbolInfo = model.GetSpeculativeSymbolInfo(nodeLocation, newExpression, SpeculativeBindingOption.BindAsExpression);
Assert.True(symbolInfo.IsEmpty);
}
[Fact]
public void TestSpeculativeModel02()
{
string source = @"
class C
{
static void M(int i) {}
static void Main()
{
M(42);
}
}
";
var comp = CreateCompilation(source, parseOptions: ImplicitObjectCreationTestOptions);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var node = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ExpressionStatementSyntax>().Single();
int nodeLocation = node.Location.SourceSpan.Start;
var modifiedNode = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement("M(new());", options: ImplicitObjectCreationTestOptions);
Assert.False(modifiedNode.HasErrors);
bool success = model.TryGetSpeculativeSemanticModel(nodeLocation, modifiedNode, out var speculativeModel);
Assert.True(success);
Assert.NotNull(speculativeModel);
var newExpression = ((InvocationExpressionSyntax)modifiedNode.Expression).ArgumentList.Arguments[0].Expression;
var symbolInfo = speculativeModel.GetSymbolInfo(newExpression);
Assert.Equal("System.Int32..ctor()", symbolInfo.Symbol.ToTestDisplayString());
var typeInfo = speculativeModel.GetTypeInfo(newExpression);
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
}
[Fact]
public void TestInOverloadWithIllegalConversion()
{
var source = @"
class C
{
public static void Main()
{
M(new());
M(array: new());
}
static void M(int[] array) { }
static void M(int i) { }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(int[])' and 'C.M(int)'
// M(new());
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(int[])", "C.M(int)").WithLocation(6, 9),
// (7,18): error CS8752: The type 'int[]' may not be used as the target type of new()
// M(array: new());
Diagnostic(ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, "new()").WithArguments("int[]").WithLocation(7, 18)
);
}
[Fact]
public void TestInOverloadWithUseSiteError()
{
var missing = @"public class Missing { }";
var missingComp = CreateCompilation(missing, assemblyName: "missing");
var lib = @"
public class C
{
public void M(Missing m) { }
public void M(C c) { }
}";
var libComp = CreateCompilation(lib, references: new[] { missingComp.EmitToImageReference() });
var source = @"
class D
{
public void M2(C c)
{
c.M(new());
c.M(default);
c.M(null);
}
}
";
var comp = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() });
comp.VerifyDiagnostics(
// (6,9): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// c.M(new());
Diagnostic(ErrorCode.ERR_NoTypeDef, "c.M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 9),
// (7,9): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// c.M(default);
Diagnostic(ErrorCode.ERR_NoTypeDef, "c.M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 9),
// (8,9): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// c.M(null);
Diagnostic(ErrorCode.ERR_NoTypeDef, "c.M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 9)
);
}
[Fact]
public void TestInConstructorOverloadWithUseSiteError()
{
var missing = @"public class Missing { }";
var missingComp = CreateCompilation(missing, assemblyName: "missing");
var lib = @"
public class C
{
public C(Missing m) => throw null;
public C(D d) => throw null;
}
public class D { }
";
var libComp = CreateCompilation(lib, references: new[] { missingComp.EmitToImageReference() });
var source = @"
class D
{
public void M()
{
new C(new());
new C(default);
new C(null);
C c = new(null);
}
}
";
var comp = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() });
comp.VerifyDiagnostics(
// (6,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// new C(new());
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 13),
// (7,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// new C(default);
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 13),
// (8,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// new C(null);
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 13),
// (9,15): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// C c = new(null);
Diagnostic(ErrorCode.ERR_NoTypeDef, "new(null)").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 15)
);
}
[Fact]
public void ImplicitObjectCreationHasUseSiteError()
{
var missing = @"public class Missing { }";
var missingComp = CreateCompilation(missing, assemblyName: "missing");
var lib = @"
public class C
{
public static void M(Missing m) => throw null;
}
";
var libComp = CreateCompilation(lib, references: new[] { missingComp.EmitToImageReference() });
libComp.VerifyDiagnostics();
var source = @"
class D
{
public void M2()
{
C.M(new());
}
}
";
var comp = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() });
comp.VerifyDiagnostics(
// (6,9): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// C.M(new());
Diagnostic(ErrorCode.ERR_NoTypeDef, "C.M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 9)
);
}
[Fact]
public void ArgumentOfImplicitObjectCreationHasUseSiteError()
{
var missing = @"public class Missing { }";
var missingComp = CreateCompilation(missing, assemblyName: "missing");
var lib = @"
public class C
{
public C(Missing m) => throw null;
}
";
var libComp = CreateCompilation(lib, references: new[] { missingComp.EmitToImageReference() });
libComp.VerifyDiagnostics();
var source = @"
class D
{
public void M(C c) { }
public void M2()
{
M(new(null));
}
}
";
var comp = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() });
comp.VerifyDiagnostics(
// (7,11): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// M(new(null));
Diagnostic(ErrorCode.ERR_NoTypeDef, "new(null)").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 11)
);
}
[Fact]
public void UseSiteWarning()
{
var signedDll = TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2);
var libBTemplate = @"
[assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")]
public class B {{ }}
";
var libBv1 = CreateCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: signedDll);
var libBv2 = CreateCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: signedDll);
var libASource = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")]
public class A
{
public void M(B b) { }
public void M(string s) { }
}
";
var libAv1 = CreateCompilation(
libASource,
new[] { new CSharpCompilationReference(libBv1) },
assemblyName: "A",
options: signedDll);
var source = @"
public class Source
{
public void Test(A a)
{
a.M(new());
a.M(default);
a.M(null);
}
}
";
var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) },
parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1),
// (6,11): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(B)' and 'A.M(string)'
// a.M(new());
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(B)", "A.M(string)").WithLocation(6, 11),
// warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1),
// (7,11): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(B)' and 'A.M(string)'
// a.M(default);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(B)", "A.M(string)").WithLocation(7, 11),
// warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1),
// (8,11): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(B)' and 'A.M(string)'
// a.M(null);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(B)", "A.M(string)").WithLocation(8, 11)
);
}
[Fact, WorkItem(49547, "https://github.com/dotnet/roslyn/issues/49547")]
public void CallerMemberNameAttributeWithImplicitObjectCreation()
{
string source = @"
using System;
using System.Runtime.CompilerServices;
class Test
{
public string Caller { get; set; }
public Test([CallerMemberName] string caller = ""?"") => Caller = caller;
public void PrintCaller() => Console.WriteLine(Caller);
}
class Program
{
static void Main()
{
Test f1 = new Test();
f1.PrintCaller();
Test f2 = new();
f2.PrintCaller();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput:
@"Main
Main").VerifyDiagnostics();
}
[Fact]
public void CallerLineNumberAttributeWithImplicitObjectCreation()
{
string source = @"
using System;
using System.Runtime.CompilerServices;
class Test
{
public int LineNumber { get; set; }
public Test([CallerLineNumber] int lineNumber = -1) => LineNumber = lineNumber;
public void PrintLineNumber() => Console.WriteLine(LineNumber);
}
class Program
{
static void Main()
{
Test f1 = new Test();
f1.PrintLineNumber();
Test f2 = new();
f2.PrintLineNumber();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput:
@"16
19").VerifyDiagnostics();
}
[Fact]
[WorkItem(50030, "https://github.com/dotnet/roslyn/issues/50030")]
public void GetCollectionInitializerSymbolInfo()
{
var source = @"
using System;
using System.Collections.Generic;
class X : List<int>
{
new void Add(int x) { }
void Add(string x) {}
static void Main()
{
X z = new() { String.Empty, 12 };
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
where node.IsKind(SyntaxKind.CollectionInitializerExpression)
select (InitializerExpressionSyntax)node).Single().Expressions;
SymbolInfo symbolInfo;
symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(nodes[0]);
Assert.NotNull(symbolInfo.Symbol);
Assert.Equal("void X.Add(System.String x)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(nodes[1]);
Assert.NotNull(symbolInfo.Symbol);
Assert.Equal("void X.Add(System.Int32 x)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
}
[Fact]
public void GetNamedParameterSymbolInfo()
{
var source = @"
class X
{
X(int aParameter)
{}
static void Main()
{
X z = new(aParameter: 1);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "aParameter").Single();
SymbolInfo symbolInfo;
symbolInfo = semanticModel.GetSymbolInfo(node);
Assert.NotNull(symbolInfo.Symbol);
Assert.Equal("System.Int32 aParameter", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
}
[Fact]
[WorkItem(50489, "https://github.com/dotnet/roslyn/issues/50489")]
public void InEarlyWellknownAttribute_01()
{
var source1 = @"
public class C
{
static void Main()
{
M1();
M2();
}
[System.Obsolete(""reported 1"", new bool())]
static public void M1()
{
}
[System.Obsolete(""reported 2"", new())]
static public void M2()
{
}
}";
var compilation1 = CreateCompilation(source1);
compilation1.VerifyDiagnostics(
// (6,9): warning CS0618: 'C.M1()' is obsolete: 'reported 1'
// M1();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "M1()").WithArguments("C.M1()", "reported 1").WithLocation(6, 9),
// (7,9): warning CS0618: 'C.M2()' is obsolete: 'reported 2'
// M2();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "M2()").WithArguments("C.M2()", "reported 2").WithLocation(7, 9)
);
var source2 = @"
public class B
{
static void Main()
{
C.M1();
C.M2();
}
}";
var compilation2 = CreateCompilation(source2, references: new[] { compilation1.EmitToImageReference() });
compilation2.VerifyDiagnostics(
// (6,9): warning CS0618: 'C.M1()' is obsolete: 'reported 1'
// C.M1();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "C.M1()").WithArguments("C.M1()", "reported 1").WithLocation(6, 9),
// (7,9): warning CS0618: 'C.M2()' is obsolete: 'reported 2'
// C.M2();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "C.M2()").WithArguments("C.M2()", "reported 2").WithLocation(7, 9)
);
}
[Fact]
public void InEarlyWellknownAttribute_02()
{
var source1 = @"
using System.Runtime.InteropServices;
public class C
{
public void M1([DefaultParameterValue(new())] object o)
{
}
public void M2([DefaultParameterValue(new object())] object o)
{
}
}
";
var compilation1 = CreateCompilation(source1);
compilation1.VerifyDiagnostics(
// (6,43): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// public void M1([DefaultParameterValue(new())] object o)
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new()").WithLocation(6, 43),
// (10,43): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// public void M2([DefaultParameterValue(new object())] object o)
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new object()").WithLocation(10, 43)
);
}
[Fact]
public void InEarlyWellknownAttribute_03()
{
var source1 = @"
using System;
[AttributeUsage(new AttributeTargets())]
public class Attr1 : Attribute {}
[AttributeUsage(new())]
public class Attr2 : Attribute {}
";
var compilation1 = CreateCompilation(source1);
compilation1.VerifyDiagnostics(
// (4,17): error CS0591: Invalid value for argument to 'AttributeUsage' attribute
// [AttributeUsage(new AttributeTargets())]
Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "new AttributeTargets()").WithArguments("AttributeUsage").WithLocation(4, 17),
// (7,17): error CS0591: Invalid value for argument to 'AttributeUsage' attribute
// [AttributeUsage(new())]
Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "new()").WithArguments("AttributeUsage").WithLocation(7, 17)
);
}
[Fact]
public void InAttributes()
{
var source = @"
[C(new())]
public class C : System.Attribute
{
public C(C c) {}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (2,2): error CS0181: Attribute constructor parameter 'c' has type 'C', which is not a valid attribute parameter type
// [C(new())]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "C").WithArguments("c", "C").WithLocation(2, 2),
// (2,4): error CS7036: There is no argument given that corresponds to the required formal parameter 'c' of 'C.C(C)'
// [C(new())]
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "new()").WithArguments("c", "C.C(C)").WithLocation(2, 4)
);
}
[Fact, WorkItem(54193, "https://github.com/dotnet/roslyn/issues/54193")]
public void InSwitchExpression()
{
var source = @"
using static System.Console;
var c0 = 0 switch { 1 => new C(), int n => new() { n = n } };
C c1 = 1 switch { int n => new() { n = n } };
C c2 = 2 switch { int n => n switch { int u => new() { n = n + u } } };
Write(c0.n);
Write(c1.n);
Write(c2.n);
class C
{
public int n;
}
";
var compilation = CreateCompilation(source);
CompileAndVerify(compilation, expectedOutput: "014")
.VerifyDiagnostics();
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal sealed class RemoteEditAndContinueService : BrokeredServiceBase, IRemoteEditAndContinueService
{
internal sealed class Factory : FactoryBase<IRemoteEditAndContinueService, IRemoteEditAndContinueService.ICallback>
{
protected override IRemoteEditAndContinueService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteEditAndContinueService.ICallback> callback)
=> new RemoteEditAndContinueService(arguments, callback);
}
private sealed class ManagedEditAndContinueDebuggerService : IManagedEditAndContinueDebuggerService
{
private readonly RemoteCallback<IRemoteEditAndContinueService.ICallback> _callback;
private readonly RemoteServiceCallbackId _callbackId;
public ManagedEditAndContinueDebuggerService(RemoteCallback<IRemoteEditAndContinueService.ICallback> callback, RemoteServiceCallbackId callbackId)
{
_callback = callback;
_callbackId = callbackId;
}
Task<ImmutableArray<ManagedActiveStatementDebugInfo>> IManagedEditAndContinueDebuggerService.GetActiveStatementsAsync(CancellationToken cancellationToken)
=> _callback.InvokeAsync((callback, cancellationToken) => callback.GetActiveStatementsAsync(_callbackId, cancellationToken), cancellationToken).AsTask();
Task<ManagedEditAndContinueAvailability> IManagedEditAndContinueDebuggerService.GetAvailabilityAsync(Guid moduleVersionId, CancellationToken cancellationToken)
=> _callback.InvokeAsync((callback, cancellationToken) => callback.GetAvailabilityAsync(_callbackId, moduleVersionId, cancellationToken), cancellationToken).AsTask();
Task<ImmutableArray<string>> IManagedEditAndContinueDebuggerService.GetCapabilitiesAsync(CancellationToken cancellationToken)
=> _callback.InvokeAsync((callback, cancellationToken) => callback.GetCapabilitiesAsync(_callbackId, cancellationToken), cancellationToken).AsTask();
Task IManagedEditAndContinueDebuggerService.PrepareModuleForUpdateAsync(Guid moduleVersionId, CancellationToken cancellationToken)
=> _callback.InvokeAsync((callback, cancellationToken) => callback.PrepareModuleForUpdateAsync(_callbackId, moduleVersionId, cancellationToken), cancellationToken).AsTask();
}
private readonly RemoteCallback<IRemoteEditAndContinueService.ICallback> _callback;
public RemoteEditAndContinueService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteEditAndContinueService.ICallback> callback)
: base(arguments)
{
_callback = callback;
}
private IEditAndContinueWorkspaceService GetService()
=> GetWorkspace().Services.GetRequiredService<IEditAndContinueWorkspaceService>();
private ActiveStatementSpanProvider CreateActiveStatementSpanProvider(RemoteServiceCallbackId callbackId)
=> new((documentId, filePath, cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetSpansAsync(callbackId, documentId, filePath, cancellationToken), cancellationToken));
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
var debuggerService = new ManagedEditAndContinueDebuggerService(_callback, callbackId);
var sessionId = await GetService().StartDebuggingSessionAsync(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false);
return sessionId;
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<ImmutableArray<DocumentId>> BreakStateEnteredAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken)
{
return RunServiceAsync(cancellationToken =>
{
GetService().BreakStateEntered(sessionId, out var documentsToReanalyze);
return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<ImmutableArray<DocumentId>> EndDebuggingSessionAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken)
{
return RunServiceAsync(cancellationToken =>
{
GetService().EndDebuggingSession(sessionId, out var documentsToReanalyze);
return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<ImmutableArray<DiagnosticData>> GetDocumentDiagnosticsAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
var document = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false);
var diagnostics = await GetService().GetDocumentDiagnosticsAsync(document, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false);
return diagnostics.SelectAsArray(diagnostic => DiagnosticData.Create(diagnostic, document));
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<bool> HasChangesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, string? sourceFilePath, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
return await GetService().HasChangesAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), sourceFilePath, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<EmitSolutionUpdateResults.Data> EmitSolutionUpdateAsync(
PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var service = GetService();
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
try
{
var results = await service.EmitSolutionUpdateAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false);
return results.Dehydrate(solution);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty);
var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.CannotApplyChangesUnexpectedError);
var diagnostic = Diagnostic.Create(descriptor, Location.None, new[] { e.Message });
var diagnostics = ImmutableArray.Create(DiagnosticData.Create(diagnostic, solution.Options));
return new EmitSolutionUpdateResults.Data(updates, diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty);
}
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<ImmutableArray<DocumentId>> CommitSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken)
{
return RunServiceAsync(cancellationToken =>
{
GetService().CommitSolutionUpdate(sessionId, out var documentsToReanalyze);
return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask DiscardSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken)
{
return RunServiceAsync(cancellationToken =>
{
GetService().DiscardSolutionUpdate(sessionId);
return default;
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
return await GetService().GetBaseActiveStatementSpansAsync(sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, DocumentId documentId, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
var document = await solution.GetRequiredTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
return await GetService().GetAdjustedActiveStatementSpansAsync(sessionId, document, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
return await GetService().IsActiveStatementInExceptionRegionAsync(sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
return await GetService().GetCurrentActiveStatementPositionAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), instructionId, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask OnSourceFileUpdatedAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
// TODO: Non-C#/VB documents are not currently serialized to remote workspace.
// https://github.com/dotnet/roslyn/issues/47341
var document = solution.GetDocument(documentId);
if (document != null)
{
GetService().OnSourceFileUpdated(document);
}
}, 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 enable
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal sealed class RemoteEditAndContinueService : BrokeredServiceBase, IRemoteEditAndContinueService
{
internal sealed class Factory : FactoryBase<IRemoteEditAndContinueService, IRemoteEditAndContinueService.ICallback>
{
protected override IRemoteEditAndContinueService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteEditAndContinueService.ICallback> callback)
=> new RemoteEditAndContinueService(arguments, callback);
}
private sealed class ManagedEditAndContinueDebuggerService : IManagedEditAndContinueDebuggerService
{
private readonly RemoteCallback<IRemoteEditAndContinueService.ICallback> _callback;
private readonly RemoteServiceCallbackId _callbackId;
public ManagedEditAndContinueDebuggerService(RemoteCallback<IRemoteEditAndContinueService.ICallback> callback, RemoteServiceCallbackId callbackId)
{
_callback = callback;
_callbackId = callbackId;
}
Task<ImmutableArray<ManagedActiveStatementDebugInfo>> IManagedEditAndContinueDebuggerService.GetActiveStatementsAsync(CancellationToken cancellationToken)
=> _callback.InvokeAsync((callback, cancellationToken) => callback.GetActiveStatementsAsync(_callbackId, cancellationToken), cancellationToken).AsTask();
Task<ManagedEditAndContinueAvailability> IManagedEditAndContinueDebuggerService.GetAvailabilityAsync(Guid moduleVersionId, CancellationToken cancellationToken)
=> _callback.InvokeAsync((callback, cancellationToken) => callback.GetAvailabilityAsync(_callbackId, moduleVersionId, cancellationToken), cancellationToken).AsTask();
Task<ImmutableArray<string>> IManagedEditAndContinueDebuggerService.GetCapabilitiesAsync(CancellationToken cancellationToken)
=> _callback.InvokeAsync((callback, cancellationToken) => callback.GetCapabilitiesAsync(_callbackId, cancellationToken), cancellationToken).AsTask();
Task IManagedEditAndContinueDebuggerService.PrepareModuleForUpdateAsync(Guid moduleVersionId, CancellationToken cancellationToken)
=> _callback.InvokeAsync((callback, cancellationToken) => callback.PrepareModuleForUpdateAsync(_callbackId, moduleVersionId, cancellationToken), cancellationToken).AsTask();
}
private readonly RemoteCallback<IRemoteEditAndContinueService.ICallback> _callback;
public RemoteEditAndContinueService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteEditAndContinueService.ICallback> callback)
: base(arguments)
{
_callback = callback;
}
private IEditAndContinueWorkspaceService GetService()
=> GetWorkspace().Services.GetRequiredService<IEditAndContinueWorkspaceService>();
private ActiveStatementSpanProvider CreateActiveStatementSpanProvider(RemoteServiceCallbackId callbackId)
=> new((documentId, filePath, cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetSpansAsync(callbackId, documentId, filePath, cancellationToken), cancellationToken));
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
var debuggerService = new ManagedEditAndContinueDebuggerService(_callback, callbackId);
var sessionId = await GetService().StartDebuggingSessionAsync(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false);
return sessionId;
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<ImmutableArray<DocumentId>> BreakStateEnteredAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken)
{
return RunServiceAsync(cancellationToken =>
{
GetService().BreakStateEntered(sessionId, out var documentsToReanalyze);
return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<ImmutableArray<DocumentId>> EndDebuggingSessionAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken)
{
return RunServiceAsync(cancellationToken =>
{
GetService().EndDebuggingSession(sessionId, out var documentsToReanalyze);
return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<ImmutableArray<DiagnosticData>> GetDocumentDiagnosticsAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
var document = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false);
var diagnostics = await GetService().GetDocumentDiagnosticsAsync(document, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false);
return diagnostics.SelectAsArray(diagnostic => DiagnosticData.Create(diagnostic, document));
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<bool> HasChangesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, string? sourceFilePath, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
return await GetService().HasChangesAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), sourceFilePath, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<EmitSolutionUpdateResults.Data> EmitSolutionUpdateAsync(
PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var service = GetService();
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
try
{
var results = await service.EmitSolutionUpdateAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false);
return results.Dehydrate(solution);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty);
var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.CannotApplyChangesUnexpectedError);
var diagnostic = Diagnostic.Create(descriptor, Location.None, new[] { e.Message });
var diagnostics = ImmutableArray.Create(DiagnosticData.Create(diagnostic, solution.Options));
return new EmitSolutionUpdateResults.Data(updates, diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty);
}
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<ImmutableArray<DocumentId>> CommitSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken)
{
return RunServiceAsync(cancellationToken =>
{
GetService().CommitSolutionUpdate(sessionId, out var documentsToReanalyze);
return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask DiscardSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken)
{
return RunServiceAsync(cancellationToken =>
{
GetService().DiscardSolutionUpdate(sessionId);
return default;
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
return await GetService().GetBaseActiveStatementSpansAsync(sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, DocumentId documentId, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
var document = await solution.GetRequiredTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
return await GetService().GetAdjustedActiveStatementSpansAsync(sessionId, document, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
return await GetService().IsActiveStatementInExceptionRegionAsync(sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
return await GetService().GetCurrentActiveStatementPositionAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), instructionId, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
}
/// <summary>
/// Remote API.
/// </summary>
public ValueTask OnSourceFileUpdatedAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
// TODO: Non-C#/VB documents are not currently serialized to remote workspace.
// https://github.com/dotnet/roslyn/issues/47341
var document = solution.GetDocument(documentId);
if (document != null)
{
GetService().OnSourceFileUpdated(document);
}
}, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/CSharp/Portable/Compilation/BuiltInOperators.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Internal cache of built-in operators.
/// Cache is compilation-specific because it uses compilation-specific SpecialTypes.
/// </summary>
internal class BuiltInOperators
{
private readonly CSharpCompilation _compilation;
//actual lazily-constructed caches of built-in operators.
private ImmutableArray<UnaryOperatorSignature>[] _builtInUnaryOperators;
private ImmutableArray<BinaryOperatorSignature>[][] _builtInOperators;
internal BuiltInOperators(CSharpCompilation compilation)
{
_compilation = compilation;
}
// PERF: Use int instead of UnaryOperatorKind so the compiler can use array literal initialization.
// The most natural type choice, Enum arrays, are not blittable due to a CLR limitation.
private ImmutableArray<UnaryOperatorSignature> GetSignaturesFromUnaryOperatorKinds(int[] operatorKinds)
{
var builder = ArrayBuilder<UnaryOperatorSignature>.GetInstance();
foreach (var kind in operatorKinds)
{
builder.Add(GetSignature((UnaryOperatorKind)kind));
}
return builder.ToImmutableAndFree();
}
internal void GetSimpleBuiltInOperators(UnaryOperatorKind kind, ArrayBuilder<UnaryOperatorSignature> operators, bool skipNativeIntegerOperators)
{
if (_builtInUnaryOperators == null)
{
var allOperators = new ImmutableArray<UnaryOperatorSignature>[]
{
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.SBytePostfixIncrement,
(int)UnaryOperatorKind.BytePostfixIncrement,
(int)UnaryOperatorKind.ShortPostfixIncrement,
(int)UnaryOperatorKind.UShortPostfixIncrement,
(int)UnaryOperatorKind.IntPostfixIncrement,
(int)UnaryOperatorKind.UIntPostfixIncrement,
(int)UnaryOperatorKind.LongPostfixIncrement,
(int)UnaryOperatorKind.ULongPostfixIncrement,
(int)UnaryOperatorKind.NIntPostfixIncrement,
(int)UnaryOperatorKind.NUIntPostfixIncrement,
(int)UnaryOperatorKind.CharPostfixIncrement,
(int)UnaryOperatorKind.FloatPostfixIncrement,
(int)UnaryOperatorKind.DoublePostfixIncrement,
(int)UnaryOperatorKind.DecimalPostfixIncrement,
(int)UnaryOperatorKind.LiftedSBytePostfixIncrement,
(int)UnaryOperatorKind.LiftedBytePostfixIncrement,
(int)UnaryOperatorKind.LiftedShortPostfixIncrement,
(int)UnaryOperatorKind.LiftedUShortPostfixIncrement,
(int)UnaryOperatorKind.LiftedIntPostfixIncrement,
(int)UnaryOperatorKind.LiftedUIntPostfixIncrement,
(int)UnaryOperatorKind.LiftedLongPostfixIncrement,
(int)UnaryOperatorKind.LiftedULongPostfixIncrement,
(int)UnaryOperatorKind.LiftedNIntPostfixIncrement,
(int)UnaryOperatorKind.LiftedNUIntPostfixIncrement,
(int)UnaryOperatorKind.LiftedCharPostfixIncrement,
(int)UnaryOperatorKind.LiftedFloatPostfixIncrement,
(int)UnaryOperatorKind.LiftedDoublePostfixIncrement,
(int)UnaryOperatorKind.LiftedDecimalPostfixIncrement,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.SBytePostfixDecrement,
(int)UnaryOperatorKind.BytePostfixDecrement,
(int)UnaryOperatorKind.ShortPostfixDecrement,
(int)UnaryOperatorKind.UShortPostfixDecrement,
(int)UnaryOperatorKind.IntPostfixDecrement,
(int)UnaryOperatorKind.UIntPostfixDecrement,
(int)UnaryOperatorKind.LongPostfixDecrement,
(int)UnaryOperatorKind.ULongPostfixDecrement,
(int)UnaryOperatorKind.NIntPostfixDecrement,
(int)UnaryOperatorKind.NUIntPostfixDecrement,
(int)UnaryOperatorKind.CharPostfixDecrement,
(int)UnaryOperatorKind.FloatPostfixDecrement,
(int)UnaryOperatorKind.DoublePostfixDecrement,
(int)UnaryOperatorKind.DecimalPostfixDecrement,
(int)UnaryOperatorKind.LiftedSBytePostfixDecrement,
(int)UnaryOperatorKind.LiftedBytePostfixDecrement,
(int)UnaryOperatorKind.LiftedShortPostfixDecrement,
(int)UnaryOperatorKind.LiftedUShortPostfixDecrement,
(int)UnaryOperatorKind.LiftedIntPostfixDecrement,
(int)UnaryOperatorKind.LiftedUIntPostfixDecrement,
(int)UnaryOperatorKind.LiftedLongPostfixDecrement,
(int)UnaryOperatorKind.LiftedULongPostfixDecrement,
(int)UnaryOperatorKind.LiftedNIntPostfixDecrement,
(int)UnaryOperatorKind.LiftedNUIntPostfixDecrement,
(int)UnaryOperatorKind.LiftedCharPostfixDecrement,
(int)UnaryOperatorKind.LiftedFloatPostfixDecrement,
(int)UnaryOperatorKind.LiftedDoublePostfixDecrement,
(int)UnaryOperatorKind.LiftedDecimalPostfixDecrement,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.SBytePrefixIncrement,
(int)UnaryOperatorKind.BytePrefixIncrement,
(int)UnaryOperatorKind.ShortPrefixIncrement,
(int)UnaryOperatorKind.UShortPrefixIncrement,
(int)UnaryOperatorKind.IntPrefixIncrement,
(int)UnaryOperatorKind.UIntPrefixIncrement,
(int)UnaryOperatorKind.LongPrefixIncrement,
(int)UnaryOperatorKind.ULongPrefixIncrement,
(int)UnaryOperatorKind.NIntPrefixIncrement,
(int)UnaryOperatorKind.NUIntPrefixIncrement,
(int)UnaryOperatorKind.CharPrefixIncrement,
(int)UnaryOperatorKind.FloatPrefixIncrement,
(int)UnaryOperatorKind.DoublePrefixIncrement,
(int)UnaryOperatorKind.DecimalPrefixIncrement,
(int)UnaryOperatorKind.LiftedSBytePrefixIncrement,
(int)UnaryOperatorKind.LiftedBytePrefixIncrement,
(int)UnaryOperatorKind.LiftedShortPrefixIncrement,
(int)UnaryOperatorKind.LiftedUShortPrefixIncrement,
(int)UnaryOperatorKind.LiftedIntPrefixIncrement,
(int)UnaryOperatorKind.LiftedUIntPrefixIncrement,
(int)UnaryOperatorKind.LiftedLongPrefixIncrement,
(int)UnaryOperatorKind.LiftedULongPrefixIncrement,
(int)UnaryOperatorKind.LiftedNIntPrefixIncrement,
(int)UnaryOperatorKind.LiftedNUIntPrefixIncrement,
(int)UnaryOperatorKind.LiftedCharPrefixIncrement,
(int)UnaryOperatorKind.LiftedFloatPrefixIncrement,
(int)UnaryOperatorKind.LiftedDoublePrefixIncrement,
(int)UnaryOperatorKind.LiftedDecimalPrefixIncrement,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.SBytePrefixDecrement,
(int)UnaryOperatorKind.BytePrefixDecrement,
(int)UnaryOperatorKind.ShortPrefixDecrement,
(int)UnaryOperatorKind.UShortPrefixDecrement,
(int)UnaryOperatorKind.IntPrefixDecrement,
(int)UnaryOperatorKind.UIntPrefixDecrement,
(int)UnaryOperatorKind.NIntPrefixDecrement,
(int)UnaryOperatorKind.NUIntPrefixDecrement,
(int)UnaryOperatorKind.LongPrefixDecrement,
(int)UnaryOperatorKind.ULongPrefixDecrement,
(int)UnaryOperatorKind.CharPrefixDecrement,
(int)UnaryOperatorKind.FloatPrefixDecrement,
(int)UnaryOperatorKind.DoublePrefixDecrement,
(int)UnaryOperatorKind.DecimalPrefixDecrement,
(int)UnaryOperatorKind.LiftedSBytePrefixDecrement,
(int)UnaryOperatorKind.LiftedBytePrefixDecrement,
(int)UnaryOperatorKind.LiftedShortPrefixDecrement,
(int)UnaryOperatorKind.LiftedUShortPrefixDecrement,
(int)UnaryOperatorKind.LiftedIntPrefixDecrement,
(int)UnaryOperatorKind.LiftedUIntPrefixDecrement,
(int)UnaryOperatorKind.LiftedLongPrefixDecrement,
(int)UnaryOperatorKind.LiftedULongPrefixDecrement,
(int)UnaryOperatorKind.LiftedNIntPrefixDecrement,
(int)UnaryOperatorKind.LiftedNUIntPrefixDecrement,
(int)UnaryOperatorKind.LiftedCharPrefixDecrement,
(int)UnaryOperatorKind.LiftedFloatPrefixDecrement,
(int)UnaryOperatorKind.LiftedDoublePrefixDecrement,
(int)UnaryOperatorKind.LiftedDecimalPrefixDecrement,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.IntUnaryPlus,
(int)UnaryOperatorKind.UIntUnaryPlus,
(int)UnaryOperatorKind.LongUnaryPlus,
(int)UnaryOperatorKind.ULongUnaryPlus,
(int)UnaryOperatorKind.NIntUnaryPlus,
(int)UnaryOperatorKind.NUIntUnaryPlus,
(int)UnaryOperatorKind.FloatUnaryPlus,
(int)UnaryOperatorKind.DoubleUnaryPlus,
(int)UnaryOperatorKind.DecimalUnaryPlus,
(int)UnaryOperatorKind.LiftedIntUnaryPlus,
(int)UnaryOperatorKind.LiftedUIntUnaryPlus,
(int)UnaryOperatorKind.LiftedLongUnaryPlus,
(int)UnaryOperatorKind.LiftedULongUnaryPlus,
(int)UnaryOperatorKind.LiftedNIntUnaryPlus,
(int)UnaryOperatorKind.LiftedNUIntUnaryPlus,
(int)UnaryOperatorKind.LiftedFloatUnaryPlus,
(int)UnaryOperatorKind.LiftedDoubleUnaryPlus,
(int)UnaryOperatorKind.LiftedDecimalUnaryPlus,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.IntUnaryMinus,
(int)UnaryOperatorKind.LongUnaryMinus,
(int)UnaryOperatorKind.NIntUnaryMinus,
(int)UnaryOperatorKind.FloatUnaryMinus,
(int)UnaryOperatorKind.DoubleUnaryMinus,
(int)UnaryOperatorKind.DecimalUnaryMinus,
(int)UnaryOperatorKind.LiftedIntUnaryMinus,
(int)UnaryOperatorKind.LiftedLongUnaryMinus,
(int)UnaryOperatorKind.LiftedNIntUnaryMinus,
(int)UnaryOperatorKind.LiftedFloatUnaryMinus,
(int)UnaryOperatorKind.LiftedDoubleUnaryMinus,
(int)UnaryOperatorKind.LiftedDecimalUnaryMinus,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.BoolLogicalNegation,
(int)UnaryOperatorKind.LiftedBoolLogicalNegation,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.IntBitwiseComplement,
(int)UnaryOperatorKind.UIntBitwiseComplement,
(int)UnaryOperatorKind.LongBitwiseComplement,
(int)UnaryOperatorKind.ULongBitwiseComplement,
(int)UnaryOperatorKind.NIntBitwiseComplement,
(int)UnaryOperatorKind.NUIntBitwiseComplement,
(int)UnaryOperatorKind.LiftedIntBitwiseComplement,
(int)UnaryOperatorKind.LiftedUIntBitwiseComplement,
(int)UnaryOperatorKind.LiftedLongBitwiseComplement,
(int)UnaryOperatorKind.LiftedULongBitwiseComplement,
(int)UnaryOperatorKind.LiftedNIntBitwiseComplement,
(int)UnaryOperatorKind.LiftedNUIntBitwiseComplement,
}),
// No built-in operator true or operator false
ImmutableArray<UnaryOperatorSignature>.Empty,
ImmutableArray<UnaryOperatorSignature>.Empty,
};
Interlocked.CompareExchange(ref _builtInUnaryOperators, allOperators, null);
}
foreach (var op in _builtInUnaryOperators[kind.OperatorIndex()])
{
if (skipNativeIntegerOperators)
{
switch (op.Kind.OperandTypes())
{
case UnaryOperatorKind.NInt:
case UnaryOperatorKind.NUInt:
continue;
}
}
operators.Add(op);
}
}
internal UnaryOperatorSignature GetSignature(UnaryOperatorKind kind)
{
TypeSymbol opType;
switch (kind.OperandTypes())
{
case UnaryOperatorKind.SByte: opType = _compilation.GetSpecialType(SpecialType.System_SByte); break;
case UnaryOperatorKind.Byte: opType = _compilation.GetSpecialType(SpecialType.System_Byte); break;
case UnaryOperatorKind.Short: opType = _compilation.GetSpecialType(SpecialType.System_Int16); break;
case UnaryOperatorKind.UShort: opType = _compilation.GetSpecialType(SpecialType.System_UInt16); break;
case UnaryOperatorKind.Int: opType = _compilation.GetSpecialType(SpecialType.System_Int32); break;
case UnaryOperatorKind.UInt: opType = _compilation.GetSpecialType(SpecialType.System_UInt32); break;
case UnaryOperatorKind.Long: opType = _compilation.GetSpecialType(SpecialType.System_Int64); break;
case UnaryOperatorKind.ULong: opType = _compilation.GetSpecialType(SpecialType.System_UInt64); break;
case UnaryOperatorKind.NInt: opType = _compilation.CreateNativeIntegerTypeSymbol(signed: true); break;
case UnaryOperatorKind.NUInt: opType = _compilation.CreateNativeIntegerTypeSymbol(signed: false); break;
case UnaryOperatorKind.Char: opType = _compilation.GetSpecialType(SpecialType.System_Char); break;
case UnaryOperatorKind.Float: opType = _compilation.GetSpecialType(SpecialType.System_Single); break;
case UnaryOperatorKind.Double: opType = _compilation.GetSpecialType(SpecialType.System_Double); break;
case UnaryOperatorKind.Decimal: opType = _compilation.GetSpecialType(SpecialType.System_Decimal); break;
case UnaryOperatorKind.Bool: opType = _compilation.GetSpecialType(SpecialType.System_Boolean); break;
default: throw ExceptionUtilities.UnexpectedValue(kind.OperandTypes());
}
if (kind.IsLifted())
{
opType = _compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(opType);
}
return new UnaryOperatorSignature(kind, opType, opType);
}
// PERF: Use int instead of BinaryOperatorKind so the compiler can use array literal initialization.
// The most natural type choice, Enum arrays, are not blittable due to a CLR limitation.
private ImmutableArray<BinaryOperatorSignature> GetSignaturesFromBinaryOperatorKinds(int[] operatorKinds)
{
var builder = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
foreach (var kind in operatorKinds)
{
builder.Add(GetSignature((BinaryOperatorKind)kind));
}
return builder.ToImmutableAndFree();
}
internal void GetSimpleBuiltInOperators(BinaryOperatorKind kind, ArrayBuilder<BinaryOperatorSignature> operators, bool skipNativeIntegerOperators)
{
if (_builtInOperators == null)
{
var logicalOperators = new ImmutableArray<BinaryOperatorSignature>[]
{
ImmutableArray<BinaryOperatorSignature>.Empty, //multiplication
ImmutableArray<BinaryOperatorSignature>.Empty, //addition
ImmutableArray<BinaryOperatorSignature>.Empty, //subtraction
ImmutableArray<BinaryOperatorSignature>.Empty, //division
ImmutableArray<BinaryOperatorSignature>.Empty, //remainder
ImmutableArray<BinaryOperatorSignature>.Empty, //left shift
ImmutableArray<BinaryOperatorSignature>.Empty, //right shift
ImmutableArray<BinaryOperatorSignature>.Empty, //equal
ImmutableArray<BinaryOperatorSignature>.Empty, //not equal
ImmutableArray<BinaryOperatorSignature>.Empty, //greater than
ImmutableArray<BinaryOperatorSignature>.Empty, //less than
ImmutableArray<BinaryOperatorSignature>.Empty, //greater than or equal
ImmutableArray<BinaryOperatorSignature>.Empty, //less than or equal
ImmutableArray.Create<BinaryOperatorSignature>(GetSignature(BinaryOperatorKind.LogicalBoolAnd)), //and
ImmutableArray<BinaryOperatorSignature>.Empty, //xor
ImmutableArray.Create<BinaryOperatorSignature>(GetSignature(BinaryOperatorKind.LogicalBoolOr)), //or
};
var nonLogicalOperators = new ImmutableArray<BinaryOperatorSignature>[]
{
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntMultiplication,
(int)BinaryOperatorKind.UIntMultiplication,
(int)BinaryOperatorKind.LongMultiplication,
(int)BinaryOperatorKind.ULongMultiplication,
(int)BinaryOperatorKind.NIntMultiplication,
(int)BinaryOperatorKind.NUIntMultiplication,
(int)BinaryOperatorKind.FloatMultiplication,
(int)BinaryOperatorKind.DoubleMultiplication,
(int)BinaryOperatorKind.DecimalMultiplication,
(int)BinaryOperatorKind.LiftedIntMultiplication,
(int)BinaryOperatorKind.LiftedUIntMultiplication,
(int)BinaryOperatorKind.LiftedLongMultiplication,
(int)BinaryOperatorKind.LiftedULongMultiplication,
(int)BinaryOperatorKind.LiftedNIntMultiplication,
(int)BinaryOperatorKind.LiftedNUIntMultiplication,
(int)BinaryOperatorKind.LiftedFloatMultiplication,
(int)BinaryOperatorKind.LiftedDoubleMultiplication,
(int)BinaryOperatorKind.LiftedDecimalMultiplication,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntAddition,
(int)BinaryOperatorKind.UIntAddition,
(int)BinaryOperatorKind.LongAddition,
(int)BinaryOperatorKind.ULongAddition,
(int)BinaryOperatorKind.NIntAddition,
(int)BinaryOperatorKind.NUIntAddition,
(int)BinaryOperatorKind.FloatAddition,
(int)BinaryOperatorKind.DoubleAddition,
(int)BinaryOperatorKind.DecimalAddition,
(int)BinaryOperatorKind.LiftedIntAddition,
(int)BinaryOperatorKind.LiftedUIntAddition,
(int)BinaryOperatorKind.LiftedLongAddition,
(int)BinaryOperatorKind.LiftedULongAddition,
(int)BinaryOperatorKind.LiftedNIntAddition,
(int)BinaryOperatorKind.LiftedNUIntAddition,
(int)BinaryOperatorKind.LiftedFloatAddition,
(int)BinaryOperatorKind.LiftedDoubleAddition,
(int)BinaryOperatorKind.LiftedDecimalAddition,
(int)BinaryOperatorKind.StringConcatenation,
(int)BinaryOperatorKind.StringAndObjectConcatenation,
(int)BinaryOperatorKind.ObjectAndStringConcatenation,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntSubtraction,
(int)BinaryOperatorKind.UIntSubtraction,
(int)BinaryOperatorKind.LongSubtraction,
(int)BinaryOperatorKind.ULongSubtraction,
(int)BinaryOperatorKind.NIntSubtraction,
(int)BinaryOperatorKind.NUIntSubtraction,
(int)BinaryOperatorKind.FloatSubtraction,
(int)BinaryOperatorKind.DoubleSubtraction,
(int)BinaryOperatorKind.DecimalSubtraction,
(int)BinaryOperatorKind.LiftedIntSubtraction,
(int)BinaryOperatorKind.LiftedUIntSubtraction,
(int)BinaryOperatorKind.LiftedLongSubtraction,
(int)BinaryOperatorKind.LiftedULongSubtraction,
(int)BinaryOperatorKind.LiftedNIntSubtraction,
(int)BinaryOperatorKind.LiftedNUIntSubtraction,
(int)BinaryOperatorKind.LiftedFloatSubtraction,
(int)BinaryOperatorKind.LiftedDoubleSubtraction,
(int)BinaryOperatorKind.LiftedDecimalSubtraction,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntDivision,
(int)BinaryOperatorKind.UIntDivision,
(int)BinaryOperatorKind.LongDivision,
(int)BinaryOperatorKind.ULongDivision,
(int)BinaryOperatorKind.NIntDivision,
(int)BinaryOperatorKind.NUIntDivision,
(int)BinaryOperatorKind.FloatDivision,
(int)BinaryOperatorKind.DoubleDivision,
(int)BinaryOperatorKind.DecimalDivision,
(int)BinaryOperatorKind.LiftedIntDivision,
(int)BinaryOperatorKind.LiftedUIntDivision,
(int)BinaryOperatorKind.LiftedLongDivision,
(int)BinaryOperatorKind.LiftedULongDivision,
(int)BinaryOperatorKind.LiftedNIntDivision,
(int)BinaryOperatorKind.LiftedNUIntDivision,
(int)BinaryOperatorKind.LiftedFloatDivision,
(int)BinaryOperatorKind.LiftedDoubleDivision,
(int)BinaryOperatorKind.LiftedDecimalDivision,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntRemainder,
(int)BinaryOperatorKind.UIntRemainder,
(int)BinaryOperatorKind.LongRemainder,
(int)BinaryOperatorKind.ULongRemainder,
(int)BinaryOperatorKind.NIntRemainder,
(int)BinaryOperatorKind.NUIntRemainder,
(int)BinaryOperatorKind.FloatRemainder,
(int)BinaryOperatorKind.DoubleRemainder,
(int)BinaryOperatorKind.DecimalRemainder,
(int)BinaryOperatorKind.LiftedIntRemainder,
(int)BinaryOperatorKind.LiftedUIntRemainder,
(int)BinaryOperatorKind.LiftedLongRemainder,
(int)BinaryOperatorKind.LiftedULongRemainder,
(int)BinaryOperatorKind.LiftedNIntRemainder,
(int)BinaryOperatorKind.LiftedNUIntRemainder,
(int)BinaryOperatorKind.LiftedFloatRemainder,
(int)BinaryOperatorKind.LiftedDoubleRemainder,
(int)BinaryOperatorKind.LiftedDecimalRemainder,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntLeftShift,
(int)BinaryOperatorKind.UIntLeftShift,
(int)BinaryOperatorKind.LongLeftShift,
(int)BinaryOperatorKind.ULongLeftShift,
(int)BinaryOperatorKind.NIntLeftShift,
(int)BinaryOperatorKind.NUIntLeftShift,
(int)BinaryOperatorKind.LiftedIntLeftShift,
(int)BinaryOperatorKind.LiftedUIntLeftShift,
(int)BinaryOperatorKind.LiftedLongLeftShift,
(int)BinaryOperatorKind.LiftedULongLeftShift,
(int)BinaryOperatorKind.LiftedNIntLeftShift,
(int)BinaryOperatorKind.LiftedNUIntLeftShift,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntRightShift,
(int)BinaryOperatorKind.UIntRightShift,
(int)BinaryOperatorKind.LongRightShift,
(int)BinaryOperatorKind.ULongRightShift,
(int)BinaryOperatorKind.NIntRightShift,
(int)BinaryOperatorKind.NUIntRightShift,
(int)BinaryOperatorKind.LiftedIntRightShift,
(int)BinaryOperatorKind.LiftedUIntRightShift,
(int)BinaryOperatorKind.LiftedLongRightShift,
(int)BinaryOperatorKind.LiftedULongRightShift,
(int)BinaryOperatorKind.LiftedNIntRightShift,
(int)BinaryOperatorKind.LiftedNUIntRightShift,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntEqual,
(int)BinaryOperatorKind.UIntEqual,
(int)BinaryOperatorKind.LongEqual,
(int)BinaryOperatorKind.ULongEqual,
(int)BinaryOperatorKind.NIntEqual,
(int)BinaryOperatorKind.NUIntEqual,
(int)BinaryOperatorKind.FloatEqual,
(int)BinaryOperatorKind.DoubleEqual,
(int)BinaryOperatorKind.DecimalEqual,
(int)BinaryOperatorKind.BoolEqual,
(int)BinaryOperatorKind.LiftedIntEqual,
(int)BinaryOperatorKind.LiftedUIntEqual,
(int)BinaryOperatorKind.LiftedLongEqual,
(int)BinaryOperatorKind.LiftedULongEqual,
(int)BinaryOperatorKind.LiftedNIntEqual,
(int)BinaryOperatorKind.LiftedNUIntEqual,
(int)BinaryOperatorKind.LiftedFloatEqual,
(int)BinaryOperatorKind.LiftedDoubleEqual,
(int)BinaryOperatorKind.LiftedDecimalEqual,
(int)BinaryOperatorKind.LiftedBoolEqual,
(int)BinaryOperatorKind.ObjectEqual,
(int)BinaryOperatorKind.StringEqual,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntNotEqual,
(int)BinaryOperatorKind.UIntNotEqual,
(int)BinaryOperatorKind.LongNotEqual,
(int)BinaryOperatorKind.ULongNotEqual,
(int)BinaryOperatorKind.NIntNotEqual,
(int)BinaryOperatorKind.NUIntNotEqual,
(int)BinaryOperatorKind.FloatNotEqual,
(int)BinaryOperatorKind.DoubleNotEqual,
(int)BinaryOperatorKind.DecimalNotEqual,
(int)BinaryOperatorKind.BoolNotEqual,
(int)BinaryOperatorKind.LiftedIntNotEqual,
(int)BinaryOperatorKind.LiftedUIntNotEqual,
(int)BinaryOperatorKind.LiftedLongNotEqual,
(int)BinaryOperatorKind.LiftedULongNotEqual,
(int)BinaryOperatorKind.LiftedNIntNotEqual,
(int)BinaryOperatorKind.LiftedNUIntNotEqual,
(int)BinaryOperatorKind.LiftedFloatNotEqual,
(int)BinaryOperatorKind.LiftedDoubleNotEqual,
(int)BinaryOperatorKind.LiftedDecimalNotEqual,
(int)BinaryOperatorKind.LiftedBoolNotEqual,
(int)BinaryOperatorKind.ObjectNotEqual,
(int)BinaryOperatorKind.StringNotEqual,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntGreaterThan,
(int)BinaryOperatorKind.UIntGreaterThan,
(int)BinaryOperatorKind.LongGreaterThan,
(int)BinaryOperatorKind.ULongGreaterThan,
(int)BinaryOperatorKind.NIntGreaterThan,
(int)BinaryOperatorKind.NUIntGreaterThan,
(int)BinaryOperatorKind.FloatGreaterThan,
(int)BinaryOperatorKind.DoubleGreaterThan,
(int)BinaryOperatorKind.DecimalGreaterThan,
(int)BinaryOperatorKind.LiftedIntGreaterThan,
(int)BinaryOperatorKind.LiftedUIntGreaterThan,
(int)BinaryOperatorKind.LiftedLongGreaterThan,
(int)BinaryOperatorKind.LiftedULongGreaterThan,
(int)BinaryOperatorKind.LiftedNIntGreaterThan,
(int)BinaryOperatorKind.LiftedNUIntGreaterThan,
(int)BinaryOperatorKind.LiftedFloatGreaterThan,
(int)BinaryOperatorKind.LiftedDoubleGreaterThan,
(int)BinaryOperatorKind.LiftedDecimalGreaterThan,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntLessThan,
(int)BinaryOperatorKind.UIntLessThan,
(int)BinaryOperatorKind.LongLessThan,
(int)BinaryOperatorKind.ULongLessThan,
(int)BinaryOperatorKind.NIntLessThan,
(int)BinaryOperatorKind.NUIntLessThan,
(int)BinaryOperatorKind.FloatLessThan,
(int)BinaryOperatorKind.DoubleLessThan,
(int)BinaryOperatorKind.DecimalLessThan,
(int)BinaryOperatorKind.LiftedIntLessThan,
(int)BinaryOperatorKind.LiftedUIntLessThan,
(int)BinaryOperatorKind.LiftedLongLessThan,
(int)BinaryOperatorKind.LiftedULongLessThan,
(int)BinaryOperatorKind.LiftedNIntLessThan,
(int)BinaryOperatorKind.LiftedNUIntLessThan,
(int)BinaryOperatorKind.LiftedFloatLessThan,
(int)BinaryOperatorKind.LiftedDoubleLessThan,
(int)BinaryOperatorKind.LiftedDecimalLessThan,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntGreaterThanOrEqual,
(int)BinaryOperatorKind.UIntGreaterThanOrEqual,
(int)BinaryOperatorKind.LongGreaterThanOrEqual,
(int)BinaryOperatorKind.ULongGreaterThanOrEqual,
(int)BinaryOperatorKind.NIntGreaterThanOrEqual,
(int)BinaryOperatorKind.NUIntGreaterThanOrEqual,
(int)BinaryOperatorKind.FloatGreaterThanOrEqual,
(int)BinaryOperatorKind.DoubleGreaterThanOrEqual,
(int)BinaryOperatorKind.DecimalGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedIntGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedUIntGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedLongGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedULongGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedNIntGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedNUIntGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedFloatGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedDoubleGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedDecimalGreaterThanOrEqual,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntLessThanOrEqual,
(int)BinaryOperatorKind.UIntLessThanOrEqual,
(int)BinaryOperatorKind.LongLessThanOrEqual,
(int)BinaryOperatorKind.ULongLessThanOrEqual,
(int)BinaryOperatorKind.NIntLessThanOrEqual,
(int)BinaryOperatorKind.NUIntLessThanOrEqual,
(int)BinaryOperatorKind.FloatLessThanOrEqual,
(int)BinaryOperatorKind.DoubleLessThanOrEqual,
(int)BinaryOperatorKind.DecimalLessThanOrEqual,
(int)BinaryOperatorKind.LiftedIntLessThanOrEqual,
(int)BinaryOperatorKind.LiftedUIntLessThanOrEqual,
(int)BinaryOperatorKind.LiftedLongLessThanOrEqual,
(int)BinaryOperatorKind.LiftedULongLessThanOrEqual,
(int)BinaryOperatorKind.LiftedNIntLessThanOrEqual,
(int)BinaryOperatorKind.LiftedNUIntLessThanOrEqual,
(int)BinaryOperatorKind.LiftedFloatLessThanOrEqual,
(int)BinaryOperatorKind.LiftedDoubleLessThanOrEqual,
(int)BinaryOperatorKind.LiftedDecimalLessThanOrEqual,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntAnd,
(int)BinaryOperatorKind.UIntAnd,
(int)BinaryOperatorKind.LongAnd,
(int)BinaryOperatorKind.ULongAnd,
(int)BinaryOperatorKind.NIntAnd,
(int)BinaryOperatorKind.NUIntAnd,
(int)BinaryOperatorKind.BoolAnd,
(int)BinaryOperatorKind.LiftedIntAnd,
(int)BinaryOperatorKind.LiftedUIntAnd,
(int)BinaryOperatorKind.LiftedLongAnd,
(int)BinaryOperatorKind.LiftedULongAnd,
(int)BinaryOperatorKind.LiftedNIntAnd,
(int)BinaryOperatorKind.LiftedNUIntAnd,
(int)BinaryOperatorKind.LiftedBoolAnd,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntXor,
(int)BinaryOperatorKind.UIntXor,
(int)BinaryOperatorKind.LongXor,
(int)BinaryOperatorKind.ULongXor,
(int)BinaryOperatorKind.NIntXor,
(int)BinaryOperatorKind.NUIntXor,
(int)BinaryOperatorKind.BoolXor,
(int)BinaryOperatorKind.LiftedIntXor,
(int)BinaryOperatorKind.LiftedUIntXor,
(int)BinaryOperatorKind.LiftedLongXor,
(int)BinaryOperatorKind.LiftedULongXor,
(int)BinaryOperatorKind.LiftedNIntXor,
(int)BinaryOperatorKind.LiftedNUIntXor,
(int)BinaryOperatorKind.LiftedBoolXor,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntOr,
(int)BinaryOperatorKind.UIntOr,
(int)BinaryOperatorKind.LongOr,
(int)BinaryOperatorKind.ULongOr,
(int)BinaryOperatorKind.NIntOr,
(int)BinaryOperatorKind.NUIntOr,
(int)BinaryOperatorKind.BoolOr,
(int)BinaryOperatorKind.LiftedIntOr,
(int)BinaryOperatorKind.LiftedUIntOr,
(int)BinaryOperatorKind.LiftedLongOr,
(int)BinaryOperatorKind.LiftedULongOr,
(int)BinaryOperatorKind.LiftedNIntOr,
(int)BinaryOperatorKind.LiftedNUIntOr,
(int)BinaryOperatorKind.LiftedBoolOr,
}),
};
var allOperators = new[] { nonLogicalOperators, logicalOperators };
Interlocked.CompareExchange(ref _builtInOperators, allOperators, null);
}
foreach (var op in _builtInOperators[kind.IsLogical() ? 1 : 0][kind.OperatorIndex()])
{
if (skipNativeIntegerOperators)
{
switch (op.Kind.OperandTypes())
{
case BinaryOperatorKind.NInt:
case BinaryOperatorKind.NUInt:
continue;
}
}
operators.Add(op);
}
}
internal BinaryOperatorSignature GetSignature(BinaryOperatorKind kind)
{
var left = LeftType(kind);
switch (kind.Operator())
{
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Division:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Remainder:
case BinaryOperatorKind.And:
case BinaryOperatorKind.Or:
case BinaryOperatorKind.Xor:
return new BinaryOperatorSignature(kind, left, left, left);
case BinaryOperatorKind.Addition:
return new BinaryOperatorSignature(kind, left, RightType(kind), ReturnType(kind));
case BinaryOperatorKind.LeftShift:
case BinaryOperatorKind.RightShift:
TypeSymbol rightType = _compilation.GetSpecialType(SpecialType.System_Int32);
if (kind.IsLifted())
{
rightType = _compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(rightType);
}
return new BinaryOperatorSignature(kind, left, rightType, left);
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
return new BinaryOperatorSignature(kind, left, left, _compilation.GetSpecialType(SpecialType.System_Boolean));
}
return new BinaryOperatorSignature(kind, left, RightType(kind), ReturnType(kind));
}
private TypeSymbol LeftType(BinaryOperatorKind kind)
{
if (kind.IsLifted())
{
return LiftedType(kind);
}
else
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Int: return _compilation.GetSpecialType(SpecialType.System_Int32);
case BinaryOperatorKind.UInt: return _compilation.GetSpecialType(SpecialType.System_UInt32);
case BinaryOperatorKind.Long: return _compilation.GetSpecialType(SpecialType.System_Int64);
case BinaryOperatorKind.ULong: return _compilation.GetSpecialType(SpecialType.System_UInt64);
case BinaryOperatorKind.NInt: return _compilation.CreateNativeIntegerTypeSymbol(signed: true);
case BinaryOperatorKind.NUInt: return _compilation.CreateNativeIntegerTypeSymbol(signed: false);
case BinaryOperatorKind.Float: return _compilation.GetSpecialType(SpecialType.System_Single);
case BinaryOperatorKind.Double: return _compilation.GetSpecialType(SpecialType.System_Double);
case BinaryOperatorKind.Decimal: return _compilation.GetSpecialType(SpecialType.System_Decimal);
case BinaryOperatorKind.Bool: return _compilation.GetSpecialType(SpecialType.System_Boolean);
case BinaryOperatorKind.ObjectAndString:
case BinaryOperatorKind.Object:
return _compilation.GetSpecialType(SpecialType.System_Object);
case BinaryOperatorKind.String:
case BinaryOperatorKind.StringAndObject:
return _compilation.GetSpecialType(SpecialType.System_String);
}
}
Debug.Assert(false, "Bad operator kind in left type");
return null;
}
private TypeSymbol RightType(BinaryOperatorKind kind)
{
if (kind.IsLifted())
{
return LiftedType(kind);
}
else
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Int: return _compilation.GetSpecialType(SpecialType.System_Int32);
case BinaryOperatorKind.UInt: return _compilation.GetSpecialType(SpecialType.System_UInt32);
case BinaryOperatorKind.Long: return _compilation.GetSpecialType(SpecialType.System_Int64);
case BinaryOperatorKind.ULong: return _compilation.GetSpecialType(SpecialType.System_UInt64);
case BinaryOperatorKind.NInt: return _compilation.CreateNativeIntegerTypeSymbol(signed: true);
case BinaryOperatorKind.NUInt: return _compilation.CreateNativeIntegerTypeSymbol(signed: false);
case BinaryOperatorKind.Float: return _compilation.GetSpecialType(SpecialType.System_Single);
case BinaryOperatorKind.Double: return _compilation.GetSpecialType(SpecialType.System_Double);
case BinaryOperatorKind.Decimal: return _compilation.GetSpecialType(SpecialType.System_Decimal);
case BinaryOperatorKind.Bool: return _compilation.GetSpecialType(SpecialType.System_Boolean);
case BinaryOperatorKind.ObjectAndString:
case BinaryOperatorKind.String:
return _compilation.GetSpecialType(SpecialType.System_String);
case BinaryOperatorKind.StringAndObject:
case BinaryOperatorKind.Object:
return _compilation.GetSpecialType(SpecialType.System_Object);
}
}
Debug.Assert(false, "Bad operator kind in right type");
return null;
}
private TypeSymbol ReturnType(BinaryOperatorKind kind)
{
if (kind.IsLifted())
{
return LiftedType(kind);
}
else
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Int: return _compilation.GetSpecialType(SpecialType.System_Int32);
case BinaryOperatorKind.UInt: return _compilation.GetSpecialType(SpecialType.System_UInt32);
case BinaryOperatorKind.Long: return _compilation.GetSpecialType(SpecialType.System_Int64);
case BinaryOperatorKind.ULong: return _compilation.GetSpecialType(SpecialType.System_UInt64);
case BinaryOperatorKind.NInt: return _compilation.CreateNativeIntegerTypeSymbol(signed: true);
case BinaryOperatorKind.NUInt: return _compilation.CreateNativeIntegerTypeSymbol(signed: false);
case BinaryOperatorKind.Float: return _compilation.GetSpecialType(SpecialType.System_Single);
case BinaryOperatorKind.Double: return _compilation.GetSpecialType(SpecialType.System_Double);
case BinaryOperatorKind.Decimal: return _compilation.GetSpecialType(SpecialType.System_Decimal);
case BinaryOperatorKind.Bool: return _compilation.GetSpecialType(SpecialType.System_Boolean);
case BinaryOperatorKind.Object: return _compilation.GetSpecialType(SpecialType.System_Object);
case BinaryOperatorKind.ObjectAndString:
case BinaryOperatorKind.StringAndObject:
case BinaryOperatorKind.String:
return _compilation.GetSpecialType(SpecialType.System_String);
}
}
Debug.Assert(false, "Bad operator kind in return type");
return null;
}
private TypeSymbol LiftedType(BinaryOperatorKind kind)
{
Debug.Assert(kind.IsLifted());
var nullable = _compilation.GetSpecialType(SpecialType.System_Nullable_T);
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Int: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_Int32));
case BinaryOperatorKind.UInt: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_UInt32));
case BinaryOperatorKind.Long: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_Int64));
case BinaryOperatorKind.ULong: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_UInt64));
case BinaryOperatorKind.NInt: return nullable.Construct(_compilation.CreateNativeIntegerTypeSymbol(signed: true));
case BinaryOperatorKind.NUInt: return nullable.Construct(_compilation.CreateNativeIntegerTypeSymbol(signed: false));
case BinaryOperatorKind.Float: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_Single));
case BinaryOperatorKind.Double: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_Double));
case BinaryOperatorKind.Decimal: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_Decimal));
case BinaryOperatorKind.Bool: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_Boolean));
}
Debug.Assert(false, "Bad operator kind in lifted type");
return null;
}
internal static bool IsValidObjectEquality(Conversions Conversions, TypeSymbol leftType, bool leftIsNull, bool leftIsDefault, TypeSymbol rightType, bool rightIsNull, bool rightIsDefault, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
// SPEC: The predefined reference type equality operators require one of the following:
// SPEC: (1) Both operands are a value of a type known to be a reference-type or the literal null.
// SPEC: Furthermore, an explicit reference conversion exists from the type of either
// SPEC: operand to the type of the other operand. Or:
// SPEC: (2) One operand is a value of type T where T is a type-parameter and the other operand is
// SPEC: the literal null. Furthermore T does not have the value type constraint.
// SPEC: (3) One operand is the literal default and the other operand is a reference-type.
// SPEC ERROR: Notice that the spec calls out that an explicit reference conversion must exist;
// SPEC ERROR: in fact it should say that an explicit reference conversion, implicit reference
// SPEC ERROR: conversion or identity conversion must exist. The conversion from object to object
// SPEC ERROR: is not classified as a reference conversion at all; it is an identity conversion.
// Dev10 does not follow the spec exactly for type parameters. Specifically, in Dev10,
// if a type parameter argument is known to be a value type, or if a type parameter
// argument is not known to be either a value type or reference type and the other
// argument is not null, reference type equality cannot be applied. Otherwise, the
// effective base class of the type parameter is used to determine the conversion
// to the other argument type. (See ExpressionBinder::GetRefEqualSigs.)
if (((object)leftType != null) && leftType.IsTypeParameter())
{
if (leftType.IsValueType || (!leftType.IsReferenceType && !rightIsNull))
{
return false;
}
leftType = ((TypeParameterSymbol)leftType).EffectiveBaseClass(ref useSiteInfo);
Debug.Assert((object)leftType != null);
}
if (((object)rightType != null) && rightType.IsTypeParameter())
{
if (rightType.IsValueType || (!rightType.IsReferenceType && !leftIsNull))
{
return false;
}
rightType = ((TypeParameterSymbol)rightType).EffectiveBaseClass(ref useSiteInfo);
Debug.Assert((object)rightType != null);
}
var leftIsReferenceType = ((object)leftType != null) && leftType.IsReferenceType;
if (!leftIsReferenceType && !leftIsNull && !leftIsDefault)
{
return false;
}
var rightIsReferenceType = ((object)rightType != null) && rightType.IsReferenceType;
if (!rightIsReferenceType && !rightIsNull && !rightIsDefault)
{
return false;
}
if (leftIsDefault && rightIsDefault)
{
return false;
}
if (leftIsDefault && rightIsNull)
{
return false;
}
if (leftIsNull && rightIsDefault)
{
return false;
}
// If at least one side is null or default then clearly a conversion exists.
if (leftIsNull || rightIsNull || leftIsDefault || rightIsDefault)
{
return true;
}
var leftConversion = Conversions.ClassifyConversionFromType(leftType, rightType, ref useSiteInfo);
if (leftConversion.IsIdentity || leftConversion.IsReference)
{
return true;
}
var rightConversion = Conversions.ClassifyConversionFromType(rightType, leftType, ref useSiteInfo);
if (rightConversion.IsIdentity || rightConversion.IsReference)
{
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.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Internal cache of built-in operators.
/// Cache is compilation-specific because it uses compilation-specific SpecialTypes.
/// </summary>
internal class BuiltInOperators
{
private readonly CSharpCompilation _compilation;
//actual lazily-constructed caches of built-in operators.
private ImmutableArray<UnaryOperatorSignature>[] _builtInUnaryOperators;
private ImmutableArray<BinaryOperatorSignature>[][] _builtInOperators;
internal BuiltInOperators(CSharpCompilation compilation)
{
_compilation = compilation;
}
// PERF: Use int instead of UnaryOperatorKind so the compiler can use array literal initialization.
// The most natural type choice, Enum arrays, are not blittable due to a CLR limitation.
private ImmutableArray<UnaryOperatorSignature> GetSignaturesFromUnaryOperatorKinds(int[] operatorKinds)
{
var builder = ArrayBuilder<UnaryOperatorSignature>.GetInstance();
foreach (var kind in operatorKinds)
{
builder.Add(GetSignature((UnaryOperatorKind)kind));
}
return builder.ToImmutableAndFree();
}
internal void GetSimpleBuiltInOperators(UnaryOperatorKind kind, ArrayBuilder<UnaryOperatorSignature> operators, bool skipNativeIntegerOperators)
{
if (_builtInUnaryOperators == null)
{
var allOperators = new ImmutableArray<UnaryOperatorSignature>[]
{
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.SBytePostfixIncrement,
(int)UnaryOperatorKind.BytePostfixIncrement,
(int)UnaryOperatorKind.ShortPostfixIncrement,
(int)UnaryOperatorKind.UShortPostfixIncrement,
(int)UnaryOperatorKind.IntPostfixIncrement,
(int)UnaryOperatorKind.UIntPostfixIncrement,
(int)UnaryOperatorKind.LongPostfixIncrement,
(int)UnaryOperatorKind.ULongPostfixIncrement,
(int)UnaryOperatorKind.NIntPostfixIncrement,
(int)UnaryOperatorKind.NUIntPostfixIncrement,
(int)UnaryOperatorKind.CharPostfixIncrement,
(int)UnaryOperatorKind.FloatPostfixIncrement,
(int)UnaryOperatorKind.DoublePostfixIncrement,
(int)UnaryOperatorKind.DecimalPostfixIncrement,
(int)UnaryOperatorKind.LiftedSBytePostfixIncrement,
(int)UnaryOperatorKind.LiftedBytePostfixIncrement,
(int)UnaryOperatorKind.LiftedShortPostfixIncrement,
(int)UnaryOperatorKind.LiftedUShortPostfixIncrement,
(int)UnaryOperatorKind.LiftedIntPostfixIncrement,
(int)UnaryOperatorKind.LiftedUIntPostfixIncrement,
(int)UnaryOperatorKind.LiftedLongPostfixIncrement,
(int)UnaryOperatorKind.LiftedULongPostfixIncrement,
(int)UnaryOperatorKind.LiftedNIntPostfixIncrement,
(int)UnaryOperatorKind.LiftedNUIntPostfixIncrement,
(int)UnaryOperatorKind.LiftedCharPostfixIncrement,
(int)UnaryOperatorKind.LiftedFloatPostfixIncrement,
(int)UnaryOperatorKind.LiftedDoublePostfixIncrement,
(int)UnaryOperatorKind.LiftedDecimalPostfixIncrement,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.SBytePostfixDecrement,
(int)UnaryOperatorKind.BytePostfixDecrement,
(int)UnaryOperatorKind.ShortPostfixDecrement,
(int)UnaryOperatorKind.UShortPostfixDecrement,
(int)UnaryOperatorKind.IntPostfixDecrement,
(int)UnaryOperatorKind.UIntPostfixDecrement,
(int)UnaryOperatorKind.LongPostfixDecrement,
(int)UnaryOperatorKind.ULongPostfixDecrement,
(int)UnaryOperatorKind.NIntPostfixDecrement,
(int)UnaryOperatorKind.NUIntPostfixDecrement,
(int)UnaryOperatorKind.CharPostfixDecrement,
(int)UnaryOperatorKind.FloatPostfixDecrement,
(int)UnaryOperatorKind.DoublePostfixDecrement,
(int)UnaryOperatorKind.DecimalPostfixDecrement,
(int)UnaryOperatorKind.LiftedSBytePostfixDecrement,
(int)UnaryOperatorKind.LiftedBytePostfixDecrement,
(int)UnaryOperatorKind.LiftedShortPostfixDecrement,
(int)UnaryOperatorKind.LiftedUShortPostfixDecrement,
(int)UnaryOperatorKind.LiftedIntPostfixDecrement,
(int)UnaryOperatorKind.LiftedUIntPostfixDecrement,
(int)UnaryOperatorKind.LiftedLongPostfixDecrement,
(int)UnaryOperatorKind.LiftedULongPostfixDecrement,
(int)UnaryOperatorKind.LiftedNIntPostfixDecrement,
(int)UnaryOperatorKind.LiftedNUIntPostfixDecrement,
(int)UnaryOperatorKind.LiftedCharPostfixDecrement,
(int)UnaryOperatorKind.LiftedFloatPostfixDecrement,
(int)UnaryOperatorKind.LiftedDoublePostfixDecrement,
(int)UnaryOperatorKind.LiftedDecimalPostfixDecrement,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.SBytePrefixIncrement,
(int)UnaryOperatorKind.BytePrefixIncrement,
(int)UnaryOperatorKind.ShortPrefixIncrement,
(int)UnaryOperatorKind.UShortPrefixIncrement,
(int)UnaryOperatorKind.IntPrefixIncrement,
(int)UnaryOperatorKind.UIntPrefixIncrement,
(int)UnaryOperatorKind.LongPrefixIncrement,
(int)UnaryOperatorKind.ULongPrefixIncrement,
(int)UnaryOperatorKind.NIntPrefixIncrement,
(int)UnaryOperatorKind.NUIntPrefixIncrement,
(int)UnaryOperatorKind.CharPrefixIncrement,
(int)UnaryOperatorKind.FloatPrefixIncrement,
(int)UnaryOperatorKind.DoublePrefixIncrement,
(int)UnaryOperatorKind.DecimalPrefixIncrement,
(int)UnaryOperatorKind.LiftedSBytePrefixIncrement,
(int)UnaryOperatorKind.LiftedBytePrefixIncrement,
(int)UnaryOperatorKind.LiftedShortPrefixIncrement,
(int)UnaryOperatorKind.LiftedUShortPrefixIncrement,
(int)UnaryOperatorKind.LiftedIntPrefixIncrement,
(int)UnaryOperatorKind.LiftedUIntPrefixIncrement,
(int)UnaryOperatorKind.LiftedLongPrefixIncrement,
(int)UnaryOperatorKind.LiftedULongPrefixIncrement,
(int)UnaryOperatorKind.LiftedNIntPrefixIncrement,
(int)UnaryOperatorKind.LiftedNUIntPrefixIncrement,
(int)UnaryOperatorKind.LiftedCharPrefixIncrement,
(int)UnaryOperatorKind.LiftedFloatPrefixIncrement,
(int)UnaryOperatorKind.LiftedDoublePrefixIncrement,
(int)UnaryOperatorKind.LiftedDecimalPrefixIncrement,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.SBytePrefixDecrement,
(int)UnaryOperatorKind.BytePrefixDecrement,
(int)UnaryOperatorKind.ShortPrefixDecrement,
(int)UnaryOperatorKind.UShortPrefixDecrement,
(int)UnaryOperatorKind.IntPrefixDecrement,
(int)UnaryOperatorKind.UIntPrefixDecrement,
(int)UnaryOperatorKind.NIntPrefixDecrement,
(int)UnaryOperatorKind.NUIntPrefixDecrement,
(int)UnaryOperatorKind.LongPrefixDecrement,
(int)UnaryOperatorKind.ULongPrefixDecrement,
(int)UnaryOperatorKind.CharPrefixDecrement,
(int)UnaryOperatorKind.FloatPrefixDecrement,
(int)UnaryOperatorKind.DoublePrefixDecrement,
(int)UnaryOperatorKind.DecimalPrefixDecrement,
(int)UnaryOperatorKind.LiftedSBytePrefixDecrement,
(int)UnaryOperatorKind.LiftedBytePrefixDecrement,
(int)UnaryOperatorKind.LiftedShortPrefixDecrement,
(int)UnaryOperatorKind.LiftedUShortPrefixDecrement,
(int)UnaryOperatorKind.LiftedIntPrefixDecrement,
(int)UnaryOperatorKind.LiftedUIntPrefixDecrement,
(int)UnaryOperatorKind.LiftedLongPrefixDecrement,
(int)UnaryOperatorKind.LiftedULongPrefixDecrement,
(int)UnaryOperatorKind.LiftedNIntPrefixDecrement,
(int)UnaryOperatorKind.LiftedNUIntPrefixDecrement,
(int)UnaryOperatorKind.LiftedCharPrefixDecrement,
(int)UnaryOperatorKind.LiftedFloatPrefixDecrement,
(int)UnaryOperatorKind.LiftedDoublePrefixDecrement,
(int)UnaryOperatorKind.LiftedDecimalPrefixDecrement,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.IntUnaryPlus,
(int)UnaryOperatorKind.UIntUnaryPlus,
(int)UnaryOperatorKind.LongUnaryPlus,
(int)UnaryOperatorKind.ULongUnaryPlus,
(int)UnaryOperatorKind.NIntUnaryPlus,
(int)UnaryOperatorKind.NUIntUnaryPlus,
(int)UnaryOperatorKind.FloatUnaryPlus,
(int)UnaryOperatorKind.DoubleUnaryPlus,
(int)UnaryOperatorKind.DecimalUnaryPlus,
(int)UnaryOperatorKind.LiftedIntUnaryPlus,
(int)UnaryOperatorKind.LiftedUIntUnaryPlus,
(int)UnaryOperatorKind.LiftedLongUnaryPlus,
(int)UnaryOperatorKind.LiftedULongUnaryPlus,
(int)UnaryOperatorKind.LiftedNIntUnaryPlus,
(int)UnaryOperatorKind.LiftedNUIntUnaryPlus,
(int)UnaryOperatorKind.LiftedFloatUnaryPlus,
(int)UnaryOperatorKind.LiftedDoubleUnaryPlus,
(int)UnaryOperatorKind.LiftedDecimalUnaryPlus,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.IntUnaryMinus,
(int)UnaryOperatorKind.LongUnaryMinus,
(int)UnaryOperatorKind.NIntUnaryMinus,
(int)UnaryOperatorKind.FloatUnaryMinus,
(int)UnaryOperatorKind.DoubleUnaryMinus,
(int)UnaryOperatorKind.DecimalUnaryMinus,
(int)UnaryOperatorKind.LiftedIntUnaryMinus,
(int)UnaryOperatorKind.LiftedLongUnaryMinus,
(int)UnaryOperatorKind.LiftedNIntUnaryMinus,
(int)UnaryOperatorKind.LiftedFloatUnaryMinus,
(int)UnaryOperatorKind.LiftedDoubleUnaryMinus,
(int)UnaryOperatorKind.LiftedDecimalUnaryMinus,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.BoolLogicalNegation,
(int)UnaryOperatorKind.LiftedBoolLogicalNegation,
}),
GetSignaturesFromUnaryOperatorKinds(new []
{
(int)UnaryOperatorKind.IntBitwiseComplement,
(int)UnaryOperatorKind.UIntBitwiseComplement,
(int)UnaryOperatorKind.LongBitwiseComplement,
(int)UnaryOperatorKind.ULongBitwiseComplement,
(int)UnaryOperatorKind.NIntBitwiseComplement,
(int)UnaryOperatorKind.NUIntBitwiseComplement,
(int)UnaryOperatorKind.LiftedIntBitwiseComplement,
(int)UnaryOperatorKind.LiftedUIntBitwiseComplement,
(int)UnaryOperatorKind.LiftedLongBitwiseComplement,
(int)UnaryOperatorKind.LiftedULongBitwiseComplement,
(int)UnaryOperatorKind.LiftedNIntBitwiseComplement,
(int)UnaryOperatorKind.LiftedNUIntBitwiseComplement,
}),
// No built-in operator true or operator false
ImmutableArray<UnaryOperatorSignature>.Empty,
ImmutableArray<UnaryOperatorSignature>.Empty,
};
Interlocked.CompareExchange(ref _builtInUnaryOperators, allOperators, null);
}
foreach (var op in _builtInUnaryOperators[kind.OperatorIndex()])
{
if (skipNativeIntegerOperators)
{
switch (op.Kind.OperandTypes())
{
case UnaryOperatorKind.NInt:
case UnaryOperatorKind.NUInt:
continue;
}
}
operators.Add(op);
}
}
internal UnaryOperatorSignature GetSignature(UnaryOperatorKind kind)
{
TypeSymbol opType;
switch (kind.OperandTypes())
{
case UnaryOperatorKind.SByte: opType = _compilation.GetSpecialType(SpecialType.System_SByte); break;
case UnaryOperatorKind.Byte: opType = _compilation.GetSpecialType(SpecialType.System_Byte); break;
case UnaryOperatorKind.Short: opType = _compilation.GetSpecialType(SpecialType.System_Int16); break;
case UnaryOperatorKind.UShort: opType = _compilation.GetSpecialType(SpecialType.System_UInt16); break;
case UnaryOperatorKind.Int: opType = _compilation.GetSpecialType(SpecialType.System_Int32); break;
case UnaryOperatorKind.UInt: opType = _compilation.GetSpecialType(SpecialType.System_UInt32); break;
case UnaryOperatorKind.Long: opType = _compilation.GetSpecialType(SpecialType.System_Int64); break;
case UnaryOperatorKind.ULong: opType = _compilation.GetSpecialType(SpecialType.System_UInt64); break;
case UnaryOperatorKind.NInt: opType = _compilation.CreateNativeIntegerTypeSymbol(signed: true); break;
case UnaryOperatorKind.NUInt: opType = _compilation.CreateNativeIntegerTypeSymbol(signed: false); break;
case UnaryOperatorKind.Char: opType = _compilation.GetSpecialType(SpecialType.System_Char); break;
case UnaryOperatorKind.Float: opType = _compilation.GetSpecialType(SpecialType.System_Single); break;
case UnaryOperatorKind.Double: opType = _compilation.GetSpecialType(SpecialType.System_Double); break;
case UnaryOperatorKind.Decimal: opType = _compilation.GetSpecialType(SpecialType.System_Decimal); break;
case UnaryOperatorKind.Bool: opType = _compilation.GetSpecialType(SpecialType.System_Boolean); break;
default: throw ExceptionUtilities.UnexpectedValue(kind.OperandTypes());
}
if (kind.IsLifted())
{
opType = _compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(opType);
}
return new UnaryOperatorSignature(kind, opType, opType);
}
// PERF: Use int instead of BinaryOperatorKind so the compiler can use array literal initialization.
// The most natural type choice, Enum arrays, are not blittable due to a CLR limitation.
private ImmutableArray<BinaryOperatorSignature> GetSignaturesFromBinaryOperatorKinds(int[] operatorKinds)
{
var builder = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
foreach (var kind in operatorKinds)
{
builder.Add(GetSignature((BinaryOperatorKind)kind));
}
return builder.ToImmutableAndFree();
}
internal void GetSimpleBuiltInOperators(BinaryOperatorKind kind, ArrayBuilder<BinaryOperatorSignature> operators, bool skipNativeIntegerOperators)
{
if (_builtInOperators == null)
{
var logicalOperators = new ImmutableArray<BinaryOperatorSignature>[]
{
ImmutableArray<BinaryOperatorSignature>.Empty, //multiplication
ImmutableArray<BinaryOperatorSignature>.Empty, //addition
ImmutableArray<BinaryOperatorSignature>.Empty, //subtraction
ImmutableArray<BinaryOperatorSignature>.Empty, //division
ImmutableArray<BinaryOperatorSignature>.Empty, //remainder
ImmutableArray<BinaryOperatorSignature>.Empty, //left shift
ImmutableArray<BinaryOperatorSignature>.Empty, //right shift
ImmutableArray<BinaryOperatorSignature>.Empty, //equal
ImmutableArray<BinaryOperatorSignature>.Empty, //not equal
ImmutableArray<BinaryOperatorSignature>.Empty, //greater than
ImmutableArray<BinaryOperatorSignature>.Empty, //less than
ImmutableArray<BinaryOperatorSignature>.Empty, //greater than or equal
ImmutableArray<BinaryOperatorSignature>.Empty, //less than or equal
ImmutableArray.Create<BinaryOperatorSignature>(GetSignature(BinaryOperatorKind.LogicalBoolAnd)), //and
ImmutableArray<BinaryOperatorSignature>.Empty, //xor
ImmutableArray.Create<BinaryOperatorSignature>(GetSignature(BinaryOperatorKind.LogicalBoolOr)), //or
};
var nonLogicalOperators = new ImmutableArray<BinaryOperatorSignature>[]
{
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntMultiplication,
(int)BinaryOperatorKind.UIntMultiplication,
(int)BinaryOperatorKind.LongMultiplication,
(int)BinaryOperatorKind.ULongMultiplication,
(int)BinaryOperatorKind.NIntMultiplication,
(int)BinaryOperatorKind.NUIntMultiplication,
(int)BinaryOperatorKind.FloatMultiplication,
(int)BinaryOperatorKind.DoubleMultiplication,
(int)BinaryOperatorKind.DecimalMultiplication,
(int)BinaryOperatorKind.LiftedIntMultiplication,
(int)BinaryOperatorKind.LiftedUIntMultiplication,
(int)BinaryOperatorKind.LiftedLongMultiplication,
(int)BinaryOperatorKind.LiftedULongMultiplication,
(int)BinaryOperatorKind.LiftedNIntMultiplication,
(int)BinaryOperatorKind.LiftedNUIntMultiplication,
(int)BinaryOperatorKind.LiftedFloatMultiplication,
(int)BinaryOperatorKind.LiftedDoubleMultiplication,
(int)BinaryOperatorKind.LiftedDecimalMultiplication,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntAddition,
(int)BinaryOperatorKind.UIntAddition,
(int)BinaryOperatorKind.LongAddition,
(int)BinaryOperatorKind.ULongAddition,
(int)BinaryOperatorKind.NIntAddition,
(int)BinaryOperatorKind.NUIntAddition,
(int)BinaryOperatorKind.FloatAddition,
(int)BinaryOperatorKind.DoubleAddition,
(int)BinaryOperatorKind.DecimalAddition,
(int)BinaryOperatorKind.LiftedIntAddition,
(int)BinaryOperatorKind.LiftedUIntAddition,
(int)BinaryOperatorKind.LiftedLongAddition,
(int)BinaryOperatorKind.LiftedULongAddition,
(int)BinaryOperatorKind.LiftedNIntAddition,
(int)BinaryOperatorKind.LiftedNUIntAddition,
(int)BinaryOperatorKind.LiftedFloatAddition,
(int)BinaryOperatorKind.LiftedDoubleAddition,
(int)BinaryOperatorKind.LiftedDecimalAddition,
(int)BinaryOperatorKind.StringConcatenation,
(int)BinaryOperatorKind.StringAndObjectConcatenation,
(int)BinaryOperatorKind.ObjectAndStringConcatenation,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntSubtraction,
(int)BinaryOperatorKind.UIntSubtraction,
(int)BinaryOperatorKind.LongSubtraction,
(int)BinaryOperatorKind.ULongSubtraction,
(int)BinaryOperatorKind.NIntSubtraction,
(int)BinaryOperatorKind.NUIntSubtraction,
(int)BinaryOperatorKind.FloatSubtraction,
(int)BinaryOperatorKind.DoubleSubtraction,
(int)BinaryOperatorKind.DecimalSubtraction,
(int)BinaryOperatorKind.LiftedIntSubtraction,
(int)BinaryOperatorKind.LiftedUIntSubtraction,
(int)BinaryOperatorKind.LiftedLongSubtraction,
(int)BinaryOperatorKind.LiftedULongSubtraction,
(int)BinaryOperatorKind.LiftedNIntSubtraction,
(int)BinaryOperatorKind.LiftedNUIntSubtraction,
(int)BinaryOperatorKind.LiftedFloatSubtraction,
(int)BinaryOperatorKind.LiftedDoubleSubtraction,
(int)BinaryOperatorKind.LiftedDecimalSubtraction,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntDivision,
(int)BinaryOperatorKind.UIntDivision,
(int)BinaryOperatorKind.LongDivision,
(int)BinaryOperatorKind.ULongDivision,
(int)BinaryOperatorKind.NIntDivision,
(int)BinaryOperatorKind.NUIntDivision,
(int)BinaryOperatorKind.FloatDivision,
(int)BinaryOperatorKind.DoubleDivision,
(int)BinaryOperatorKind.DecimalDivision,
(int)BinaryOperatorKind.LiftedIntDivision,
(int)BinaryOperatorKind.LiftedUIntDivision,
(int)BinaryOperatorKind.LiftedLongDivision,
(int)BinaryOperatorKind.LiftedULongDivision,
(int)BinaryOperatorKind.LiftedNIntDivision,
(int)BinaryOperatorKind.LiftedNUIntDivision,
(int)BinaryOperatorKind.LiftedFloatDivision,
(int)BinaryOperatorKind.LiftedDoubleDivision,
(int)BinaryOperatorKind.LiftedDecimalDivision,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntRemainder,
(int)BinaryOperatorKind.UIntRemainder,
(int)BinaryOperatorKind.LongRemainder,
(int)BinaryOperatorKind.ULongRemainder,
(int)BinaryOperatorKind.NIntRemainder,
(int)BinaryOperatorKind.NUIntRemainder,
(int)BinaryOperatorKind.FloatRemainder,
(int)BinaryOperatorKind.DoubleRemainder,
(int)BinaryOperatorKind.DecimalRemainder,
(int)BinaryOperatorKind.LiftedIntRemainder,
(int)BinaryOperatorKind.LiftedUIntRemainder,
(int)BinaryOperatorKind.LiftedLongRemainder,
(int)BinaryOperatorKind.LiftedULongRemainder,
(int)BinaryOperatorKind.LiftedNIntRemainder,
(int)BinaryOperatorKind.LiftedNUIntRemainder,
(int)BinaryOperatorKind.LiftedFloatRemainder,
(int)BinaryOperatorKind.LiftedDoubleRemainder,
(int)BinaryOperatorKind.LiftedDecimalRemainder,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntLeftShift,
(int)BinaryOperatorKind.UIntLeftShift,
(int)BinaryOperatorKind.LongLeftShift,
(int)BinaryOperatorKind.ULongLeftShift,
(int)BinaryOperatorKind.NIntLeftShift,
(int)BinaryOperatorKind.NUIntLeftShift,
(int)BinaryOperatorKind.LiftedIntLeftShift,
(int)BinaryOperatorKind.LiftedUIntLeftShift,
(int)BinaryOperatorKind.LiftedLongLeftShift,
(int)BinaryOperatorKind.LiftedULongLeftShift,
(int)BinaryOperatorKind.LiftedNIntLeftShift,
(int)BinaryOperatorKind.LiftedNUIntLeftShift,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntRightShift,
(int)BinaryOperatorKind.UIntRightShift,
(int)BinaryOperatorKind.LongRightShift,
(int)BinaryOperatorKind.ULongRightShift,
(int)BinaryOperatorKind.NIntRightShift,
(int)BinaryOperatorKind.NUIntRightShift,
(int)BinaryOperatorKind.LiftedIntRightShift,
(int)BinaryOperatorKind.LiftedUIntRightShift,
(int)BinaryOperatorKind.LiftedLongRightShift,
(int)BinaryOperatorKind.LiftedULongRightShift,
(int)BinaryOperatorKind.LiftedNIntRightShift,
(int)BinaryOperatorKind.LiftedNUIntRightShift,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntEqual,
(int)BinaryOperatorKind.UIntEqual,
(int)BinaryOperatorKind.LongEqual,
(int)BinaryOperatorKind.ULongEqual,
(int)BinaryOperatorKind.NIntEqual,
(int)BinaryOperatorKind.NUIntEqual,
(int)BinaryOperatorKind.FloatEqual,
(int)BinaryOperatorKind.DoubleEqual,
(int)BinaryOperatorKind.DecimalEqual,
(int)BinaryOperatorKind.BoolEqual,
(int)BinaryOperatorKind.LiftedIntEqual,
(int)BinaryOperatorKind.LiftedUIntEqual,
(int)BinaryOperatorKind.LiftedLongEqual,
(int)BinaryOperatorKind.LiftedULongEqual,
(int)BinaryOperatorKind.LiftedNIntEqual,
(int)BinaryOperatorKind.LiftedNUIntEqual,
(int)BinaryOperatorKind.LiftedFloatEqual,
(int)BinaryOperatorKind.LiftedDoubleEqual,
(int)BinaryOperatorKind.LiftedDecimalEqual,
(int)BinaryOperatorKind.LiftedBoolEqual,
(int)BinaryOperatorKind.ObjectEqual,
(int)BinaryOperatorKind.StringEqual,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntNotEqual,
(int)BinaryOperatorKind.UIntNotEqual,
(int)BinaryOperatorKind.LongNotEqual,
(int)BinaryOperatorKind.ULongNotEqual,
(int)BinaryOperatorKind.NIntNotEqual,
(int)BinaryOperatorKind.NUIntNotEqual,
(int)BinaryOperatorKind.FloatNotEqual,
(int)BinaryOperatorKind.DoubleNotEqual,
(int)BinaryOperatorKind.DecimalNotEqual,
(int)BinaryOperatorKind.BoolNotEqual,
(int)BinaryOperatorKind.LiftedIntNotEqual,
(int)BinaryOperatorKind.LiftedUIntNotEqual,
(int)BinaryOperatorKind.LiftedLongNotEqual,
(int)BinaryOperatorKind.LiftedULongNotEqual,
(int)BinaryOperatorKind.LiftedNIntNotEqual,
(int)BinaryOperatorKind.LiftedNUIntNotEqual,
(int)BinaryOperatorKind.LiftedFloatNotEqual,
(int)BinaryOperatorKind.LiftedDoubleNotEqual,
(int)BinaryOperatorKind.LiftedDecimalNotEqual,
(int)BinaryOperatorKind.LiftedBoolNotEqual,
(int)BinaryOperatorKind.ObjectNotEqual,
(int)BinaryOperatorKind.StringNotEqual,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntGreaterThan,
(int)BinaryOperatorKind.UIntGreaterThan,
(int)BinaryOperatorKind.LongGreaterThan,
(int)BinaryOperatorKind.ULongGreaterThan,
(int)BinaryOperatorKind.NIntGreaterThan,
(int)BinaryOperatorKind.NUIntGreaterThan,
(int)BinaryOperatorKind.FloatGreaterThan,
(int)BinaryOperatorKind.DoubleGreaterThan,
(int)BinaryOperatorKind.DecimalGreaterThan,
(int)BinaryOperatorKind.LiftedIntGreaterThan,
(int)BinaryOperatorKind.LiftedUIntGreaterThan,
(int)BinaryOperatorKind.LiftedLongGreaterThan,
(int)BinaryOperatorKind.LiftedULongGreaterThan,
(int)BinaryOperatorKind.LiftedNIntGreaterThan,
(int)BinaryOperatorKind.LiftedNUIntGreaterThan,
(int)BinaryOperatorKind.LiftedFloatGreaterThan,
(int)BinaryOperatorKind.LiftedDoubleGreaterThan,
(int)BinaryOperatorKind.LiftedDecimalGreaterThan,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntLessThan,
(int)BinaryOperatorKind.UIntLessThan,
(int)BinaryOperatorKind.LongLessThan,
(int)BinaryOperatorKind.ULongLessThan,
(int)BinaryOperatorKind.NIntLessThan,
(int)BinaryOperatorKind.NUIntLessThan,
(int)BinaryOperatorKind.FloatLessThan,
(int)BinaryOperatorKind.DoubleLessThan,
(int)BinaryOperatorKind.DecimalLessThan,
(int)BinaryOperatorKind.LiftedIntLessThan,
(int)BinaryOperatorKind.LiftedUIntLessThan,
(int)BinaryOperatorKind.LiftedLongLessThan,
(int)BinaryOperatorKind.LiftedULongLessThan,
(int)BinaryOperatorKind.LiftedNIntLessThan,
(int)BinaryOperatorKind.LiftedNUIntLessThan,
(int)BinaryOperatorKind.LiftedFloatLessThan,
(int)BinaryOperatorKind.LiftedDoubleLessThan,
(int)BinaryOperatorKind.LiftedDecimalLessThan,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntGreaterThanOrEqual,
(int)BinaryOperatorKind.UIntGreaterThanOrEqual,
(int)BinaryOperatorKind.LongGreaterThanOrEqual,
(int)BinaryOperatorKind.ULongGreaterThanOrEqual,
(int)BinaryOperatorKind.NIntGreaterThanOrEqual,
(int)BinaryOperatorKind.NUIntGreaterThanOrEqual,
(int)BinaryOperatorKind.FloatGreaterThanOrEqual,
(int)BinaryOperatorKind.DoubleGreaterThanOrEqual,
(int)BinaryOperatorKind.DecimalGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedIntGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedUIntGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedLongGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedULongGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedNIntGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedNUIntGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedFloatGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedDoubleGreaterThanOrEqual,
(int)BinaryOperatorKind.LiftedDecimalGreaterThanOrEqual,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntLessThanOrEqual,
(int)BinaryOperatorKind.UIntLessThanOrEqual,
(int)BinaryOperatorKind.LongLessThanOrEqual,
(int)BinaryOperatorKind.ULongLessThanOrEqual,
(int)BinaryOperatorKind.NIntLessThanOrEqual,
(int)BinaryOperatorKind.NUIntLessThanOrEqual,
(int)BinaryOperatorKind.FloatLessThanOrEqual,
(int)BinaryOperatorKind.DoubleLessThanOrEqual,
(int)BinaryOperatorKind.DecimalLessThanOrEqual,
(int)BinaryOperatorKind.LiftedIntLessThanOrEqual,
(int)BinaryOperatorKind.LiftedUIntLessThanOrEqual,
(int)BinaryOperatorKind.LiftedLongLessThanOrEqual,
(int)BinaryOperatorKind.LiftedULongLessThanOrEqual,
(int)BinaryOperatorKind.LiftedNIntLessThanOrEqual,
(int)BinaryOperatorKind.LiftedNUIntLessThanOrEqual,
(int)BinaryOperatorKind.LiftedFloatLessThanOrEqual,
(int)BinaryOperatorKind.LiftedDoubleLessThanOrEqual,
(int)BinaryOperatorKind.LiftedDecimalLessThanOrEqual,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntAnd,
(int)BinaryOperatorKind.UIntAnd,
(int)BinaryOperatorKind.LongAnd,
(int)BinaryOperatorKind.ULongAnd,
(int)BinaryOperatorKind.NIntAnd,
(int)BinaryOperatorKind.NUIntAnd,
(int)BinaryOperatorKind.BoolAnd,
(int)BinaryOperatorKind.LiftedIntAnd,
(int)BinaryOperatorKind.LiftedUIntAnd,
(int)BinaryOperatorKind.LiftedLongAnd,
(int)BinaryOperatorKind.LiftedULongAnd,
(int)BinaryOperatorKind.LiftedNIntAnd,
(int)BinaryOperatorKind.LiftedNUIntAnd,
(int)BinaryOperatorKind.LiftedBoolAnd,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntXor,
(int)BinaryOperatorKind.UIntXor,
(int)BinaryOperatorKind.LongXor,
(int)BinaryOperatorKind.ULongXor,
(int)BinaryOperatorKind.NIntXor,
(int)BinaryOperatorKind.NUIntXor,
(int)BinaryOperatorKind.BoolXor,
(int)BinaryOperatorKind.LiftedIntXor,
(int)BinaryOperatorKind.LiftedUIntXor,
(int)BinaryOperatorKind.LiftedLongXor,
(int)BinaryOperatorKind.LiftedULongXor,
(int)BinaryOperatorKind.LiftedNIntXor,
(int)BinaryOperatorKind.LiftedNUIntXor,
(int)BinaryOperatorKind.LiftedBoolXor,
}),
GetSignaturesFromBinaryOperatorKinds(new []
{
(int)BinaryOperatorKind.IntOr,
(int)BinaryOperatorKind.UIntOr,
(int)BinaryOperatorKind.LongOr,
(int)BinaryOperatorKind.ULongOr,
(int)BinaryOperatorKind.NIntOr,
(int)BinaryOperatorKind.NUIntOr,
(int)BinaryOperatorKind.BoolOr,
(int)BinaryOperatorKind.LiftedIntOr,
(int)BinaryOperatorKind.LiftedUIntOr,
(int)BinaryOperatorKind.LiftedLongOr,
(int)BinaryOperatorKind.LiftedULongOr,
(int)BinaryOperatorKind.LiftedNIntOr,
(int)BinaryOperatorKind.LiftedNUIntOr,
(int)BinaryOperatorKind.LiftedBoolOr,
}),
};
var allOperators = new[] { nonLogicalOperators, logicalOperators };
Interlocked.CompareExchange(ref _builtInOperators, allOperators, null);
}
foreach (var op in _builtInOperators[kind.IsLogical() ? 1 : 0][kind.OperatorIndex()])
{
if (skipNativeIntegerOperators)
{
switch (op.Kind.OperandTypes())
{
case BinaryOperatorKind.NInt:
case BinaryOperatorKind.NUInt:
continue;
}
}
operators.Add(op);
}
}
internal BinaryOperatorSignature GetSignature(BinaryOperatorKind kind)
{
var left = LeftType(kind);
switch (kind.Operator())
{
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Division:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Remainder:
case BinaryOperatorKind.And:
case BinaryOperatorKind.Or:
case BinaryOperatorKind.Xor:
return new BinaryOperatorSignature(kind, left, left, left);
case BinaryOperatorKind.Addition:
return new BinaryOperatorSignature(kind, left, RightType(kind), ReturnType(kind));
case BinaryOperatorKind.LeftShift:
case BinaryOperatorKind.RightShift:
TypeSymbol rightType = _compilation.GetSpecialType(SpecialType.System_Int32);
if (kind.IsLifted())
{
rightType = _compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(rightType);
}
return new BinaryOperatorSignature(kind, left, rightType, left);
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
return new BinaryOperatorSignature(kind, left, left, _compilation.GetSpecialType(SpecialType.System_Boolean));
}
return new BinaryOperatorSignature(kind, left, RightType(kind), ReturnType(kind));
}
private TypeSymbol LeftType(BinaryOperatorKind kind)
{
if (kind.IsLifted())
{
return LiftedType(kind);
}
else
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Int: return _compilation.GetSpecialType(SpecialType.System_Int32);
case BinaryOperatorKind.UInt: return _compilation.GetSpecialType(SpecialType.System_UInt32);
case BinaryOperatorKind.Long: return _compilation.GetSpecialType(SpecialType.System_Int64);
case BinaryOperatorKind.ULong: return _compilation.GetSpecialType(SpecialType.System_UInt64);
case BinaryOperatorKind.NInt: return _compilation.CreateNativeIntegerTypeSymbol(signed: true);
case BinaryOperatorKind.NUInt: return _compilation.CreateNativeIntegerTypeSymbol(signed: false);
case BinaryOperatorKind.Float: return _compilation.GetSpecialType(SpecialType.System_Single);
case BinaryOperatorKind.Double: return _compilation.GetSpecialType(SpecialType.System_Double);
case BinaryOperatorKind.Decimal: return _compilation.GetSpecialType(SpecialType.System_Decimal);
case BinaryOperatorKind.Bool: return _compilation.GetSpecialType(SpecialType.System_Boolean);
case BinaryOperatorKind.ObjectAndString:
case BinaryOperatorKind.Object:
return _compilation.GetSpecialType(SpecialType.System_Object);
case BinaryOperatorKind.String:
case BinaryOperatorKind.StringAndObject:
return _compilation.GetSpecialType(SpecialType.System_String);
}
}
Debug.Assert(false, "Bad operator kind in left type");
return null;
}
private TypeSymbol RightType(BinaryOperatorKind kind)
{
if (kind.IsLifted())
{
return LiftedType(kind);
}
else
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Int: return _compilation.GetSpecialType(SpecialType.System_Int32);
case BinaryOperatorKind.UInt: return _compilation.GetSpecialType(SpecialType.System_UInt32);
case BinaryOperatorKind.Long: return _compilation.GetSpecialType(SpecialType.System_Int64);
case BinaryOperatorKind.ULong: return _compilation.GetSpecialType(SpecialType.System_UInt64);
case BinaryOperatorKind.NInt: return _compilation.CreateNativeIntegerTypeSymbol(signed: true);
case BinaryOperatorKind.NUInt: return _compilation.CreateNativeIntegerTypeSymbol(signed: false);
case BinaryOperatorKind.Float: return _compilation.GetSpecialType(SpecialType.System_Single);
case BinaryOperatorKind.Double: return _compilation.GetSpecialType(SpecialType.System_Double);
case BinaryOperatorKind.Decimal: return _compilation.GetSpecialType(SpecialType.System_Decimal);
case BinaryOperatorKind.Bool: return _compilation.GetSpecialType(SpecialType.System_Boolean);
case BinaryOperatorKind.ObjectAndString:
case BinaryOperatorKind.String:
return _compilation.GetSpecialType(SpecialType.System_String);
case BinaryOperatorKind.StringAndObject:
case BinaryOperatorKind.Object:
return _compilation.GetSpecialType(SpecialType.System_Object);
}
}
Debug.Assert(false, "Bad operator kind in right type");
return null;
}
private TypeSymbol ReturnType(BinaryOperatorKind kind)
{
if (kind.IsLifted())
{
return LiftedType(kind);
}
else
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Int: return _compilation.GetSpecialType(SpecialType.System_Int32);
case BinaryOperatorKind.UInt: return _compilation.GetSpecialType(SpecialType.System_UInt32);
case BinaryOperatorKind.Long: return _compilation.GetSpecialType(SpecialType.System_Int64);
case BinaryOperatorKind.ULong: return _compilation.GetSpecialType(SpecialType.System_UInt64);
case BinaryOperatorKind.NInt: return _compilation.CreateNativeIntegerTypeSymbol(signed: true);
case BinaryOperatorKind.NUInt: return _compilation.CreateNativeIntegerTypeSymbol(signed: false);
case BinaryOperatorKind.Float: return _compilation.GetSpecialType(SpecialType.System_Single);
case BinaryOperatorKind.Double: return _compilation.GetSpecialType(SpecialType.System_Double);
case BinaryOperatorKind.Decimal: return _compilation.GetSpecialType(SpecialType.System_Decimal);
case BinaryOperatorKind.Bool: return _compilation.GetSpecialType(SpecialType.System_Boolean);
case BinaryOperatorKind.Object: return _compilation.GetSpecialType(SpecialType.System_Object);
case BinaryOperatorKind.ObjectAndString:
case BinaryOperatorKind.StringAndObject:
case BinaryOperatorKind.String:
return _compilation.GetSpecialType(SpecialType.System_String);
}
}
Debug.Assert(false, "Bad operator kind in return type");
return null;
}
private TypeSymbol LiftedType(BinaryOperatorKind kind)
{
Debug.Assert(kind.IsLifted());
var nullable = _compilation.GetSpecialType(SpecialType.System_Nullable_T);
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Int: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_Int32));
case BinaryOperatorKind.UInt: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_UInt32));
case BinaryOperatorKind.Long: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_Int64));
case BinaryOperatorKind.ULong: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_UInt64));
case BinaryOperatorKind.NInt: return nullable.Construct(_compilation.CreateNativeIntegerTypeSymbol(signed: true));
case BinaryOperatorKind.NUInt: return nullable.Construct(_compilation.CreateNativeIntegerTypeSymbol(signed: false));
case BinaryOperatorKind.Float: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_Single));
case BinaryOperatorKind.Double: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_Double));
case BinaryOperatorKind.Decimal: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_Decimal));
case BinaryOperatorKind.Bool: return nullable.Construct(_compilation.GetSpecialType(SpecialType.System_Boolean));
}
Debug.Assert(false, "Bad operator kind in lifted type");
return null;
}
internal static bool IsValidObjectEquality(Conversions Conversions, TypeSymbol leftType, bool leftIsNull, bool leftIsDefault, TypeSymbol rightType, bool rightIsNull, bool rightIsDefault, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
// SPEC: The predefined reference type equality operators require one of the following:
// SPEC: (1) Both operands are a value of a type known to be a reference-type or the literal null.
// SPEC: Furthermore, an explicit reference conversion exists from the type of either
// SPEC: operand to the type of the other operand. Or:
// SPEC: (2) One operand is a value of type T where T is a type-parameter and the other operand is
// SPEC: the literal null. Furthermore T does not have the value type constraint.
// SPEC: (3) One operand is the literal default and the other operand is a reference-type.
// SPEC ERROR: Notice that the spec calls out that an explicit reference conversion must exist;
// SPEC ERROR: in fact it should say that an explicit reference conversion, implicit reference
// SPEC ERROR: conversion or identity conversion must exist. The conversion from object to object
// SPEC ERROR: is not classified as a reference conversion at all; it is an identity conversion.
// Dev10 does not follow the spec exactly for type parameters. Specifically, in Dev10,
// if a type parameter argument is known to be a value type, or if a type parameter
// argument is not known to be either a value type or reference type and the other
// argument is not null, reference type equality cannot be applied. Otherwise, the
// effective base class of the type parameter is used to determine the conversion
// to the other argument type. (See ExpressionBinder::GetRefEqualSigs.)
if (((object)leftType != null) && leftType.IsTypeParameter())
{
if (leftType.IsValueType || (!leftType.IsReferenceType && !rightIsNull))
{
return false;
}
leftType = ((TypeParameterSymbol)leftType).EffectiveBaseClass(ref useSiteInfo);
Debug.Assert((object)leftType != null);
}
if (((object)rightType != null) && rightType.IsTypeParameter())
{
if (rightType.IsValueType || (!rightType.IsReferenceType && !leftIsNull))
{
return false;
}
rightType = ((TypeParameterSymbol)rightType).EffectiveBaseClass(ref useSiteInfo);
Debug.Assert((object)rightType != null);
}
var leftIsReferenceType = ((object)leftType != null) && leftType.IsReferenceType;
if (!leftIsReferenceType && !leftIsNull && !leftIsDefault)
{
return false;
}
var rightIsReferenceType = ((object)rightType != null) && rightType.IsReferenceType;
if (!rightIsReferenceType && !rightIsNull && !rightIsDefault)
{
return false;
}
if (leftIsDefault && rightIsDefault)
{
return false;
}
if (leftIsDefault && rightIsNull)
{
return false;
}
if (leftIsNull && rightIsDefault)
{
return false;
}
// If at least one side is null or default then clearly a conversion exists.
if (leftIsNull || rightIsNull || leftIsDefault || rightIsDefault)
{
return true;
}
var leftConversion = Conversions.ClassifyConversionFromType(leftType, rightType, ref useSiteInfo);
if (leftConversion.IsIdentity || leftConversion.IsReference)
{
return true;
}
var rightConversion = Conversions.ClassifyConversionFromType(rightType, leftType, ref useSiteInfo);
if (rightConversion.IsIdentity || rightConversion.IsReference)
{
return true;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/VisualStudio/Core/Def/Telemetry/AbstractWorkspaceTelemetryService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Telemetry;
using Microsoft.VisualStudio.Telemetry;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Telemetry
{
internal abstract class AbstractWorkspaceTelemetryService : IWorkspaceTelemetryService
{
public TelemetrySession? CurrentSession { get; private set; }
protected abstract ILogger CreateLogger(TelemetrySession telemetrySession);
public void InitializeTelemetrySession(TelemetrySession telemetrySession)
{
Contract.ThrowIfFalse(CurrentSession is null);
Logger.SetLogger(CreateLogger(telemetrySession));
WatsonReporter.RegisterTelemetrySesssion(telemetrySession);
CurrentSession = telemetrySession;
TelemetrySessionInitialized();
}
protected virtual void TelemetrySessionInitialized()
{
}
public bool HasActiveSession
=> CurrentSession != null && CurrentSession.IsOptedIn;
public string? SerializeCurrentSessionSettings()
=> CurrentSession?.SerializeSettings();
public void RegisterUnexpectedExceptionLogger(TraceSource logger)
=> WatsonReporter.RegisterLogger(logger);
public void UnregisterUnexpectedExceptionLogger(TraceSource logger)
=> WatsonReporter.UnregisterLogger(logger);
public void ReportApiUsage(HashSet<ISymbol> symbols, Guid solutionSessionId, Guid projectGuid)
{
const string EventName = "vs/compilers/api";
const string ApiPropertyName = "vs.compilers.api.pii";
const string ProjectIdPropertyName = "vs.solution.project.projectid";
const string SessionIdPropertyName = "vs.solution.solutionsessionid";
var groupByAssembly = symbols.GroupBy(symbol => symbol.ContainingAssembly);
var apiPerAssembly = groupByAssembly.Select(assemblyGroup => new
{
// mark all string as PII (customer data)
AssemblyName = new TelemetryPiiProperty(assemblyGroup.Key.Identity.Name),
AssemblyVersion = assemblyGroup.Key.Identity.Version.ToString(),
Namespaces = assemblyGroup.GroupBy(symbol => symbol.ContainingNamespace)
.Select(namespaceGroup =>
{
var namespaceName = namespaceGroup.Key?.ToString() ?? string.Empty;
return new
{
Namespace = new TelemetryPiiProperty(namespaceName),
Symbols = namespaceGroup.Select(symbol => symbol.GetDocumentationCommentId())
.Where(id => id != null)
.Select(id => new TelemetryPiiProperty(id))
};
})
});
// use telemetry API directly rather than Logger abstraction for PII data
var telemetryEvent = new TelemetryEvent(EventName);
telemetryEvent.Properties[ApiPropertyName] = new TelemetryComplexProperty(apiPerAssembly);
telemetryEvent.Properties[SessionIdPropertyName] = new TelemetryPiiProperty(solutionSessionId.ToString("B"));
telemetryEvent.Properties[ProjectIdPropertyName] = new TelemetryPiiProperty(projectGuid.ToString("B"));
try
{
CurrentSession?.PostEvent(telemetryEvent);
}
catch
{
// no-op
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Telemetry;
using Microsoft.VisualStudio.Telemetry;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Telemetry
{
internal abstract class AbstractWorkspaceTelemetryService : IWorkspaceTelemetryService
{
public TelemetrySession? CurrentSession { get; private set; }
protected abstract ILogger CreateLogger(TelemetrySession telemetrySession);
public void InitializeTelemetrySession(TelemetrySession telemetrySession)
{
Contract.ThrowIfFalse(CurrentSession is null);
Logger.SetLogger(CreateLogger(telemetrySession));
WatsonReporter.RegisterTelemetrySesssion(telemetrySession);
CurrentSession = telemetrySession;
TelemetrySessionInitialized();
}
protected virtual void TelemetrySessionInitialized()
{
}
public bool HasActiveSession
=> CurrentSession != null && CurrentSession.IsOptedIn;
public string? SerializeCurrentSessionSettings()
=> CurrentSession?.SerializeSettings();
public void RegisterUnexpectedExceptionLogger(TraceSource logger)
=> WatsonReporter.RegisterLogger(logger);
public void UnregisterUnexpectedExceptionLogger(TraceSource logger)
=> WatsonReporter.UnregisterLogger(logger);
public void ReportApiUsage(HashSet<ISymbol> symbols, Guid solutionSessionId, Guid projectGuid)
{
const string EventName = "vs/compilers/api";
const string ApiPropertyName = "vs.compilers.api.pii";
const string ProjectIdPropertyName = "vs.solution.project.projectid";
const string SessionIdPropertyName = "vs.solution.solutionsessionid";
var groupByAssembly = symbols.GroupBy(symbol => symbol.ContainingAssembly);
var apiPerAssembly = groupByAssembly.Select(assemblyGroup => new
{
// mark all string as PII (customer data)
AssemblyName = new TelemetryPiiProperty(assemblyGroup.Key.Identity.Name),
AssemblyVersion = assemblyGroup.Key.Identity.Version.ToString(),
Namespaces = assemblyGroup.GroupBy(symbol => symbol.ContainingNamespace)
.Select(namespaceGroup =>
{
var namespaceName = namespaceGroup.Key?.ToString() ?? string.Empty;
return new
{
Namespace = new TelemetryPiiProperty(namespaceName),
Symbols = namespaceGroup.Select(symbol => symbol.GetDocumentationCommentId())
.Where(id => id != null)
.Select(id => new TelemetryPiiProperty(id))
};
})
});
// use telemetry API directly rather than Logger abstraction for PII data
var telemetryEvent = new TelemetryEvent(EventName);
telemetryEvent.Properties[ApiPropertyName] = new TelemetryComplexProperty(apiPerAssembly);
telemetryEvent.Properties[SessionIdPropertyName] = new TelemetryPiiProperty(solutionSessionId.ToString("B"));
telemetryEvent.Properties[ProjectIdPropertyName] = new TelemetryPiiProperty(projectGuid.ToString("B"));
try
{
CurrentSession?.PostEvent(telemetryEvent);
}
catch
{
// no-op
}
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Workspaces/Core/Portable/Classification/ClassifiedText.cs | // Licensed to the .NET Foundation under one or more 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.Classification
{
internal struct ClassifiedText
{
public string ClassificationType { get; }
public string Text { get; }
public ClassifiedText(string classificationType, string text)
{
ClassificationType = classificationType;
Text = text;
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Classification
{
internal struct ClassifiedText
{
public string ClassificationType { get; }
public string Text { get; }
public ClassifiedText(string classificationType, string text)
{
ClassificationType = classificationType;
Text = text;
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/EditorFeatures/TestUtilities/SignatureHelp/AbstractSignatureHelpProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Classification;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp
{
[UseExportProvider]
public abstract class AbstractSignatureHelpProviderTests<TWorkspaceFixture> : TestBase
where TWorkspaceFixture : TestWorkspaceFixture, new()
{
private readonly TestFixtureHelper<TWorkspaceFixture> _fixtureHelper = new();
internal abstract Type GetSignatureHelpProviderType();
private protected ReferenceCountedDisposable<TWorkspaceFixture> GetOrCreateWorkspaceFixture()
=> _fixtureHelper.GetOrCreateFixture();
/// <summary>
/// Verifies that sighelp comes up at the indicated location in markup ($$), with the indicated span [| ... |].
/// </summary>
/// <param name="markup">Input markup with $$ denoting the cursor position, and [| ... |]
/// denoting the expected sighelp span</param>
/// <param name="expectedOrderedItemsOrNull">The exact expected sighelp items list. If null, this part of the test is ignored.</param>
/// <param name="usePreviousCharAsTrigger">If true, uses the last character before $$ to trigger sighelp.
/// If false, invokes sighelp explicitly at the cursor location.</param>
/// <param name="sourceCodeKind">The sourcecodekind to run this test on. If null, runs on both regular and script sources.</param>
protected virtual async Task TestAsync(
string markup,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false,
SourceCodeKind? sourceCodeKind = null,
bool experimental = false)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
if (sourceCodeKind.HasValue)
{
await TestSignatureHelpWorkerAsync(markup, sourceCodeKind.Value, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
else
{
await TestSignatureHelpWorkerAsync(markup, SourceCodeKind.Regular, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
await TestSignatureHelpWorkerAsync(markup, SourceCodeKind.Script, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
}
private async Task TestSignatureHelpWorkerAsync(
string markupWithPositionAndOptSpan,
SourceCodeKind sourceCodeKind,
bool experimental,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
markupWithPositionAndOptSpan = markupWithPositionAndOptSpan.NormalizeLineEndings();
TextSpan? textSpan = null;
MarkupTestFile.GetPositionAndSpans(
markupWithPositionAndOptSpan,
out var code,
out var cursorPosition,
out ImmutableArray<TextSpan> textSpans);
if (textSpans.Any())
{
textSpan = textSpans.First();
}
var parseOptions = CreateExperimentalParseOptions();
// regular
var document1 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind);
if (experimental)
{
document1 = document1.Project.WithParseOptions(parseOptions).GetDocument(document1.Id);
}
await TestSignatureHelpWorkerSharedAsync(workspaceFixture.Target.GetWorkspace(), code, cursorPosition, document1, textSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
// speculative semantic model
if (await CanUseSpeculativeSemanticModelAsync(document1, cursorPosition))
{
var document2 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind, cleanBeforeUpdate: false);
if (experimental)
{
document2 = document2.Project.WithParseOptions(parseOptions).GetDocument(document2.Id);
}
await TestSignatureHelpWorkerSharedAsync(workspaceFixture.Target.GetWorkspace(), code, cursorPosition, document2, textSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
}
protected abstract ParseOptions CreateExperimentalParseOptions();
private static async Task<bool> CanUseSpeculativeSemanticModelAsync(Document document, int position)
{
var service = document.GetLanguageService<ISyntaxFactsService>();
var node = (await document.GetSyntaxRootAsync()).FindToken(position).Parent;
return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty;
}
protected void VerifyTriggerCharacters(char[] expectedTriggerCharacters, char[] unexpectedTriggerCharacters)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspaceFixture.Target.GetWorkspace().ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
foreach (var expectedTriggerCharacter in expectedTriggerCharacters)
{
Assert.True(signatureHelpProvider.IsTriggerCharacter(expectedTriggerCharacter), "Expected '" + expectedTriggerCharacter + "' to be a trigger character");
}
foreach (var unexpectedTriggerCharacter in unexpectedTriggerCharacters)
{
Assert.False(signatureHelpProvider.IsTriggerCharacter(unexpectedTriggerCharacter), "Expected '" + unexpectedTriggerCharacter + "' to NOT be a trigger character");
}
}
protected virtual async Task VerifyCurrentParameterNameAsync(string markup, string expectedParameterName, SourceCodeKind? sourceCodeKind = null)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
if (sourceCodeKind.HasValue)
{
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, sourceCodeKind.Value);
}
else
{
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, SourceCodeKind.Regular);
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, SourceCodeKind.Script);
}
}
private static async Task<SignatureHelpState> GetArgumentStateAsync(int cursorPosition, Document document, ISignatureHelpProvider signatureHelpProvider, SignatureHelpTriggerInfo triggerInfo)
{
var items = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
return items == null ? null : new SignatureHelpState(items.ArgumentIndex, items.ArgumentCount, items.ArgumentName, null);
}
private async Task VerifyCurrentParameterNameWorkerAsync(string markup, string expectedParameterName, SourceCodeKind sourceCodeKind)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out var code, out int cursorPosition);
var document = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind);
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspaceFixture.Target.GetWorkspace().ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
_ = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
Assert.Equal(expectedParameterName, (await GetArgumentStateAsync(cursorPosition, document, signatureHelpProvider, triggerInfo)).ArgumentName);
}
private static void CompareAndAssertCollectionsAndCurrentParameter(
IEnumerable<SignatureHelpTestItem> expectedTestItems, SignatureHelpItems actualSignatureHelpItems)
{
Assert.Equal(expectedTestItems.Count(), actualSignatureHelpItems.Items.Count());
for (var i = 0; i < expectedTestItems.Count(); i++)
{
CompareSigHelpItemsAndCurrentPosition(
actualSignatureHelpItems,
actualSignatureHelpItems.Items.ElementAt(i),
expectedTestItems.ElementAt(i));
}
}
private static void CompareSigHelpItemsAndCurrentPosition(
SignatureHelpItems items,
SignatureHelpItem actualSignatureHelpItem,
SignatureHelpTestItem expectedTestItem)
{
var currentParameterIndex = -1;
if (expectedTestItem.CurrentParameterIndex != null)
{
if (expectedTestItem.CurrentParameterIndex.Value >= 0 && expectedTestItem.CurrentParameterIndex.Value < actualSignatureHelpItem.Parameters.Length)
{
currentParameterIndex = expectedTestItem.CurrentParameterIndex.Value;
}
}
var signature = new Signature(applicableToSpan: null, signatureHelpItem: actualSignatureHelpItem, selectedParameterIndex: currentParameterIndex);
// We're a match if the signature matches...
// We're now combining the signature and documentation to make classification work.
if (!string.IsNullOrEmpty(expectedTestItem.MethodDocumentation))
{
Assert.Equal(expectedTestItem.Signature + "\r\n" + expectedTestItem.MethodDocumentation, signature.Content);
}
else
{
Assert.Equal(expectedTestItem.Signature, signature.Content);
}
if (expectedTestItem.PrettyPrintedSignature != null)
{
Assert.Equal(expectedTestItem.PrettyPrintedSignature, signature.PrettyPrintedContent);
}
if (expectedTestItem.MethodDocumentation != null)
{
Assert.Equal(expectedTestItem.MethodDocumentation, actualSignatureHelpItem.DocumentationFactory(CancellationToken.None).GetFullText());
}
if (expectedTestItem.ParameterDocumentation != null)
{
Assert.Equal(expectedTestItem.ParameterDocumentation, signature.CurrentParameter.Documentation);
}
if (expectedTestItem.CurrentParameterIndex != null)
{
Assert.Equal(expectedTestItem.CurrentParameterIndex, items.ArgumentIndex);
}
if (expectedTestItem.Description != null)
{
Assert.Equal(expectedTestItem.Description, ToString(actualSignatureHelpItem.DescriptionParts));
}
// Always get and realise the classified spans, even if no expected spans are passed in, to at least validate that
// exceptions aren't thrown
var classifiedSpans = actualSignatureHelpItem.DocumentationFactory(CancellationToken.None).ToClassifiedSpans().ToList();
if (expectedTestItem.ClassificationTypeNames is { } classificationTypeNames)
{
Assert.Equal(string.Join(", ", classificationTypeNames), string.Join(", ", classifiedSpans.Select(s => s.ClassificationType)));
}
}
private static string ToString(IEnumerable<TaggedText> list)
=> string.Concat(list.Select(i => i.ToString()));
protected async Task TestSignatureHelpInEditorBrowsableContextsAsync(
string markup,
string referencedCode,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsMetadataReference,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsSameSolution,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false)
{
if (expectedOrderedItemsMetadataReference == null || expectedOrderedItemsSameSolution == null)
{
AssertEx.Fail("Expected signature help items must be provided for EditorBrowsable tests. If there are no expected items, provide an empty IEnumerable rather than null.");
}
await TestSignatureHelpWithMetadataReferenceHelperAsync(markup, referencedCode, expectedOrderedItemsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers);
await TestSignatureHelpWithProjectReferenceHelperAsync(markup, referencedCode, expectedOrderedItemsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers);
// Multi-language projects are not supported.
if (sourceLanguage == referencedLanguage)
{
await TestSignatureHelpInSameProjectHelperAsync(markup, referencedCode, expectedOrderedItemsSameSolution, sourceLanguage, hideAdvancedMembers);
}
}
public Task TestSignatureHelpWithMetadataReferenceHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</MetadataReferenceFromSource>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
return VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
public async Task TestSignatureHelpWithProjectReferenceHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<ProjectReference>ReferencedProject</ProjectReference>
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
<Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
private async Task TestSignatureHelpInSameProjectHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<Document FilePath=""ReferencedDocument"">
{2}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode));
await VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
protected async Task VerifyItemWithReferenceWorkerAsync(string xmlString, IEnumerable<SignatureHelpTestItem> expectedOrderedItems, bool hideAdvancedMembers)
{
using var testWorkspace = TestWorkspace.Create(xmlString);
var cursorPosition = testWorkspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = testWorkspace.Documents.First(d => d.Name == "SourceDocument").Id;
var document = testWorkspace.CurrentSolution.GetDocument(documentId);
testWorkspace.TryApplyChanges(testWorkspace.CurrentSolution.WithOptions(testWorkspace.Options
.WithChangedOption(CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers)));
document = testWorkspace.CurrentSolution.GetDocument(documentId);
var code = (await document.GetTextAsync()).ToString();
IList<TextSpan> textSpans = null;
var selectedSpans = testWorkspace.Documents.First(d => d.Name == "SourceDocument").SelectedSpans;
if (selectedSpans.Any())
{
textSpans = selectedSpans;
}
TextSpan? textSpan = null;
if (textSpans != null && textSpans.Any())
{
textSpan = textSpans.First();
}
await TestSignatureHelpWorkerSharedAsync(testWorkspace, code, cursorPosition, document, textSpan, expectedOrderedItems);
}
private async Task TestSignatureHelpWorkerSharedAsync(
TestWorkspace workspace,
string code,
int cursorPosition,
Document document,
TextSpan? textSpan,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false)
{
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspace.ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
if (usePreviousCharAsTrigger)
{
triggerInfo = new SignatureHelpTriggerInfo(
SignatureHelpTriggerReason.TypeCharCommand,
code.ElementAt(cursorPosition - 1));
if (!signatureHelpProvider.IsTriggerCharacter(triggerInfo.TriggerCharacter.Value))
{
return;
}
}
var items = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
// If we're expecting 0 items, then there's no need to compare them
if ((expectedOrderedItemsOrNull == null || !expectedOrderedItemsOrNull.Any()) && items == null)
{
return;
}
AssertEx.NotNull(items, "Signature help provider returned null for items. Did you forget $$ in the test or is the test otherwise malformed, e.g. quotes not escaped?");
// Verify the span
if (textSpan != null)
{
Assert.Equal(textSpan, items.ApplicableSpan);
}
if (expectedOrderedItemsOrNull != null)
{
CompareAndAssertCollectionsAndCurrentParameter(expectedOrderedItemsOrNull, items);
CompareSelectedIndex(expectedOrderedItemsOrNull, items.SelectedItemIndex);
}
}
private static void CompareSelectedIndex(IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull, int? selectedItemIndex)
{
if (expectedOrderedItemsOrNull == null ||
!expectedOrderedItemsOrNull.Any(i => i.IsSelected))
{
return;
}
Assert.True(expectedOrderedItemsOrNull.Count(i => i.IsSelected) == 1, "Only one expected item can be marked with 'IsSelected'");
Assert.True(selectedItemIndex != null, "Expected an item to be selected, but no item was actually selected");
var counter = 0;
foreach (var item in expectedOrderedItemsOrNull)
{
if (item.IsSelected)
{
Assert.True(selectedItemIndex == counter,
$"Expected item with index {counter} to be selected, but the actual selected index is {selectedItemIndex}.");
}
else
{
Assert.True(selectedItemIndex != counter,
$"Found unexpected selected item. Actual selected index is {selectedItemIndex}.");
}
counter++;
}
}
protected async Task TestSignatureHelpWithMscorlib45Async(
string markup,
IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferencesNet45=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(markup));
using var testWorkspace = TestWorkspace.Create(xmlString);
var cursorPosition = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = testWorkspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id;
var document = testWorkspace.CurrentSolution.GetDocument(documentId);
var code = (await document.GetTextAsync()).ToString();
IList<TextSpan> textSpans = null;
var selectedSpans = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").SelectedSpans;
if (selectedSpans.Any())
{
textSpans = selectedSpans;
}
TextSpan? textSpan = null;
if (textSpans != null && textSpans.Any())
{
textSpan = textSpans.First();
}
await TestSignatureHelpWorkerSharedAsync(testWorkspace, code, cursorPosition, document, textSpan, expectedOrderedItems);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Classification;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp
{
[UseExportProvider]
public abstract class AbstractSignatureHelpProviderTests<TWorkspaceFixture> : TestBase
where TWorkspaceFixture : TestWorkspaceFixture, new()
{
private readonly TestFixtureHelper<TWorkspaceFixture> _fixtureHelper = new();
internal abstract Type GetSignatureHelpProviderType();
private protected ReferenceCountedDisposable<TWorkspaceFixture> GetOrCreateWorkspaceFixture()
=> _fixtureHelper.GetOrCreateFixture();
/// <summary>
/// Verifies that sighelp comes up at the indicated location in markup ($$), with the indicated span [| ... |].
/// </summary>
/// <param name="markup">Input markup with $$ denoting the cursor position, and [| ... |]
/// denoting the expected sighelp span</param>
/// <param name="expectedOrderedItemsOrNull">The exact expected sighelp items list. If null, this part of the test is ignored.</param>
/// <param name="usePreviousCharAsTrigger">If true, uses the last character before $$ to trigger sighelp.
/// If false, invokes sighelp explicitly at the cursor location.</param>
/// <param name="sourceCodeKind">The sourcecodekind to run this test on. If null, runs on both regular and script sources.</param>
protected virtual async Task TestAsync(
string markup,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false,
SourceCodeKind? sourceCodeKind = null,
bool experimental = false)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
if (sourceCodeKind.HasValue)
{
await TestSignatureHelpWorkerAsync(markup, sourceCodeKind.Value, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
else
{
await TestSignatureHelpWorkerAsync(markup, SourceCodeKind.Regular, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
await TestSignatureHelpWorkerAsync(markup, SourceCodeKind.Script, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
}
private async Task TestSignatureHelpWorkerAsync(
string markupWithPositionAndOptSpan,
SourceCodeKind sourceCodeKind,
bool experimental,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
markupWithPositionAndOptSpan = markupWithPositionAndOptSpan.NormalizeLineEndings();
TextSpan? textSpan = null;
MarkupTestFile.GetPositionAndSpans(
markupWithPositionAndOptSpan,
out var code,
out var cursorPosition,
out ImmutableArray<TextSpan> textSpans);
if (textSpans.Any())
{
textSpan = textSpans.First();
}
var parseOptions = CreateExperimentalParseOptions();
// regular
var document1 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind);
if (experimental)
{
document1 = document1.Project.WithParseOptions(parseOptions).GetDocument(document1.Id);
}
await TestSignatureHelpWorkerSharedAsync(workspaceFixture.Target.GetWorkspace(), code, cursorPosition, document1, textSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
// speculative semantic model
if (await CanUseSpeculativeSemanticModelAsync(document1, cursorPosition))
{
var document2 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind, cleanBeforeUpdate: false);
if (experimental)
{
document2 = document2.Project.WithParseOptions(parseOptions).GetDocument(document2.Id);
}
await TestSignatureHelpWorkerSharedAsync(workspaceFixture.Target.GetWorkspace(), code, cursorPosition, document2, textSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
}
protected abstract ParseOptions CreateExperimentalParseOptions();
private static async Task<bool> CanUseSpeculativeSemanticModelAsync(Document document, int position)
{
var service = document.GetLanguageService<ISyntaxFactsService>();
var node = (await document.GetSyntaxRootAsync()).FindToken(position).Parent;
return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty;
}
protected void VerifyTriggerCharacters(char[] expectedTriggerCharacters, char[] unexpectedTriggerCharacters)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspaceFixture.Target.GetWorkspace().ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
foreach (var expectedTriggerCharacter in expectedTriggerCharacters)
{
Assert.True(signatureHelpProvider.IsTriggerCharacter(expectedTriggerCharacter), "Expected '" + expectedTriggerCharacter + "' to be a trigger character");
}
foreach (var unexpectedTriggerCharacter in unexpectedTriggerCharacters)
{
Assert.False(signatureHelpProvider.IsTriggerCharacter(unexpectedTriggerCharacter), "Expected '" + unexpectedTriggerCharacter + "' to NOT be a trigger character");
}
}
protected virtual async Task VerifyCurrentParameterNameAsync(string markup, string expectedParameterName, SourceCodeKind? sourceCodeKind = null)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
if (sourceCodeKind.HasValue)
{
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, sourceCodeKind.Value);
}
else
{
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, SourceCodeKind.Regular);
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, SourceCodeKind.Script);
}
}
private static async Task<SignatureHelpState> GetArgumentStateAsync(int cursorPosition, Document document, ISignatureHelpProvider signatureHelpProvider, SignatureHelpTriggerInfo triggerInfo)
{
var items = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
return items == null ? null : new SignatureHelpState(items.ArgumentIndex, items.ArgumentCount, items.ArgumentName, null);
}
private async Task VerifyCurrentParameterNameWorkerAsync(string markup, string expectedParameterName, SourceCodeKind sourceCodeKind)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out var code, out int cursorPosition);
var document = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind);
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspaceFixture.Target.GetWorkspace().ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
_ = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
Assert.Equal(expectedParameterName, (await GetArgumentStateAsync(cursorPosition, document, signatureHelpProvider, triggerInfo)).ArgumentName);
}
private static void CompareAndAssertCollectionsAndCurrentParameter(
IEnumerable<SignatureHelpTestItem> expectedTestItems, SignatureHelpItems actualSignatureHelpItems)
{
Assert.Equal(expectedTestItems.Count(), actualSignatureHelpItems.Items.Count());
for (var i = 0; i < expectedTestItems.Count(); i++)
{
CompareSigHelpItemsAndCurrentPosition(
actualSignatureHelpItems,
actualSignatureHelpItems.Items.ElementAt(i),
expectedTestItems.ElementAt(i));
}
}
private static void CompareSigHelpItemsAndCurrentPosition(
SignatureHelpItems items,
SignatureHelpItem actualSignatureHelpItem,
SignatureHelpTestItem expectedTestItem)
{
var currentParameterIndex = -1;
if (expectedTestItem.CurrentParameterIndex != null)
{
if (expectedTestItem.CurrentParameterIndex.Value >= 0 && expectedTestItem.CurrentParameterIndex.Value < actualSignatureHelpItem.Parameters.Length)
{
currentParameterIndex = expectedTestItem.CurrentParameterIndex.Value;
}
}
var signature = new Signature(applicableToSpan: null, signatureHelpItem: actualSignatureHelpItem, selectedParameterIndex: currentParameterIndex);
// We're a match if the signature matches...
// We're now combining the signature and documentation to make classification work.
if (!string.IsNullOrEmpty(expectedTestItem.MethodDocumentation))
{
Assert.Equal(expectedTestItem.Signature + "\r\n" + expectedTestItem.MethodDocumentation, signature.Content);
}
else
{
Assert.Equal(expectedTestItem.Signature, signature.Content);
}
if (expectedTestItem.PrettyPrintedSignature != null)
{
Assert.Equal(expectedTestItem.PrettyPrintedSignature, signature.PrettyPrintedContent);
}
if (expectedTestItem.MethodDocumentation != null)
{
Assert.Equal(expectedTestItem.MethodDocumentation, actualSignatureHelpItem.DocumentationFactory(CancellationToken.None).GetFullText());
}
if (expectedTestItem.ParameterDocumentation != null)
{
Assert.Equal(expectedTestItem.ParameterDocumentation, signature.CurrentParameter.Documentation);
}
if (expectedTestItem.CurrentParameterIndex != null)
{
Assert.Equal(expectedTestItem.CurrentParameterIndex, items.ArgumentIndex);
}
if (expectedTestItem.Description != null)
{
Assert.Equal(expectedTestItem.Description, ToString(actualSignatureHelpItem.DescriptionParts));
}
// Always get and realise the classified spans, even if no expected spans are passed in, to at least validate that
// exceptions aren't thrown
var classifiedSpans = actualSignatureHelpItem.DocumentationFactory(CancellationToken.None).ToClassifiedSpans().ToList();
if (expectedTestItem.ClassificationTypeNames is { } classificationTypeNames)
{
Assert.Equal(string.Join(", ", classificationTypeNames), string.Join(", ", classifiedSpans.Select(s => s.ClassificationType)));
}
}
private static string ToString(IEnumerable<TaggedText> list)
=> string.Concat(list.Select(i => i.ToString()));
protected async Task TestSignatureHelpInEditorBrowsableContextsAsync(
string markup,
string referencedCode,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsMetadataReference,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsSameSolution,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false)
{
if (expectedOrderedItemsMetadataReference == null || expectedOrderedItemsSameSolution == null)
{
AssertEx.Fail("Expected signature help items must be provided for EditorBrowsable tests. If there are no expected items, provide an empty IEnumerable rather than null.");
}
await TestSignatureHelpWithMetadataReferenceHelperAsync(markup, referencedCode, expectedOrderedItemsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers);
await TestSignatureHelpWithProjectReferenceHelperAsync(markup, referencedCode, expectedOrderedItemsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers);
// Multi-language projects are not supported.
if (sourceLanguage == referencedLanguage)
{
await TestSignatureHelpInSameProjectHelperAsync(markup, referencedCode, expectedOrderedItemsSameSolution, sourceLanguage, hideAdvancedMembers);
}
}
public Task TestSignatureHelpWithMetadataReferenceHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</MetadataReferenceFromSource>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
return VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
public async Task TestSignatureHelpWithProjectReferenceHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<ProjectReference>ReferencedProject</ProjectReference>
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
<Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
private async Task TestSignatureHelpInSameProjectHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<Document FilePath=""ReferencedDocument"">
{2}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode));
await VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
protected async Task VerifyItemWithReferenceWorkerAsync(string xmlString, IEnumerable<SignatureHelpTestItem> expectedOrderedItems, bool hideAdvancedMembers)
{
using var testWorkspace = TestWorkspace.Create(xmlString);
var cursorPosition = testWorkspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = testWorkspace.Documents.First(d => d.Name == "SourceDocument").Id;
var document = testWorkspace.CurrentSolution.GetDocument(documentId);
testWorkspace.TryApplyChanges(testWorkspace.CurrentSolution.WithOptions(testWorkspace.Options
.WithChangedOption(CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers)));
document = testWorkspace.CurrentSolution.GetDocument(documentId);
var code = (await document.GetTextAsync()).ToString();
IList<TextSpan> textSpans = null;
var selectedSpans = testWorkspace.Documents.First(d => d.Name == "SourceDocument").SelectedSpans;
if (selectedSpans.Any())
{
textSpans = selectedSpans;
}
TextSpan? textSpan = null;
if (textSpans != null && textSpans.Any())
{
textSpan = textSpans.First();
}
await TestSignatureHelpWorkerSharedAsync(testWorkspace, code, cursorPosition, document, textSpan, expectedOrderedItems);
}
private async Task TestSignatureHelpWorkerSharedAsync(
TestWorkspace workspace,
string code,
int cursorPosition,
Document document,
TextSpan? textSpan,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false)
{
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspace.ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
if (usePreviousCharAsTrigger)
{
triggerInfo = new SignatureHelpTriggerInfo(
SignatureHelpTriggerReason.TypeCharCommand,
code.ElementAt(cursorPosition - 1));
if (!signatureHelpProvider.IsTriggerCharacter(triggerInfo.TriggerCharacter.Value))
{
return;
}
}
var items = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
// If we're expecting 0 items, then there's no need to compare them
if ((expectedOrderedItemsOrNull == null || !expectedOrderedItemsOrNull.Any()) && items == null)
{
return;
}
AssertEx.NotNull(items, "Signature help provider returned null for items. Did you forget $$ in the test or is the test otherwise malformed, e.g. quotes not escaped?");
// Verify the span
if (textSpan != null)
{
Assert.Equal(textSpan, items.ApplicableSpan);
}
if (expectedOrderedItemsOrNull != null)
{
CompareAndAssertCollectionsAndCurrentParameter(expectedOrderedItemsOrNull, items);
CompareSelectedIndex(expectedOrderedItemsOrNull, items.SelectedItemIndex);
}
}
private static void CompareSelectedIndex(IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull, int? selectedItemIndex)
{
if (expectedOrderedItemsOrNull == null ||
!expectedOrderedItemsOrNull.Any(i => i.IsSelected))
{
return;
}
Assert.True(expectedOrderedItemsOrNull.Count(i => i.IsSelected) == 1, "Only one expected item can be marked with 'IsSelected'");
Assert.True(selectedItemIndex != null, "Expected an item to be selected, but no item was actually selected");
var counter = 0;
foreach (var item in expectedOrderedItemsOrNull)
{
if (item.IsSelected)
{
Assert.True(selectedItemIndex == counter,
$"Expected item with index {counter} to be selected, but the actual selected index is {selectedItemIndex}.");
}
else
{
Assert.True(selectedItemIndex != counter,
$"Found unexpected selected item. Actual selected index is {selectedItemIndex}.");
}
counter++;
}
}
protected async Task TestSignatureHelpWithMscorlib45Async(
string markup,
IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferencesNet45=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(markup));
using var testWorkspace = TestWorkspace.Create(xmlString);
var cursorPosition = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = testWorkspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id;
var document = testWorkspace.CurrentSolution.GetDocument(documentId);
var code = (await document.GetTextAsync()).ToString();
IList<TextSpan> textSpans = null;
var selectedSpans = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").SelectedSpans;
if (selectedSpans.Any())
{
textSpans = selectedSpans;
}
TextSpan? textSpan = null;
if (textSpans != null && textSpans.Any())
{
textSpan = textSpans.First();
}
await TestSignatureHelpWorkerSharedAsync(testWorkspace, code, cursorPosition, document, textSpan, expectedOrderedItems);
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/Core/Portable/Operations/DisposeOperationInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Operations
{
internal struct DisposeOperationInfo
{
public readonly IMethodSymbol? DisposeMethod;
public readonly ImmutableArray<IArgumentOperation> DisposeArguments;
public DisposeOperationInfo(IMethodSymbol? disposeMethod, ImmutableArray<IArgumentOperation> disposeArguments)
{
DisposeMethod = disposeMethod;
DisposeArguments = disposeArguments;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Operations
{
internal struct DisposeOperationInfo
{
public readonly IMethodSymbol? DisposeMethod;
public readonly ImmutableArray<IArgumentOperation> DisposeArguments;
public DisposeOperationInfo(IMethodSymbol? disposeMethod, ImmutableArray<IArgumentOperation> disposeArguments)
{
DisposeMethod = disposeMethod;
DisposeArguments = disposeArguments;
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/Test/Core/Diagnostics/EmptyArrayAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
/// <summary>Analyzer that looks for empty array allocations and recommends their replacement.</summary>
public class EmptyArrayAnalyzer : DiagnosticAnalyzer
{
private const string SystemCategory = "System";
/// <summary>The name of the array type.</summary>
internal const string ArrayTypeName = "System.Array"; // using instead of GetSpecialType to make more testable
/// <summary>The name of the Empty method on System.Array.</summary>
internal const string ArrayEmptyMethodName = "Empty";
private static readonly LocalizableString s_localizableTitle = "Empty Array";
private static readonly LocalizableString s_localizableMessage = "Empty array creation can be replaced with Array.Empty";
/// <summary>The diagnostic descriptor used when Array.Empty should be used instead of a new array allocation.</summary>
public static readonly DiagnosticDescriptor UseArrayEmptyDescriptor = new DiagnosticDescriptor(
"EmptyArrayRule",
s_localizableTitle,
s_localizableMessage,
SystemCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(UseArrayEmptyDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(ctx =>
{
RegisterOperationAction(ctx);
});
}
/// <summary>Reports a diagnostic warning for an array creation that should be replaced.</summary>
/// <param name="context">The context.</param>
/// <param name="arrayCreationExpression">The array creation expression to be replaced.</param>
internal void Report(OperationAnalysisContext context, SyntaxNode arrayCreationExpression)
{
context.ReportDiagnostic(Diagnostic.Create(UseArrayEmptyDescriptor, arrayCreationExpression.GetLocation()));
}
/// <summary>Called once at compilation start to register actions in the compilation context.</summary>
/// <param name="context">The analysis context.</param>
internal void RegisterOperationAction(CompilationStartAnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
IArrayCreationOperation arrayCreation = (IArrayCreationOperation)operationContext.Operation;
// ToDo: Need to suppress analysis of array creation expressions within attribute applications.
// Detect array creation expression that have rank 1 and size 0. Such expressions
// can be replaced with Array.Empty<T>(), provided that the element type can be a generic type argument.
var elementType = (arrayCreation as IArrayTypeSymbol)?.ElementType;
if (arrayCreation.DimensionSizes.Length == 1
//// Pointer types can't be generic type arguments.
&& elementType?.TypeKind != TypeKind.Pointer)
{
Optional<object> arrayLength = arrayCreation.DimensionSizes[0].ConstantValue;
if (arrayLength.HasValue &&
arrayLength.Value is int &&
(int)arrayLength.Value == 0)
{
Report(operationContext, arrayCreation.Syntax);
}
}
},
OperationKind.ArrayCreation);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
/// <summary>Analyzer that looks for empty array allocations and recommends their replacement.</summary>
public class EmptyArrayAnalyzer : DiagnosticAnalyzer
{
private const string SystemCategory = "System";
/// <summary>The name of the array type.</summary>
internal const string ArrayTypeName = "System.Array"; // using instead of GetSpecialType to make more testable
/// <summary>The name of the Empty method on System.Array.</summary>
internal const string ArrayEmptyMethodName = "Empty";
private static readonly LocalizableString s_localizableTitle = "Empty Array";
private static readonly LocalizableString s_localizableMessage = "Empty array creation can be replaced with Array.Empty";
/// <summary>The diagnostic descriptor used when Array.Empty should be used instead of a new array allocation.</summary>
public static readonly DiagnosticDescriptor UseArrayEmptyDescriptor = new DiagnosticDescriptor(
"EmptyArrayRule",
s_localizableTitle,
s_localizableMessage,
SystemCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(UseArrayEmptyDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(ctx =>
{
RegisterOperationAction(ctx);
});
}
/// <summary>Reports a diagnostic warning for an array creation that should be replaced.</summary>
/// <param name="context">The context.</param>
/// <param name="arrayCreationExpression">The array creation expression to be replaced.</param>
internal void Report(OperationAnalysisContext context, SyntaxNode arrayCreationExpression)
{
context.ReportDiagnostic(Diagnostic.Create(UseArrayEmptyDescriptor, arrayCreationExpression.GetLocation()));
}
/// <summary>Called once at compilation start to register actions in the compilation context.</summary>
/// <param name="context">The analysis context.</param>
internal void RegisterOperationAction(CompilationStartAnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
IArrayCreationOperation arrayCreation = (IArrayCreationOperation)operationContext.Operation;
// ToDo: Need to suppress analysis of array creation expressions within attribute applications.
// Detect array creation expression that have rank 1 and size 0. Such expressions
// can be replaced with Array.Empty<T>(), provided that the element type can be a generic type argument.
var elementType = (arrayCreation as IArrayTypeSymbol)?.ElementType;
if (arrayCreation.DimensionSizes.Length == 1
//// Pointer types can't be generic type arguments.
&& elementType?.TypeKind != TypeKind.Pointer)
{
Optional<object> arrayLength = arrayCreation.DimensionSizes[0].ConstantValue;
if (arrayLength.HasValue &&
arrayLength.Value is int &&
(int)arrayLength.Value == 0)
{
Report(operationContext, arrayCreation.Syntax);
}
}
},
OperationKind.ArrayCreation);
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/SyncLockKeywordRecommender.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 "SyncLock" keyword for the statement context
''' </summary>
Friend Class SyncLockKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("SyncLock", VBFeaturesResources.Ensures_that_multiple_threads_do_not_execute_the_statement_block_at_the_same_time_SyncLock_object_End_Synclock))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsMultiLineStatementContext, s_keywords, 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 "SyncLock" keyword for the statement context
''' </summary>
Friend Class SyncLockKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("SyncLock", VBFeaturesResources.Ensures_that_multiple_threads_do_not_execute_the_statement_block_at_the_same_time_SyncLock_object_End_Synclock))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsMultiLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/VisualStudio/Core/Test/Progression/InheritedByGraphQueryTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.GraphModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
<UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)>
Public Class InheritedByGraphQueryTests
<WpfFact>
Public Async Function TestInheritedByClassesCSharp() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
using System;
interface IBlah {
}
abstract class $$Base
{
public abstract int CompareTo(object obj);
}
class Goo : Base, IComparable, IBlah
{
public override int CompareTo(object obj)
{
throw new NotImplementedException();
}
}
class Goo2 : Base, IBlah
{
public override int CompareTo(object obj)
{
throw new NotImplementedException();
}
}
class ReallyDerived : Goo // should not be shown as inherited by Base
{
}
</Document>
</Project>
</Workspace>)
Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=Base)" Category="CodeSchema_Class" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="Base" Icon="Microsoft.VisualStudio.Class.Internal" Label="Base"/>
<Node Id="(@1 Type=Goo)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo"/>
<Node Id="(@1 Type=Goo2)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo2" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo2"/>
</Nodes>
<Links>
<Link Source="(@1 Type=Goo)" Target="(@1 Type=Base)" Category="InheritsFrom"/>
<Link Source="(@1 Type=Goo2)" Target="(@1 Type=Base)" Category="InheritsFrom"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
<WpfFact>
Public Async Function TestInheritedByInterfacesCSharp() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
using System;
public interface $$I { }
public class C : I { } // should appear as being derived from (implementing) I
public class C2 : C { } // should not appear as being derived from (implementing) I
interface I2 : I, IComparable
{
void M();
}
interface I3 : I2 // should not be shown as inherited by I
{
}
</Document>
</Project>
</Workspace>)
Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=C)" Category="CodeSchema_Class" CodeSchemaProperty_IsPublic="True" CommonLabel="C" Icon="Microsoft.VisualStudio.Class.Public" Label="C"/>
<Node Id="(@1 Type=I)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsPublic="True" CommonLabel="I" Icon="Microsoft.VisualStudio.Interface.Public" Label="I"/>
<Node Id="(@1 Type=I2)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="I2" Icon="Microsoft.VisualStudio.Interface.Internal" Label="I2"/>
</Nodes>
<Links>
<Link Source="(@1 Type=C)" Target="(@1 Type=I)" Category="InheritsFrom"/>
<Link Source="(@1 Type=I2)" Target="(@1 Type=I)" Category="InheritsFrom"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
<WpfFact>
Public Async Function TestInheritedByClassesVisualBasic() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj">
<Document FilePath="Z:\Project.vb">
Imports System
Interface IBlah
End Interface
MustInherit Class $$Base
Public MustOverride Function CompareTo(obj As Object) As Integer
End Class
Class Goo
Inherits Base
Implements IComparable, IBlah
Public Overrides Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
Throw New NotImplementedException()
End Function
End Class
Class Goo2
Inherits Base
Implements IBlah
Public Overrides Function CompareTo(obj As Object) As Integer
Throw New NotImplementedException()
End Function
End Class
Class ReallyDerived ' should not be shown as inherited by Base
Inherits Goo
End Class
</Document>
</Project>
</Workspace>)
Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=Base)" Category="CodeSchema_Class" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="Base" Icon="Microsoft.VisualStudio.Class.Internal" Label="Base"/>
<Node Id="(@1 Type=Goo)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo"/>
<Node Id="(@1 Type=Goo2)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo2" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo2"/>
</Nodes>
<Links>
<Link Source="(@1 Type=Goo)" Target="(@1 Type=Base)" Category="InheritsFrom"/>
<Link Source="(@1 Type=Goo2)" Target="(@1 Type=Base)" Category="InheritsFrom"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/VisualBasicAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
<WpfFact>
Public Async Function TestInheritedByInterfacesVisualBasic() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj">
<Document FilePath="Z:\Project.vb">
Imports System
Public Interface $$I
End Interface
Public Class C ' should appear as being derived from (implementing) I
Implements I
End Class
Public Class C2 ' should not appear as being derived from (implementing) I
Inherits C
End Class
Interface I2
Inherits I, IComparable
Sub M()
End Interface
Interface I3 ' should not be shown as inherited by I
Inherits I2
End Interface
</Document>
</Project>
</Workspace>)
Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=C)" Category="CodeSchema_Class" CodeSchemaProperty_IsPublic="True" CommonLabel="C" Icon="Microsoft.VisualStudio.Class.Public" Label="C"/>
<Node Id="(@1 Type=I)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsPublic="True" CommonLabel="I" Icon="Microsoft.VisualStudio.Interface.Public" Label="I"/>
<Node Id="(@1 Type=I2)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="I2" Icon="Microsoft.VisualStudio.Interface.Internal" Label="I2"/>
</Nodes>
<Links>
<Link Source="(@1 Type=C)" Target="(@1 Type=I)" Category="InheritsFrom"/>
<Link Source="(@1 Type=I2)" Target="(@1 Type=I)" Category="InheritsFrom"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/VisualBasicAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.GraphModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
<UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)>
Public Class InheritedByGraphQueryTests
<WpfFact>
Public Async Function TestInheritedByClassesCSharp() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
using System;
interface IBlah {
}
abstract class $$Base
{
public abstract int CompareTo(object obj);
}
class Goo : Base, IComparable, IBlah
{
public override int CompareTo(object obj)
{
throw new NotImplementedException();
}
}
class Goo2 : Base, IBlah
{
public override int CompareTo(object obj)
{
throw new NotImplementedException();
}
}
class ReallyDerived : Goo // should not be shown as inherited by Base
{
}
</Document>
</Project>
</Workspace>)
Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=Base)" Category="CodeSchema_Class" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="Base" Icon="Microsoft.VisualStudio.Class.Internal" Label="Base"/>
<Node Id="(@1 Type=Goo)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo"/>
<Node Id="(@1 Type=Goo2)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo2" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo2"/>
</Nodes>
<Links>
<Link Source="(@1 Type=Goo)" Target="(@1 Type=Base)" Category="InheritsFrom"/>
<Link Source="(@1 Type=Goo2)" Target="(@1 Type=Base)" Category="InheritsFrom"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
<WpfFact>
Public Async Function TestInheritedByInterfacesCSharp() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
using System;
public interface $$I { }
public class C : I { } // should appear as being derived from (implementing) I
public class C2 : C { } // should not appear as being derived from (implementing) I
interface I2 : I, IComparable
{
void M();
}
interface I3 : I2 // should not be shown as inherited by I
{
}
</Document>
</Project>
</Workspace>)
Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=C)" Category="CodeSchema_Class" CodeSchemaProperty_IsPublic="True" CommonLabel="C" Icon="Microsoft.VisualStudio.Class.Public" Label="C"/>
<Node Id="(@1 Type=I)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsPublic="True" CommonLabel="I" Icon="Microsoft.VisualStudio.Interface.Public" Label="I"/>
<Node Id="(@1 Type=I2)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="I2" Icon="Microsoft.VisualStudio.Interface.Internal" Label="I2"/>
</Nodes>
<Links>
<Link Source="(@1 Type=C)" Target="(@1 Type=I)" Category="InheritsFrom"/>
<Link Source="(@1 Type=I2)" Target="(@1 Type=I)" Category="InheritsFrom"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
<WpfFact>
Public Async Function TestInheritedByClassesVisualBasic() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj">
<Document FilePath="Z:\Project.vb">
Imports System
Interface IBlah
End Interface
MustInherit Class $$Base
Public MustOverride Function CompareTo(obj As Object) As Integer
End Class
Class Goo
Inherits Base
Implements IComparable, IBlah
Public Overrides Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
Throw New NotImplementedException()
End Function
End Class
Class Goo2
Inherits Base
Implements IBlah
Public Overrides Function CompareTo(obj As Object) As Integer
Throw New NotImplementedException()
End Function
End Class
Class ReallyDerived ' should not be shown as inherited by Base
Inherits Goo
End Class
</Document>
</Project>
</Workspace>)
Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=Base)" Category="CodeSchema_Class" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="Base" Icon="Microsoft.VisualStudio.Class.Internal" Label="Base"/>
<Node Id="(@1 Type=Goo)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo"/>
<Node Id="(@1 Type=Goo2)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo2" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo2"/>
</Nodes>
<Links>
<Link Source="(@1 Type=Goo)" Target="(@1 Type=Base)" Category="InheritsFrom"/>
<Link Source="(@1 Type=Goo2)" Target="(@1 Type=Base)" Category="InheritsFrom"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/VisualBasicAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
<WpfFact>
Public Async Function TestInheritedByInterfacesVisualBasic() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj">
<Document FilePath="Z:\Project.vb">
Imports System
Public Interface $$I
End Interface
Public Class C ' should appear as being derived from (implementing) I
Implements I
End Class
Public Class C2 ' should not appear as being derived from (implementing) I
Inherits C
End Class
Interface I2
Inherits I, IComparable
Sub M()
End Interface
Interface I3 ' should not be shown as inherited by I
Inherits I2
End Interface
</Document>
</Project>
</Workspace>)
Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=C)" Category="CodeSchema_Class" CodeSchemaProperty_IsPublic="True" CommonLabel="C" Icon="Microsoft.VisualStudio.Class.Public" Label="C"/>
<Node Id="(@1 Type=I)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsPublic="True" CommonLabel="I" Icon="Microsoft.VisualStudio.Interface.Public" Label="I"/>
<Node Id="(@1 Type=I2)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="I2" Icon="Microsoft.VisualStudio.Interface.Internal" Label="I2"/>
</Nodes>
<Links>
<Link Source="(@1 Type=C)" Target="(@1 Type=I)" Category="InheritsFrom"/>
<Link Source="(@1 Type=I2)" Target="(@1 Type=I)" Category="InheritsFrom"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/VisualBasicAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/CSharp/Portable/Symbols/PublicModel/AliasSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CSharp.Symbols.PublicModel
{
internal sealed class AliasSymbol : Symbol, IAliasSymbol
{
private readonly Symbols.AliasSymbol _underlying;
public AliasSymbol(Symbols.AliasSymbol underlying)
{
RoslynDebug.Assert(underlying is object);
_underlying = underlying;
}
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
INamespaceOrTypeSymbol IAliasSymbol.Target
{
get
{
return _underlying.Target.GetPublicSymbol();
}
}
#region ISymbol Members
protected override void Accept(SymbolVisitor visitor)
{
visitor.VisitAlias(this);
}
protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor)
where TResult : default
{
return visitor.VisitAlias(this);
}
#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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal sealed class AliasSymbol : Symbol, IAliasSymbol
{
private readonly Symbols.AliasSymbol _underlying;
public AliasSymbol(Symbols.AliasSymbol underlying)
{
RoslynDebug.Assert(underlying is object);
_underlying = underlying;
}
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
INamespaceOrTypeSymbol IAliasSymbol.Target
{
get
{
return _underlying.Target.GetPublicSymbol();
}
}
#region ISymbol Members
protected override void Accept(SymbolVisitor visitor)
{
visitor.VisitAlias(this);
}
protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor)
where TResult : default
{
return visitor.VisitAlias(this);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Features/Core/Portable/EditAndContinue/EditAndContinueErrorCode.cs | // Licensed to the .NET Foundation under one or more 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.EditAndContinue
{
internal enum EditAndContinueErrorCode
{
ErrorReadingFile = 1,
CannotApplyChangesUnexpectedError = 2,
// ChangesNotAppliedWhileRunning = 3, // obsolete
ChangesDisallowedWhileStoppedAtException = 4,
DocumentIsOutOfSyncWithDebuggee = 5,
UnableToReadSourceFileOrPdb = 6,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal enum EditAndContinueErrorCode
{
ErrorReadingFile = 1,
CannotApplyChangesUnexpectedError = 2,
// ChangesNotAppliedWhileRunning = 3, // obsolete
ChangesDisallowedWhileStoppedAtException = 4,
DocumentIsOutOfSyncWithDebuggee = 5,
UnableToReadSourceFileOrPdb = 6,
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/CSharp/Portable/Symbols/Source/SynthesizedAttributeData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Class to represent a synthesized attribute
/// </summary>
internal sealed class SynthesizedAttributeData : SourceAttributeData
{
internal SynthesizedAttributeData(MethodSymbol wellKnownMember, ImmutableArray<TypedConstant> arguments, ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments)
: base(
applicationNode: null,
attributeClass: wellKnownMember.ContainingType,
attributeConstructor: wellKnownMember,
constructorArguments: arguments,
constructorArgumentsSourceIndices: default,
namedArguments: namedArguments,
hasErrors: false,
isConditionallyOmitted: false)
{
Debug.Assert((object)wellKnownMember != null);
Debug.Assert(!arguments.IsDefault);
Debug.Assert(!namedArguments.IsDefault); // Frequently empty though.
}
internal SynthesizedAttributeData(SourceAttributeData original)
: base(
applicationNode: original.ApplicationSyntaxReference,
attributeClass: original.AttributeClass,
attributeConstructor: original.AttributeConstructor,
constructorArguments: original.CommonConstructorArguments,
constructorArgumentsSourceIndices: original.ConstructorArgumentsSourceIndices,
namedArguments: original.CommonNamedArguments,
hasErrors: original.HasErrors,
isConditionallyOmitted: original.IsConditionallyOmitted)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Class to represent a synthesized attribute
/// </summary>
internal sealed class SynthesizedAttributeData : SourceAttributeData
{
internal SynthesizedAttributeData(MethodSymbol wellKnownMember, ImmutableArray<TypedConstant> arguments, ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments)
: base(
applicationNode: null,
attributeClass: wellKnownMember.ContainingType,
attributeConstructor: wellKnownMember,
constructorArguments: arguments,
constructorArgumentsSourceIndices: default,
namedArguments: namedArguments,
hasErrors: false,
isConditionallyOmitted: false)
{
Debug.Assert((object)wellKnownMember != null);
Debug.Assert(!arguments.IsDefault);
Debug.Assert(!namedArguments.IsDefault); // Frequently empty though.
}
internal SynthesizedAttributeData(SourceAttributeData original)
: base(
applicationNode: original.ApplicationSyntaxReference,
attributeClass: original.AttributeClass,
attributeConstructor: original.AttributeConstructor,
constructorArguments: original.CommonConstructorArguments,
constructorArgumentsSourceIndices: original.ConstructorArgumentsSourceIndices,
namedArguments: original.CommonNamedArguments,
hasErrors: original.HasErrors,
isConditionallyOmitted: original.IsConditionallyOmitted)
{
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/VisualStudio/Core/Test/Snippets/TestExpansionClient.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.Runtime.InteropServices
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
Imports Microsoft.VisualStudio.TextManager.Interop
Imports MSXML
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Snippets
Friend Class TestExpansionSession
Implements IVsExpansionSession, IVsExpansionSessionInternal
Public snippetSpanInSurfaceBuffer As TextSpan
Public endSpanInSurfaceBuffer As TextSpan
Public Function GetSnippetSpan(<ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")> pts() As TextSpan) As Integer Implements IVsExpansionSession.GetSnippetSpan
pts(0) = snippetSpanInSurfaceBuffer
Return 0
End Function
Public Function SetEndSpan(<ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")> ts As TextSpan) As Integer Implements IVsExpansionSession.SetEndSpan
endSpanInSurfaceBuffer = ts
Return 0
End Function
Public Function GetEndSpan(<ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")> pts() As TextSpan) As Integer Implements IVsExpansionSession.GetEndSpan
pts(0) = endSpanInSurfaceBuffer
Return 0
End Function
Public Function GetSnippetNode(bstrNode As String, ByRef pNode As IntPtr) As Integer Implements IVsExpansionSessionInternal.GetSnippetNode
Return -1
End Function
Public Function EndCurrentExpansion(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> fLeaveCaret As Integer) As Integer Implements IVsExpansionSession.EndCurrentExpansion
Throw New NotImplementedException()
End Function
Public Function GetDeclarationNode(bstrNode As String, ByRef pNode As IXMLDOMNode) As Integer Implements IVsExpansionSession.GetDeclarationNode
Throw New NotImplementedException()
End Function
Public Function GetFieldSpan(bstrField As String, <ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")> ptsSpan() As TextSpan) As Integer Implements IVsExpansionSession.GetFieldSpan
Throw New NotImplementedException()
End Function
Public Function GetFieldValue(bstrFieldName As String, ByRef pbstrValue As String) As Integer Implements IVsExpansionSession.GetFieldValue
Throw New NotImplementedException()
End Function
Public Function GetHeaderNode(bstrNode As String, ByRef pNode As IXMLDOMNode) As Integer Implements IVsExpansionSession.GetHeaderNode
Throw New NotImplementedException()
End Function
Public Function GetSnippetNode(bstrNode As String, ByRef pNode As IXMLDOMNode) As Integer Implements IVsExpansionSession.GetSnippetNode
Throw New NotImplementedException()
End Function
Public Function GoToNextExpansionField(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> fCommitIfLast As Integer) As Integer Implements IVsExpansionSession.GoToNextExpansionField
Throw New NotImplementedException()
End Function
Public Function GoToPreviousExpansionField() As Integer Implements IVsExpansionSession.GoToPreviousExpansionField
Throw New NotImplementedException()
End Function
Public Function SetFieldDefault(bstrFieldName As String, bstrNewValue As String) As Integer Implements IVsExpansionSession.SetFieldDefault
Throw New NotImplementedException()
End Function
Public Sub Reserved1() Implements IVsExpansionSessionInternal.Reserved1
Throw New NotImplementedException()
End Sub
Public Sub Reserved2() Implements IVsExpansionSessionInternal.Reserved2
Throw New NotImplementedException()
End Sub
Public Sub Reserved3() Implements IVsExpansionSessionInternal.Reserved3
Throw New NotImplementedException()
End Sub
Public Sub Reserved4() Implements IVsExpansionSessionInternal.Reserved4
Throw New NotImplementedException()
End Sub
Public Sub Reserved5() Implements IVsExpansionSessionInternal.Reserved5
Throw New NotImplementedException()
End Sub
Public Sub Reserved6() Implements IVsExpansionSessionInternal.Reserved6
Throw New NotImplementedException()
End Sub
Public Sub Reserved7() Implements IVsExpansionSessionInternal.Reserved7
Throw New NotImplementedException()
End Sub
Public Sub Reserved8() Implements IVsExpansionSessionInternal.Reserved8
Throw New NotImplementedException()
End Sub
Public Sub Reserved9() Implements IVsExpansionSessionInternal.Reserved9
Throw New NotImplementedException()
End Sub
Public Sub Reserved10() Implements IVsExpansionSessionInternal.Reserved10
Throw New NotImplementedException()
End Sub
Public Sub Reserved11() Implements IVsExpansionSessionInternal.Reserved11
Throw New NotImplementedException()
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.Runtime.InteropServices
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
Imports Microsoft.VisualStudio.TextManager.Interop
Imports MSXML
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Snippets
Friend Class TestExpansionSession
Implements IVsExpansionSession, IVsExpansionSessionInternal
Public snippetSpanInSurfaceBuffer As TextSpan
Public endSpanInSurfaceBuffer As TextSpan
Public Function GetSnippetSpan(<ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")> pts() As TextSpan) As Integer Implements IVsExpansionSession.GetSnippetSpan
pts(0) = snippetSpanInSurfaceBuffer
Return 0
End Function
Public Function SetEndSpan(<ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")> ts As TextSpan) As Integer Implements IVsExpansionSession.SetEndSpan
endSpanInSurfaceBuffer = ts
Return 0
End Function
Public Function GetEndSpan(<ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")> pts() As TextSpan) As Integer Implements IVsExpansionSession.GetEndSpan
pts(0) = endSpanInSurfaceBuffer
Return 0
End Function
Public Function GetSnippetNode(bstrNode As String, ByRef pNode As IntPtr) As Integer Implements IVsExpansionSessionInternal.GetSnippetNode
Return -1
End Function
Public Function EndCurrentExpansion(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> fLeaveCaret As Integer) As Integer Implements IVsExpansionSession.EndCurrentExpansion
Throw New NotImplementedException()
End Function
Public Function GetDeclarationNode(bstrNode As String, ByRef pNode As IXMLDOMNode) As Integer Implements IVsExpansionSession.GetDeclarationNode
Throw New NotImplementedException()
End Function
Public Function GetFieldSpan(bstrField As String, <ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")> ptsSpan() As TextSpan) As Integer Implements IVsExpansionSession.GetFieldSpan
Throw New NotImplementedException()
End Function
Public Function GetFieldValue(bstrFieldName As String, ByRef pbstrValue As String) As Integer Implements IVsExpansionSession.GetFieldValue
Throw New NotImplementedException()
End Function
Public Function GetHeaderNode(bstrNode As String, ByRef pNode As IXMLDOMNode) As Integer Implements IVsExpansionSession.GetHeaderNode
Throw New NotImplementedException()
End Function
Public Function GetSnippetNode(bstrNode As String, ByRef pNode As IXMLDOMNode) As Integer Implements IVsExpansionSession.GetSnippetNode
Throw New NotImplementedException()
End Function
Public Function GoToNextExpansionField(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> fCommitIfLast As Integer) As Integer Implements IVsExpansionSession.GoToNextExpansionField
Throw New NotImplementedException()
End Function
Public Function GoToPreviousExpansionField() As Integer Implements IVsExpansionSession.GoToPreviousExpansionField
Throw New NotImplementedException()
End Function
Public Function SetFieldDefault(bstrFieldName As String, bstrNewValue As String) As Integer Implements IVsExpansionSession.SetFieldDefault
Throw New NotImplementedException()
End Function
Public Sub Reserved1() Implements IVsExpansionSessionInternal.Reserved1
Throw New NotImplementedException()
End Sub
Public Sub Reserved2() Implements IVsExpansionSessionInternal.Reserved2
Throw New NotImplementedException()
End Sub
Public Sub Reserved3() Implements IVsExpansionSessionInternal.Reserved3
Throw New NotImplementedException()
End Sub
Public Sub Reserved4() Implements IVsExpansionSessionInternal.Reserved4
Throw New NotImplementedException()
End Sub
Public Sub Reserved5() Implements IVsExpansionSessionInternal.Reserved5
Throw New NotImplementedException()
End Sub
Public Sub Reserved6() Implements IVsExpansionSessionInternal.Reserved6
Throw New NotImplementedException()
End Sub
Public Sub Reserved7() Implements IVsExpansionSessionInternal.Reserved7
Throw New NotImplementedException()
End Sub
Public Sub Reserved8() Implements IVsExpansionSessionInternal.Reserved8
Throw New NotImplementedException()
End Sub
Public Sub Reserved9() Implements IVsExpansionSessionInternal.Reserved9
Throw New NotImplementedException()
End Sub
Public Sub Reserved10() Implements IVsExpansionSessionInternal.Reserved10
Throw New NotImplementedException()
End Sub
Public Sub Reserved11() Implements IVsExpansionSessionInternal.Reserved11
Throw New NotImplementedException()
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./docs/compilers/CSharp/Compiler Breaking Changes - post DotNet 5.md | ## This document lists known breaking changes in Roslyn after .NET 5.
1. https://github.com/dotnet/roslyn/issues/46044 In C# 9.0 (Visual Studio 16.9), a warning is reported when assigning `default` to, or when casting a possibly `null` value to a type parameter type that is not constrained to value types or reference types. To avoid the warning, the type can be annotated with `?`.
```C#
static void F1<T>(object? obj)
{
T t1 = default; // warning CS8600: Converting possible null value to non-nullable type
t1 = (T)obj; // warning CS8600: Converting possible null value to non-nullable type
T? t2 = default; // ok
t2 = (T?)obj; // ok
}
```
2. https://github.com/dotnet/roslyn/pull/50755 In .NET 5.0.200 (Visual Studio 16.9), if there is a common type between the two branches of a conditional expression, that type is the type of the conditional expression.
This is a breaking change from 5.0.103 (Visual Studio 16.8) which due to a bug incorrectly used the target type of the conditional expression as the type even if there was a common type between the two branches.
This latest change aligns the compiler behavior with the C# specification and with versions of the compiler before .NET 5.0.
```C#
static short F1(bool b)
{
// 16.7, 16.9 : CS0266: Cannot implicitly convert type 'int' to 'short'
// 16.8 : ok
// 16.8 -langversion:8 : CS8400: Feature 'target-typed conditional expression' is not available in C# 8.0
return b ? 1 : 2;
}
static object F2(bool b, short? a)
{
// 16.7, 16.9 : int
// 16.8 : short
// 16.8 -langversion:8 : CS8400: Feature 'target-typed conditional expression' is not available in C# 8.0
return a ?? (b ? 1 : 2);
}
```
3. https://github.com/dotnet/roslyn/issues/52630 In C# 9 (.NET 5, Visual Studio 16.9), it is possible that a record uses a hidden member from a base type as a positional member. In Visual Studio 16.10, this is now an error:
```csharp
record Base
{
public int I { get; init; }
}
record Derived(int I) // The positional member 'Base.I' found corresponding to this parameter is hidden.
: Base
{
public int I() { return 0; }
}
```
4. In C# 10, method groups are implicitly convertible to `System.Delegate`, and lambda expressions are implicitly convertible to `System.Delegate` and `System.Linq.Expressions.Expression`.
This is a breaking change to overload resolution if there exists an overload with a `System.Delegate` or `System.Linq.Expressions.Expression` parameter that is applicable and the closest applicable overload with a strongly-typed delegate parameter is in an enclosing namespace.
```C#
class C
{
static void Main()
{
var c = new C();
c.M(Main); // C#9: E.M(), C#10: C.M()
c.M(() => { }); // C#9: E.M(), C#10: C.M()
}
void M(System.Delegate d) { }
}
static class E
{
public static void M(this object x, System.Action y) { }
}
``` | ## This document lists known breaking changes in Roslyn after .NET 5.
1. https://github.com/dotnet/roslyn/issues/46044 In C# 9.0 (Visual Studio 16.9), a warning is reported when assigning `default` to, or when casting a possibly `null` value to a type parameter type that is not constrained to value types or reference types. To avoid the warning, the type can be annotated with `?`.
```C#
static void F1<T>(object? obj)
{
T t1 = default; // warning CS8600: Converting possible null value to non-nullable type
t1 = (T)obj; // warning CS8600: Converting possible null value to non-nullable type
T? t2 = default; // ok
t2 = (T?)obj; // ok
}
```
2. https://github.com/dotnet/roslyn/pull/50755 In .NET 5.0.200 (Visual Studio 16.9), if there is a common type between the two branches of a conditional expression, that type is the type of the conditional expression.
This is a breaking change from 5.0.103 (Visual Studio 16.8) which due to a bug incorrectly used the target type of the conditional expression as the type even if there was a common type between the two branches.
This latest change aligns the compiler behavior with the C# specification and with versions of the compiler before .NET 5.0.
```C#
static short F1(bool b)
{
// 16.7, 16.9 : CS0266: Cannot implicitly convert type 'int' to 'short'
// 16.8 : ok
// 16.8 -langversion:8 : CS8400: Feature 'target-typed conditional expression' is not available in C# 8.0
return b ? 1 : 2;
}
static object F2(bool b, short? a)
{
// 16.7, 16.9 : int
// 16.8 : short
// 16.8 -langversion:8 : CS8400: Feature 'target-typed conditional expression' is not available in C# 8.0
return a ?? (b ? 1 : 2);
}
```
3. https://github.com/dotnet/roslyn/issues/52630 In C# 9 (.NET 5, Visual Studio 16.9), it is possible that a record uses a hidden member from a base type as a positional member. In Visual Studio 16.10, this is now an error:
```csharp
record Base
{
public int I { get; init; }
}
record Derived(int I) // The positional member 'Base.I' found corresponding to this parameter is hidden.
: Base
{
public int I() { return 0; }
}
```
4. In C# 10, method groups are implicitly convertible to `System.Delegate`, and lambda expressions are implicitly convertible to `System.Delegate` and `System.Linq.Expressions.Expression`.
This is a breaking change to overload resolution if there exists an overload with a `System.Delegate` or `System.Linq.Expressions.Expression` parameter that is applicable and the closest applicable overload with a strongly-typed delegate parameter is in an enclosing namespace.
```C#
class C
{
static void Main()
{
var c = new C();
c.M(Main); // C#9: E.M(), C#10: C.M()
c.M(() => { }); // C#9: E.M(), C#10: C.M()
}
void M(System.Delegate d) { }
}
static class E
{
public static void M(this object x, System.Action y) { }
}
``` | -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/Test/Resources/Core/NetFX/ValueTuple/ValueTuple.cs | // Licensed to the .NET Foundation under one or more 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 System.Numerics.Hashing
{
internal static class HashHelpers
{
public static readonly int RandomSeed = new Random().Next(Int32.MinValue, Int32.MaxValue);
public static int Combine(int h1, int h2)
{
// RyuJIT optimizes this to use the ROL instruction
// Related GitHub pull request: dotnet/coreclr#1830
uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
return ((int)rol5 + h1) ^ h2;
}
}
}
namespace System.Runtime.CompilerServices
{
/// <summary>
/// This interface is required for types that want to be indexed into by dynamic patterns.
/// </summary>
public interface ITuple
{
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int Length { get; }
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object this[int index] { get; }
}
}
namespace System
{
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using HashHelpers = System.Numerics.Hashing.HashHelpers;
/// <summary>
/// Helper so we can call some tuple methods recursively without knowing the underlying types.
/// </summary>
internal interface IValueTupleInternal : ITuple
{
int GetHashCode(IEqualityComparer comparer);
string ToStringEnd();
}
/// <summary>
/// The ValueTuple types (from arity 0 to 8) comprise the runtime implementation that underlies tuples in C# and struct tuples in F#.
/// Aside from created via language syntax, they are most easily created via the ValueTuple.Create factory methods.
/// The System.ValueTuple types differ from the System.Tuple types in that:
/// - they are structs rather than classes,
/// - they are mutable rather than readonly, and
/// - their members (such as Item1, Item2, etc) are fields rather than properties.
/// </summary>
[Serializable]
public struct ValueTuple
: IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, IValueTupleInternal, ITuple
{
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="ValueTuple"/>.</returns>
public override bool Equals(object obj)
{
return obj is ValueTuple;
}
/// <summary>Returns a value indicating whether this instance is equal to a specified value.</summary>
/// <param name="other">An instance to compare to this instance.</param>
/// <returns>true if <paramref name="other"/> has the same value as this instance; otherwise, false.</returns>
public bool Equals(ValueTuple other)
{
return true;
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
return other is ValueTuple;
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple))
{
throw new ArgumentException();
}
return 0;
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple other)
{
return 0;
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple))
{
throw new ArgumentException();
}
return 0;
}
/// <summary>Returns the hash code for this instance.</summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return 0;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return 0;
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return 0;
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>()</c>.
/// </remarks>
public override string ToString()
{
return "()";
}
string IValueTupleInternal.ToStringEnd()
{
return ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 0;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
throw new IndexOutOfRangeException();
}
}
/// <summary>Creates a new struct 0-tuple.</summary>
/// <returns>A 0-tuple.</returns>
public static ValueTuple Create() =>
new ValueTuple();
/// <summary>Creates a new struct 1-tuple, or singleton.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <returns>A 1-tuple (singleton) whose value is (item1).</returns>
public static ValueTuple<T1> Create<T1>(T1 item1) =>
new ValueTuple<T1>(item1);
/// <summary>Creates a new struct 2-tuple, or pair.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <returns>A 2-tuple (pair) whose value is (item1, item2).</returns>
public static ValueTuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) =>
new ValueTuple<T1, T2>(item1, item2);
/// <summary>Creates a new struct 3-tuple, or triple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <returns>A 3-tuple (triple) whose value is (item1, item2, item3).</returns>
public static ValueTuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) =>
new ValueTuple<T1, T2, T3>(item1, item2, item3);
/// <summary>Creates a new struct 4-tuple, or quadruple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <returns>A 4-tuple (quadruple) whose value is (item1, item2, item3, item4).</returns>
public static ValueTuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) =>
new ValueTuple<T1, T2, T3, T4>(item1, item2, item3, item4);
/// <summary>Creates a new struct 5-tuple, or quintuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <returns>A 5-tuple (quintuple) whose value is (item1, item2, item3, item4, item5).</returns>
public static ValueTuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) =>
new ValueTuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5);
/// <summary>Creates a new struct 6-tuple, or sextuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <param name="item6">The value of the sixth component of the tuple.</param>
/// <returns>A 6-tuple (sextuple) whose value is (item1, item2, item3, item4, item5, item6).</returns>
public static ValueTuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) =>
new ValueTuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6);
/// <summary>Creates a new struct 7-tuple, or septuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
/// <typeparam name="T7">The type of the seventh component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <param name="item6">The value of the sixth component of the tuple.</param>
/// <param name="item7">The value of the seventh component of the tuple.</param>
/// <returns>A 7-tuple (septuple) whose value is (item1, item2, item3, item4, item5, item6, item7).</returns>
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) =>
new ValueTuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7);
/// <summary>Creates a new struct 8-tuple, or octuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
/// <typeparam name="T7">The type of the seventh component of the tuple.</typeparam>
/// <typeparam name="T8">The type of the eighth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <param name="item6">The value of the sixth component of the tuple.</param>
/// <param name="item7">The value of the seventh component of the tuple.</param>
/// <param name="item8">The value of the eighth component of the tuple.</param>
/// <returns>An 8-tuple (octuple) whose value is (item1, item2, item3, item4, item5, item6, item7, item8).</returns>
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) =>
new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>(item1, item2, item3, item4, item5, item6, item7, ValueTuple.Create(item8));
internal static int CombineHashCodes(int h1, int h2)
{
return HashHelpers.Combine(HashHelpers.Combine(HashHelpers.RandomSeed, h1), h2);
}
internal static int CombineHashCodes(int h1, int h2, int h3)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2), h3);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3), h4);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4), h5);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5), h6);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6), h7);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6, h7), h8);
}
}
/// <summary>Represents a 1-tuple, or singleton, as a value type.</summary>
/// <typeparam name="T1">The type of the tuple's only component.</typeparam>
[Serializable]
public struct ValueTuple<T1>
: IEquatable<ValueTuple<T1>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
public ValueTuple(T1 item1)
{
Item1 = item1;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1> && Equals((ValueTuple<T1>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its field
/// is equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1>)) return false;
var objTuple = (ValueTuple<T1>)other;
return comparer.Equals(Item1, objTuple.Item1);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1>)other;
return Comparer<T1>.Default.Compare(Item1, objTuple.Item1);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1> other)
{
return Comparer<T1>.Default.Compare(Item1, other.Item1);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1>)other;
return comparer.Compare(Item1, objTuple.Item1);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return Item1?.GetHashCode() ?? 0;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return comparer.GetHashCode(Item1);
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return comparer.GetHashCode(Item1);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1)</c>,
/// where <c>Item1</c> represents the value of <see cref="Item1"/>. If the field is <see langword="null"/>,
/// it is represented as <see cref="string.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
if (index != 0)
{
throw new IndexOutOfRangeException();
}
return Item1;
}
}
}
/// <summary>
/// Represents a 2-tuple, or pair, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2>
: IEquatable<ValueTuple<T1, T2>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2}"/> instance's first component.
/// </summary>
public T2 Item2;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
public ValueTuple(T1 item1, T2 item2)
{
Item1 = item1;
Item2 = item2;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
///
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2> && Equals((ValueTuple<T1, T2>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified <see cref="ValueTuple{T1, T2}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified object based on a specified comparison method.
/// </summary>
/// <param name="other">The object to compare with this instance.</param>
/// <param name="comparer">An object that defines the method to use to evaluate whether the two objects are equal.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
///
/// <remarks>
/// This member is an explicit interface member implementation. It can be used only when the
/// <see cref="ValueTuple{T1, T2}"/> instance is cast to an <see cref="IStructuralEquatable"/> interface.
///
/// The <see cref="IEqualityComparer.Equals"/> implementation is called only if <c>other</c> is not <see langword="null"/>,
/// and if it can be successfully cast (in C#) or converted (in Visual Basic) to a <see cref="ValueTuple{T1, T2}"/>
/// whose components are of the same types as those of the current instance. The IStructuralEquatable.Equals(Object, IEqualityComparer) method
/// first passes the <see cref="Item1"/> values of the <see cref="ValueTuple{T1, T2}"/> objects to be compared to the
/// <see cref="IEqualityComparer.Equals"/> implementation. If this method call returns <see langword="true"/>, the method is
/// called again and passed the <see cref="Item2"/> values of the two <see cref="ValueTuple{T1, T2}"/> instances.
/// </remarks>
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2>)) return false;
var objTuple = (ValueTuple<T1, T2>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
return Comparer<T2>.Default.Compare(Item2, other.Item2);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
return comparer.Compare(Item2, objTuple.Item2);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2)</c>,
/// where <c>Item1</c> and <c>Item2</c> represent the values of the <see cref="Item1"/>
/// and <see cref="Item2"/> fields. If either field value is <see langword="null"/>,
/// it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 2;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 3-tuple, or triple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3>
: IEquatable<ValueTuple<T1, T2, T3>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3> && Equals((ValueTuple<T1, T2, T3>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3>)) return false;
var objTuple = (ValueTuple<T1, T2, T3>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
return Comparer<T3>.Default.Compare(Item3, other.Item3);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
return comparer.Compare(Item3, objTuple.Item3);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 3;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 4-tuple, or quadruple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4>
: IEquatable<ValueTuple<T1, T2, T3, T4>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4> && Equals((ValueTuple<T1, T2, T3, T4>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
return Comparer<T4>.Default.Compare(Item4, other.Item4);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
return comparer.Compare(Item4, objTuple.Item4);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 4;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 5-tuple, or quintuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5> && Equals((ValueTuple<T1, T2, T3, T4, T5>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
return Comparer<T5>.Default.Compare(Item5, other.Item5);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
return comparer.Compare(Item5, objTuple.Item5);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 5;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 6-tuple, or sixtuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
/// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's sixth component.
/// </summary>
public T6 Item6;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
/// <param name="item6">The value of the tuple's sixth component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5, T6> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
&& EqualityComparer<T6>.Default.Equals(Item6, other.Item6);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5)
&& comparer.Equals(Item6, objTuple.Item6);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
c = Comparer<T5>.Default.Compare(Item5, other.Item5);
if (c != 0) return c;
return Comparer<T6>.Default.Compare(Item6, other.Item6);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
c = comparer.Compare(Item5, objTuple.Item5);
if (c != 0) return c;
return comparer.Compare(Item6, objTuple.Item6);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5),
comparer.GetHashCode(Item6));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 6;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 7-tuple, or sentuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
/// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
/// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's sixth component.
/// </summary>
public T6 Item6;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's seventh component.
/// </summary>
public T7 Item7;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
/// <param name="item6">The value of the tuple's sixth component.</param>
/// <param name="item7">The value of the tuple's seventh component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
Item7 = item7;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
&& EqualityComparer<T6>.Default.Equals(Item6, other.Item6)
&& EqualityComparer<T7>.Default.Equals(Item7, other.Item7);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5)
&& comparer.Equals(Item6, objTuple.Item6)
&& comparer.Equals(Item7, objTuple.Item7);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
c = Comparer<T5>.Default.Compare(Item5, other.Item5);
if (c != 0) return c;
c = Comparer<T6>.Default.Compare(Item6, other.Item6);
if (c != 0) return c;
return Comparer<T7>.Default.Compare(Item7, other.Item7);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
c = comparer.Compare(Item5, objTuple.Item5);
if (c != 0) return c;
c = comparer.Compare(Item6, objTuple.Item6);
if (c != 0) return c;
return comparer.Compare(Item7, objTuple.Item7);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5),
comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6, Item7)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 7;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
case 6:
return Item7;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents an 8-tuple, or octuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
/// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
/// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
/// <typeparam name="TRest">The type of the tuple's eighth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IValueTupleInternal, ITuple
where TRest : struct
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's sixth component.
/// </summary>
public T6 Item6;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's seventh component.
/// </summary>
public T7 Item7;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's eighth component.
/// </summary>
public TRest Rest;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
/// <param name="item6">The value of the tuple's sixth component.</param>
/// <param name="item7">The value of the tuple's seventh component.</param>
/// <param name="rest">The value of the tuple's eight component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest)
{
if (!(rest is IValueTupleInternal))
{
throw new ArgumentException();
}
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
Item7 = item7;
Rest = rest;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
&& EqualityComparer<T6>.Default.Equals(Item6, other.Item6)
&& EqualityComparer<T7>.Default.Equals(Item7, other.Item7)
&& EqualityComparer<TRest>.Default.Equals(Rest, other.Rest);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5)
&& comparer.Equals(Item6, objTuple.Item6)
&& comparer.Equals(Item7, objTuple.Item7)
&& comparer.Equals(Rest, objTuple.Rest);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
c = Comparer<T5>.Default.Compare(Item5, other.Item5);
if (c != 0) return c;
c = Comparer<T6>.Default.Compare(Item6, other.Item6);
if (c != 0) return c;
c = Comparer<T7>.Default.Compare(Item7, other.Item7);
if (c != 0) return c;
return Comparer<TRest>.Default.Compare(Rest, other.Rest);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
c = comparer.Compare(Item5, objTuple.Item5);
if (c != 0) return c;
c = comparer.Compare(Item6, objTuple.Item6);
if (c != 0) return c;
c = comparer.Compare(Item7, objTuple.Item7);
if (c != 0) return c;
return comparer.Compare(Rest, objTuple.Rest);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
// We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0);
}
int size = rest.Length;
if (size >= 8) { return rest.GetHashCode(); }
// In this case, the rest member has less than 8 elements so we need to combine some our elements with the elements in rest
int k = 8 - size;
switch (k)
{
case 1:
return ValueTuple.CombineHashCodes(Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 2:
return ValueTuple.CombineHashCodes(Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 3:
return ValueTuple.CombineHashCodes(Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 4:
return ValueTuple.CombineHashCodes(Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 5:
return ValueTuple.CombineHashCodes(Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 6:
return ValueTuple.CombineHashCodes(Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 7:
case 8:
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
}
Contract.Assert(false, "Missed all cases for computing ValueTuple hash code");
return -1;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
// We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7));
}
int size = rest.Length;
if (size >= 8) { return rest.GetHashCode(comparer); }
// In this case, the rest member has less than 8 elements so we need to combine some our elements with the elements in rest
int k = 8 - size;
switch (k)
{
case 1:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 2:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 3:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7),
rest.GetHashCode(comparer));
case 4:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 5:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5),
comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 6:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7),
rest.GetHashCode(comparer));
case 7:
case 8:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
}
Contract.Assert(false, "Missed all cases for computing ValueTuple hash code");
return -1;
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6, Item7, Rest)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")";
}
else
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd();
}
}
string IValueTupleInternal.ToStringEnd()
{
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")";
}
else
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd();
}
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length
{
get
{
IValueTupleInternal rest = Rest as IValueTupleInternal;
return rest == null ? 8 : 7 + rest.Length;
}
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
case 6:
return Item7;
}
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
if (index == 7)
{
return Rest;
}
throw new IndexOutOfRangeException();
}
return rest[index - 7];
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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 System.Numerics.Hashing
{
internal static class HashHelpers
{
public static readonly int RandomSeed = new Random().Next(Int32.MinValue, Int32.MaxValue);
public static int Combine(int h1, int h2)
{
// RyuJIT optimizes this to use the ROL instruction
// Related GitHub pull request: dotnet/coreclr#1830
uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
return ((int)rol5 + h1) ^ h2;
}
}
}
namespace System.Runtime.CompilerServices
{
/// <summary>
/// This interface is required for types that want to be indexed into by dynamic patterns.
/// </summary>
public interface ITuple
{
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int Length { get; }
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object this[int index] { get; }
}
}
namespace System
{
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using HashHelpers = System.Numerics.Hashing.HashHelpers;
/// <summary>
/// Helper so we can call some tuple methods recursively without knowing the underlying types.
/// </summary>
internal interface IValueTupleInternal : ITuple
{
int GetHashCode(IEqualityComparer comparer);
string ToStringEnd();
}
/// <summary>
/// The ValueTuple types (from arity 0 to 8) comprise the runtime implementation that underlies tuples in C# and struct tuples in F#.
/// Aside from created via language syntax, they are most easily created via the ValueTuple.Create factory methods.
/// The System.ValueTuple types differ from the System.Tuple types in that:
/// - they are structs rather than classes,
/// - they are mutable rather than readonly, and
/// - their members (such as Item1, Item2, etc) are fields rather than properties.
/// </summary>
[Serializable]
public struct ValueTuple
: IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, IValueTupleInternal, ITuple
{
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="ValueTuple"/>.</returns>
public override bool Equals(object obj)
{
return obj is ValueTuple;
}
/// <summary>Returns a value indicating whether this instance is equal to a specified value.</summary>
/// <param name="other">An instance to compare to this instance.</param>
/// <returns>true if <paramref name="other"/> has the same value as this instance; otherwise, false.</returns>
public bool Equals(ValueTuple other)
{
return true;
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
return other is ValueTuple;
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple))
{
throw new ArgumentException();
}
return 0;
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple other)
{
return 0;
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple))
{
throw new ArgumentException();
}
return 0;
}
/// <summary>Returns the hash code for this instance.</summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return 0;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return 0;
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return 0;
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>()</c>.
/// </remarks>
public override string ToString()
{
return "()";
}
string IValueTupleInternal.ToStringEnd()
{
return ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 0;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
throw new IndexOutOfRangeException();
}
}
/// <summary>Creates a new struct 0-tuple.</summary>
/// <returns>A 0-tuple.</returns>
public static ValueTuple Create() =>
new ValueTuple();
/// <summary>Creates a new struct 1-tuple, or singleton.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <returns>A 1-tuple (singleton) whose value is (item1).</returns>
public static ValueTuple<T1> Create<T1>(T1 item1) =>
new ValueTuple<T1>(item1);
/// <summary>Creates a new struct 2-tuple, or pair.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <returns>A 2-tuple (pair) whose value is (item1, item2).</returns>
public static ValueTuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) =>
new ValueTuple<T1, T2>(item1, item2);
/// <summary>Creates a new struct 3-tuple, or triple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <returns>A 3-tuple (triple) whose value is (item1, item2, item3).</returns>
public static ValueTuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) =>
new ValueTuple<T1, T2, T3>(item1, item2, item3);
/// <summary>Creates a new struct 4-tuple, or quadruple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <returns>A 4-tuple (quadruple) whose value is (item1, item2, item3, item4).</returns>
public static ValueTuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) =>
new ValueTuple<T1, T2, T3, T4>(item1, item2, item3, item4);
/// <summary>Creates a new struct 5-tuple, or quintuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <returns>A 5-tuple (quintuple) whose value is (item1, item2, item3, item4, item5).</returns>
public static ValueTuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) =>
new ValueTuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5);
/// <summary>Creates a new struct 6-tuple, or sextuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <param name="item6">The value of the sixth component of the tuple.</param>
/// <returns>A 6-tuple (sextuple) whose value is (item1, item2, item3, item4, item5, item6).</returns>
public static ValueTuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) =>
new ValueTuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6);
/// <summary>Creates a new struct 7-tuple, or septuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
/// <typeparam name="T7">The type of the seventh component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <param name="item6">The value of the sixth component of the tuple.</param>
/// <param name="item7">The value of the seventh component of the tuple.</param>
/// <returns>A 7-tuple (septuple) whose value is (item1, item2, item3, item4, item5, item6, item7).</returns>
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) =>
new ValueTuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7);
/// <summary>Creates a new struct 8-tuple, or octuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
/// <typeparam name="T7">The type of the seventh component of the tuple.</typeparam>
/// <typeparam name="T8">The type of the eighth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <param name="item6">The value of the sixth component of the tuple.</param>
/// <param name="item7">The value of the seventh component of the tuple.</param>
/// <param name="item8">The value of the eighth component of the tuple.</param>
/// <returns>An 8-tuple (octuple) whose value is (item1, item2, item3, item4, item5, item6, item7, item8).</returns>
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) =>
new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>(item1, item2, item3, item4, item5, item6, item7, ValueTuple.Create(item8));
internal static int CombineHashCodes(int h1, int h2)
{
return HashHelpers.Combine(HashHelpers.Combine(HashHelpers.RandomSeed, h1), h2);
}
internal static int CombineHashCodes(int h1, int h2, int h3)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2), h3);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3), h4);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4), h5);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5), h6);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6), h7);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6, h7), h8);
}
}
/// <summary>Represents a 1-tuple, or singleton, as a value type.</summary>
/// <typeparam name="T1">The type of the tuple's only component.</typeparam>
[Serializable]
public struct ValueTuple<T1>
: IEquatable<ValueTuple<T1>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
public ValueTuple(T1 item1)
{
Item1 = item1;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1> && Equals((ValueTuple<T1>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its field
/// is equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1>)) return false;
var objTuple = (ValueTuple<T1>)other;
return comparer.Equals(Item1, objTuple.Item1);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1>)other;
return Comparer<T1>.Default.Compare(Item1, objTuple.Item1);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1> other)
{
return Comparer<T1>.Default.Compare(Item1, other.Item1);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1>)other;
return comparer.Compare(Item1, objTuple.Item1);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return Item1?.GetHashCode() ?? 0;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return comparer.GetHashCode(Item1);
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return comparer.GetHashCode(Item1);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1)</c>,
/// where <c>Item1</c> represents the value of <see cref="Item1"/>. If the field is <see langword="null"/>,
/// it is represented as <see cref="string.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
if (index != 0)
{
throw new IndexOutOfRangeException();
}
return Item1;
}
}
}
/// <summary>
/// Represents a 2-tuple, or pair, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2>
: IEquatable<ValueTuple<T1, T2>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2}"/> instance's first component.
/// </summary>
public T2 Item2;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
public ValueTuple(T1 item1, T2 item2)
{
Item1 = item1;
Item2 = item2;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
///
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2> && Equals((ValueTuple<T1, T2>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified <see cref="ValueTuple{T1, T2}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified object based on a specified comparison method.
/// </summary>
/// <param name="other">The object to compare with this instance.</param>
/// <param name="comparer">An object that defines the method to use to evaluate whether the two objects are equal.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
///
/// <remarks>
/// This member is an explicit interface member implementation. It can be used only when the
/// <see cref="ValueTuple{T1, T2}"/> instance is cast to an <see cref="IStructuralEquatable"/> interface.
///
/// The <see cref="IEqualityComparer.Equals"/> implementation is called only if <c>other</c> is not <see langword="null"/>,
/// and if it can be successfully cast (in C#) or converted (in Visual Basic) to a <see cref="ValueTuple{T1, T2}"/>
/// whose components are of the same types as those of the current instance. The IStructuralEquatable.Equals(Object, IEqualityComparer) method
/// first passes the <see cref="Item1"/> values of the <see cref="ValueTuple{T1, T2}"/> objects to be compared to the
/// <see cref="IEqualityComparer.Equals"/> implementation. If this method call returns <see langword="true"/>, the method is
/// called again and passed the <see cref="Item2"/> values of the two <see cref="ValueTuple{T1, T2}"/> instances.
/// </remarks>
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2>)) return false;
var objTuple = (ValueTuple<T1, T2>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
return Comparer<T2>.Default.Compare(Item2, other.Item2);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
return comparer.Compare(Item2, objTuple.Item2);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2)</c>,
/// where <c>Item1</c> and <c>Item2</c> represent the values of the <see cref="Item1"/>
/// and <see cref="Item2"/> fields. If either field value is <see langword="null"/>,
/// it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 2;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 3-tuple, or triple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3>
: IEquatable<ValueTuple<T1, T2, T3>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3> && Equals((ValueTuple<T1, T2, T3>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3>)) return false;
var objTuple = (ValueTuple<T1, T2, T3>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
return Comparer<T3>.Default.Compare(Item3, other.Item3);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
return comparer.Compare(Item3, objTuple.Item3);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 3;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 4-tuple, or quadruple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4>
: IEquatable<ValueTuple<T1, T2, T3, T4>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4> && Equals((ValueTuple<T1, T2, T3, T4>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
return Comparer<T4>.Default.Compare(Item4, other.Item4);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
return comparer.Compare(Item4, objTuple.Item4);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 4;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 5-tuple, or quintuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5> && Equals((ValueTuple<T1, T2, T3, T4, T5>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
return Comparer<T5>.Default.Compare(Item5, other.Item5);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
return comparer.Compare(Item5, objTuple.Item5);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 5;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 6-tuple, or sixtuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
/// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's sixth component.
/// </summary>
public T6 Item6;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
/// <param name="item6">The value of the tuple's sixth component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5, T6> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
&& EqualityComparer<T6>.Default.Equals(Item6, other.Item6);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5)
&& comparer.Equals(Item6, objTuple.Item6);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
c = Comparer<T5>.Default.Compare(Item5, other.Item5);
if (c != 0) return c;
return Comparer<T6>.Default.Compare(Item6, other.Item6);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
c = comparer.Compare(Item5, objTuple.Item5);
if (c != 0) return c;
return comparer.Compare(Item6, objTuple.Item6);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5),
comparer.GetHashCode(Item6));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 6;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 7-tuple, or sentuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
/// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
/// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's sixth component.
/// </summary>
public T6 Item6;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's seventh component.
/// </summary>
public T7 Item7;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
/// <param name="item6">The value of the tuple's sixth component.</param>
/// <param name="item7">The value of the tuple's seventh component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
Item7 = item7;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
&& EqualityComparer<T6>.Default.Equals(Item6, other.Item6)
&& EqualityComparer<T7>.Default.Equals(Item7, other.Item7);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5)
&& comparer.Equals(Item6, objTuple.Item6)
&& comparer.Equals(Item7, objTuple.Item7);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
c = Comparer<T5>.Default.Compare(Item5, other.Item5);
if (c != 0) return c;
c = Comparer<T6>.Default.Compare(Item6, other.Item6);
if (c != 0) return c;
return Comparer<T7>.Default.Compare(Item7, other.Item7);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
c = comparer.Compare(Item5, objTuple.Item5);
if (c != 0) return c;
c = comparer.Compare(Item6, objTuple.Item6);
if (c != 0) return c;
return comparer.Compare(Item7, objTuple.Item7);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5),
comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6, Item7)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 7;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
case 6:
return Item7;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents an 8-tuple, or octuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
/// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
/// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
/// <typeparam name="TRest">The type of the tuple's eighth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IValueTupleInternal, ITuple
where TRest : struct
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's sixth component.
/// </summary>
public T6 Item6;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's seventh component.
/// </summary>
public T7 Item7;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's eighth component.
/// </summary>
public TRest Rest;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
/// <param name="item6">The value of the tuple's sixth component.</param>
/// <param name="item7">The value of the tuple's seventh component.</param>
/// <param name="rest">The value of the tuple's eight component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest)
{
if (!(rest is IValueTupleInternal))
{
throw new ArgumentException();
}
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
Item7 = item7;
Rest = rest;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
&& EqualityComparer<T6>.Default.Equals(Item6, other.Item6)
&& EqualityComparer<T7>.Default.Equals(Item7, other.Item7)
&& EqualityComparer<TRest>.Default.Equals(Rest, other.Rest);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5)
&& comparer.Equals(Item6, objTuple.Item6)
&& comparer.Equals(Item7, objTuple.Item7)
&& comparer.Equals(Rest, objTuple.Rest);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
c = Comparer<T5>.Default.Compare(Item5, other.Item5);
if (c != 0) return c;
c = Comparer<T6>.Default.Compare(Item6, other.Item6);
if (c != 0) return c;
c = Comparer<T7>.Default.Compare(Item7, other.Item7);
if (c != 0) return c;
return Comparer<TRest>.Default.Compare(Rest, other.Rest);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
c = comparer.Compare(Item5, objTuple.Item5);
if (c != 0) return c;
c = comparer.Compare(Item6, objTuple.Item6);
if (c != 0) return c;
c = comparer.Compare(Item7, objTuple.Item7);
if (c != 0) return c;
return comparer.Compare(Rest, objTuple.Rest);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
// We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0);
}
int size = rest.Length;
if (size >= 8) { return rest.GetHashCode(); }
// In this case, the rest member has less than 8 elements so we need to combine some our elements with the elements in rest
int k = 8 - size;
switch (k)
{
case 1:
return ValueTuple.CombineHashCodes(Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 2:
return ValueTuple.CombineHashCodes(Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 3:
return ValueTuple.CombineHashCodes(Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 4:
return ValueTuple.CombineHashCodes(Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 5:
return ValueTuple.CombineHashCodes(Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 6:
return ValueTuple.CombineHashCodes(Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 7:
case 8:
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
}
Contract.Assert(false, "Missed all cases for computing ValueTuple hash code");
return -1;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
// We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7));
}
int size = rest.Length;
if (size >= 8) { return rest.GetHashCode(comparer); }
// In this case, the rest member has less than 8 elements so we need to combine some our elements with the elements in rest
int k = 8 - size;
switch (k)
{
case 1:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 2:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 3:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7),
rest.GetHashCode(comparer));
case 4:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 5:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5),
comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 6:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7),
rest.GetHashCode(comparer));
case 7:
case 8:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
}
Contract.Assert(false, "Missed all cases for computing ValueTuple hash code");
return -1;
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6, Item7, Rest)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")";
}
else
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd();
}
}
string IValueTupleInternal.ToStringEnd()
{
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")";
}
else
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd();
}
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length
{
get
{
IValueTupleInternal rest = Rest as IValueTupleInternal;
return rest == null ? 8 : 7 + rest.Length;
}
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
case 6:
return Item7;
}
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
if (index == 7)
{
return Rest;
}
throw new IndexOutOfRangeException();
}
return rest[index - 7];
}
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_SyncLock.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode
Dim statements = ArrayBuilder(Of BoundStatement).GetInstance
Dim syntaxNode = DirectCast(node.Syntax, SyncLockBlockSyntax)
' rewrite the lock expression.
Dim visitedLockExpression = VisitExpressionNode(node.LockExpression)
Dim objectType = GetSpecialType(SpecialType.System_Object)
Dim useSiteInfo = GetNewCompoundUseSiteInfo()
Dim conversionKind = Conversions.ClassifyConversion(visitedLockExpression.Type, objectType, useSiteInfo).Key
_diagnostics.Add(node, useSiteInfo)
' when passing this boundlocal to Monitor.Enter and Monitor.Exit we need to pass a local of type object, because the parameter
' are of type object. We also do not want to have this conversion being shown in the semantic model, which is why we add it
' during rewriting. Because only reference types are allowed for synclock, this is always guaranteed to succeed.
' This also unboxes a type parameter, so that the same object is passed to both methods.
If Not Conversions.IsIdentityConversion(conversionKind) Then
Dim integerOverflow As Boolean
Dim constantResult = Conversions.TryFoldConstantConversion(
visitedLockExpression,
objectType,
integerOverflow)
visitedLockExpression = TransformRewrittenConversion(New BoundConversion(node.LockExpression.Syntax,
visitedLockExpression,
conversionKind,
False,
False,
constantResult,
objectType))
End If
' create a new temp local for the lock object
Dim tempLockObjectLocal As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, objectType, SynthesizedLocalKind.Lock, syntaxNode.SyncLockStatement)
Dim boundLockObjectLocal = New BoundLocal(syntaxNode,
tempLockObjectLocal,
objectType)
Dim instrument As Boolean = Me.Instrument(node)
If instrument Then
' create a sequence point that contains the whole SyncLock statement as the first reachable sequence point
' of the SyncLock statement.
Dim prologue = _instrumenterOpt.CreateSyncLockStatementPrologue(node)
If prologue IsNot Nothing Then
statements.Add(prologue)
End If
End If
' assign the lock expression / object to it to avoid changes to it
Dim tempLockObjectAssignment As BoundStatement = New BoundAssignmentOperator(syntaxNode,
boundLockObjectLocal,
visitedLockExpression,
suppressObjectClone:=True,
type:=objectType).ToStatement
boundLockObjectLocal = boundLockObjectLocal.MakeRValue()
If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then
tempLockObjectAssignment = RegisterUnstructuredExceptionHandlingResumeTarget(syntaxNode, tempLockObjectAssignment, canThrow:=True)
End If
Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node)
If instrument Then
tempLockObjectAssignment = _instrumenterOpt.InstrumentSyncLockObjectCapture(node, tempLockObjectAssignment)
End If
statements.Add(tempLockObjectAssignment)
' If the type of the lock object is System.Object we need to call the vb runtime helper
' Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType to ensure no value type is
' used. Note that we are checking type on original bound node for LockExpression because rewritten node will
' always have System.Object as its type due to conversion added above.
' If helper not available on this platform (/vbruntime*), don't call this helper and do not report errors.
Dim checkForSyncLockOnValueTypeMethod As MethodSymbol = Nothing
If node.LockExpression.Type.IsObjectType() AndAlso
TryGetWellknownMember(checkForSyncLockOnValueTypeMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType, syntaxNode, isOptional:=True) Then
Dim boundHelperCall = New BoundCall(syntaxNode,
checkForSyncLockOnValueTypeMethod,
Nothing,
Nothing,
ImmutableArray.Create(Of BoundExpression)(boundLockObjectLocal),
Nothing,
checkForSyncLockOnValueTypeMethod.ReturnType,
suppressObjectClone:=True)
Dim boundHelperCallStatement = boundHelperCall.ToStatement
boundHelperCallStatement.SetWasCompilerGenerated() ' used to not create sequence points
statements.Add(boundHelperCallStatement)
End If
Dim locals As ImmutableArray(Of LocalSymbol)
Dim boundLockTakenLocal As BoundLocal = Nothing
Dim tempLockTakenAssignment As BoundStatement = Nothing
Dim tryStatements As ImmutableArray(Of BoundStatement)
Dim boundMonitorEnterCallStatement As BoundStatement = GenerateMonitorEnter(node.LockExpression.Syntax, boundLockObjectLocal, boundLockTakenLocal, tempLockTakenAssignment)
' the new Monitor.Enter call will be inside the try block, the old is outside
If boundLockTakenLocal IsNot Nothing Then
locals = ImmutableArray.Create(Of LocalSymbol)(tempLockObjectLocal, boundLockTakenLocal.LocalSymbol)
statements.Add(tempLockTakenAssignment)
tryStatements = ImmutableArray.Create(Of BoundStatement)(boundMonitorEnterCallStatement,
DirectCast(Visit(node.Body), BoundBlock))
Else
locals = ImmutableArray.Create(tempLockObjectLocal)
statements.Add(boundMonitorEnterCallStatement)
tryStatements = ImmutableArray.Create(Of BoundStatement)(DirectCast(Visit(node.Body), BoundBlock))
End If
' rewrite the SyncLock body
Dim tryBody As BoundBlock = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
tryStatements)
Dim statementInFinally As BoundStatement = GenerateMonitorExit(syntaxNode, boundLockObjectLocal, boundLockTakenLocal)
Dim finallyBody As BoundBlock = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
ImmutableArray.Create(Of BoundStatement)(statementInFinally))
If instrument Then
' Add a sequence point to highlight the "End SyncLock" syntax in case the body has thrown an exception
finallyBody = DirectCast(Concat(finallyBody, _instrumenterOpt.CreateSyncLockExitDueToExceptionEpilogue(node)), BoundBlock)
End If
Dim rewrittenSyncLock = RewriteTryStatement(syntaxNode, tryBody, ImmutableArray(Of BoundCatchBlock).Empty, finallyBody, Nothing)
statements.Add(rewrittenSyncLock)
If instrument Then
' Add a sequence point to highlight the "End SyncLock" syntax in case the body has been complete executed and
' exited normally
Dim epilogue = _instrumenterOpt.CreateSyncLockExitNormallyEpilogue(node)
If epilogue IsNot Nothing Then
statements.Add(epilogue)
End If
End If
RestoreUnstructuredExceptionHandlingContext(node, saveState)
Return New BoundBlock(syntaxNode,
Nothing,
locals,
statements.ToImmutableAndFree)
End Function
Private Function GenerateMonitorEnter(
syntaxNode As SyntaxNode,
boundLockObject As BoundExpression,
<Out> ByRef boundLockTakenLocal As BoundLocal,
<Out> ByRef boundLockTakenInitialization As BoundStatement
) As BoundStatement
boundLockTakenLocal = Nothing
boundLockTakenInitialization = Nothing
Dim parameters As ImmutableArray(Of BoundExpression)
' Figure out what Enter method to call from Monitor.
' In case the "new" Monitor.Enter(Object, ByRef Boolean) method is found, use that one,
' otherwise fall back to the Monitor.Enter() method.
Dim enterMethod As MethodSymbol = Nothing
If TryGetWellknownMember(enterMethod, WellKnownMember.System_Threading_Monitor__Enter2, syntaxNode, isOptional:=True) Then
' create local for the lockTaken boolean and initialize it with "False"
Dim tempLockTaken As LocalSymbol
If syntaxNode.Parent.Kind = SyntaxKind.SyncLockStatement Then
tempLockTaken = New SynthesizedLocal(Me._currentMethodOrLambda, enterMethod.Parameters(1).Type, SynthesizedLocalKind.LockTaken, DirectCast(syntaxNode.Parent, SyncLockStatementSyntax))
Else
tempLockTaken = New SynthesizedLocal(Me._currentMethodOrLambda, enterMethod.Parameters(1).Type, SynthesizedLocalKind.LoweringTemp)
End If
Debug.Assert(tempLockTaken.Type.IsBooleanType())
boundLockTakenLocal = New BoundLocal(syntaxNode, tempLockTaken, tempLockTaken.Type)
boundLockTakenInitialization = New BoundAssignmentOperator(syntaxNode,
boundLockTakenLocal,
New BoundLiteral(syntaxNode, ConstantValue.False, boundLockTakenLocal.Type),
suppressObjectClone:=True,
type:=boundLockTakenLocal.Type).ToStatement
boundLockTakenInitialization.SetWasCompilerGenerated() ' used to not create sequence points
parameters = ImmutableArray.Create(Of BoundExpression)(boundLockObject, boundLockTakenLocal)
boundLockTakenLocal = boundLockTakenLocal.MakeRValue()
Else
TryGetWellknownMember(enterMethod, WellKnownMember.System_Threading_Monitor__Enter, syntaxNode)
parameters = ImmutableArray.Create(Of BoundExpression)(boundLockObject)
End If
If enterMethod IsNot Nothing Then
' create a call to void Enter(object)
Dim boundMonitorEnterCall As BoundExpression
boundMonitorEnterCall = New BoundCall(syntaxNode,
enterMethod,
Nothing,
Nothing,
parameters,
Nothing,
enterMethod.ReturnType,
suppressObjectClone:=True)
Dim boundMonitorEnterCallStatement = boundMonitorEnterCall.ToStatement
boundMonitorEnterCallStatement.SetWasCompilerGenerated() ' used to not create sequence points
Return boundMonitorEnterCallStatement
End If
Return New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, parameters, ErrorTypeSymbol.UnknownResultType, hasErrors:=True).ToStatement()
End Function
Private Function GenerateMonitorExit(
syntaxNode As SyntaxNode,
boundLockObject As BoundExpression,
boundLockTakenLocal As BoundLocal
) As BoundStatement
Dim statementInFinally As BoundStatement
Dim boundMonitorExitCall As BoundExpression
Dim exitMethod As MethodSymbol = Nothing
If TryGetWellknownMember(exitMethod, WellKnownMember.System_Threading_Monitor__Exit, syntaxNode) Then
' create a call to void Monitor.Exit(object)
boundMonitorExitCall = New BoundCall(syntaxNode,
exitMethod,
Nothing,
Nothing,
ImmutableArray.Create(Of BoundExpression)(boundLockObject),
Nothing,
exitMethod.ReturnType,
suppressObjectClone:=True)
Else
boundMonitorExitCall = New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(boundLockObject), ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End If
Dim boundMonitorExitCallStatement = boundMonitorExitCall.ToStatement
boundMonitorExitCallStatement.SetWasCompilerGenerated() ' used to not create sequence points
If boundLockTakenLocal IsNot Nothing Then
Debug.Assert(boundLockTakenLocal.Type.IsBooleanType())
' if the "new" enter method is used we need to check the temporary boolean to see if the lock was really taken.
' (maybe there was an exception after try and before the enter call).
Dim boundCondition = New BoundBinaryOperator(syntaxNode,
BinaryOperatorKind.Equals,
boundLockTakenLocal,
New BoundLiteral(syntaxNode, ConstantValue.True, boundLockTakenLocal.Type),
False,
boundLockTakenLocal.Type)
statementInFinally = RewriteIfStatement(syntaxNode, boundCondition, boundMonitorExitCallStatement, Nothing, instrumentationTargetOpt:=Nothing)
Else
statementInFinally = boundMonitorExitCallStatement
End If
Return statementInFinally
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode
Dim statements = ArrayBuilder(Of BoundStatement).GetInstance
Dim syntaxNode = DirectCast(node.Syntax, SyncLockBlockSyntax)
' rewrite the lock expression.
Dim visitedLockExpression = VisitExpressionNode(node.LockExpression)
Dim objectType = GetSpecialType(SpecialType.System_Object)
Dim useSiteInfo = GetNewCompoundUseSiteInfo()
Dim conversionKind = Conversions.ClassifyConversion(visitedLockExpression.Type, objectType, useSiteInfo).Key
_diagnostics.Add(node, useSiteInfo)
' when passing this boundlocal to Monitor.Enter and Monitor.Exit we need to pass a local of type object, because the parameter
' are of type object. We also do not want to have this conversion being shown in the semantic model, which is why we add it
' during rewriting. Because only reference types are allowed for synclock, this is always guaranteed to succeed.
' This also unboxes a type parameter, so that the same object is passed to both methods.
If Not Conversions.IsIdentityConversion(conversionKind) Then
Dim integerOverflow As Boolean
Dim constantResult = Conversions.TryFoldConstantConversion(
visitedLockExpression,
objectType,
integerOverflow)
visitedLockExpression = TransformRewrittenConversion(New BoundConversion(node.LockExpression.Syntax,
visitedLockExpression,
conversionKind,
False,
False,
constantResult,
objectType))
End If
' create a new temp local for the lock object
Dim tempLockObjectLocal As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, objectType, SynthesizedLocalKind.Lock, syntaxNode.SyncLockStatement)
Dim boundLockObjectLocal = New BoundLocal(syntaxNode,
tempLockObjectLocal,
objectType)
Dim instrument As Boolean = Me.Instrument(node)
If instrument Then
' create a sequence point that contains the whole SyncLock statement as the first reachable sequence point
' of the SyncLock statement.
Dim prologue = _instrumenterOpt.CreateSyncLockStatementPrologue(node)
If prologue IsNot Nothing Then
statements.Add(prologue)
End If
End If
' assign the lock expression / object to it to avoid changes to it
Dim tempLockObjectAssignment As BoundStatement = New BoundAssignmentOperator(syntaxNode,
boundLockObjectLocal,
visitedLockExpression,
suppressObjectClone:=True,
type:=objectType).ToStatement
boundLockObjectLocal = boundLockObjectLocal.MakeRValue()
If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then
tempLockObjectAssignment = RegisterUnstructuredExceptionHandlingResumeTarget(syntaxNode, tempLockObjectAssignment, canThrow:=True)
End If
Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node)
If instrument Then
tempLockObjectAssignment = _instrumenterOpt.InstrumentSyncLockObjectCapture(node, tempLockObjectAssignment)
End If
statements.Add(tempLockObjectAssignment)
' If the type of the lock object is System.Object we need to call the vb runtime helper
' Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType to ensure no value type is
' used. Note that we are checking type on original bound node for LockExpression because rewritten node will
' always have System.Object as its type due to conversion added above.
' If helper not available on this platform (/vbruntime*), don't call this helper and do not report errors.
Dim checkForSyncLockOnValueTypeMethod As MethodSymbol = Nothing
If node.LockExpression.Type.IsObjectType() AndAlso
TryGetWellknownMember(checkForSyncLockOnValueTypeMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType, syntaxNode, isOptional:=True) Then
Dim boundHelperCall = New BoundCall(syntaxNode,
checkForSyncLockOnValueTypeMethod,
Nothing,
Nothing,
ImmutableArray.Create(Of BoundExpression)(boundLockObjectLocal),
Nothing,
checkForSyncLockOnValueTypeMethod.ReturnType,
suppressObjectClone:=True)
Dim boundHelperCallStatement = boundHelperCall.ToStatement
boundHelperCallStatement.SetWasCompilerGenerated() ' used to not create sequence points
statements.Add(boundHelperCallStatement)
End If
Dim locals As ImmutableArray(Of LocalSymbol)
Dim boundLockTakenLocal As BoundLocal = Nothing
Dim tempLockTakenAssignment As BoundStatement = Nothing
Dim tryStatements As ImmutableArray(Of BoundStatement)
Dim boundMonitorEnterCallStatement As BoundStatement = GenerateMonitorEnter(node.LockExpression.Syntax, boundLockObjectLocal, boundLockTakenLocal, tempLockTakenAssignment)
' the new Monitor.Enter call will be inside the try block, the old is outside
If boundLockTakenLocal IsNot Nothing Then
locals = ImmutableArray.Create(Of LocalSymbol)(tempLockObjectLocal, boundLockTakenLocal.LocalSymbol)
statements.Add(tempLockTakenAssignment)
tryStatements = ImmutableArray.Create(Of BoundStatement)(boundMonitorEnterCallStatement,
DirectCast(Visit(node.Body), BoundBlock))
Else
locals = ImmutableArray.Create(tempLockObjectLocal)
statements.Add(boundMonitorEnterCallStatement)
tryStatements = ImmutableArray.Create(Of BoundStatement)(DirectCast(Visit(node.Body), BoundBlock))
End If
' rewrite the SyncLock body
Dim tryBody As BoundBlock = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
tryStatements)
Dim statementInFinally As BoundStatement = GenerateMonitorExit(syntaxNode, boundLockObjectLocal, boundLockTakenLocal)
Dim finallyBody As BoundBlock = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
ImmutableArray.Create(Of BoundStatement)(statementInFinally))
If instrument Then
' Add a sequence point to highlight the "End SyncLock" syntax in case the body has thrown an exception
finallyBody = DirectCast(Concat(finallyBody, _instrumenterOpt.CreateSyncLockExitDueToExceptionEpilogue(node)), BoundBlock)
End If
Dim rewrittenSyncLock = RewriteTryStatement(syntaxNode, tryBody, ImmutableArray(Of BoundCatchBlock).Empty, finallyBody, Nothing)
statements.Add(rewrittenSyncLock)
If instrument Then
' Add a sequence point to highlight the "End SyncLock" syntax in case the body has been complete executed and
' exited normally
Dim epilogue = _instrumenterOpt.CreateSyncLockExitNormallyEpilogue(node)
If epilogue IsNot Nothing Then
statements.Add(epilogue)
End If
End If
RestoreUnstructuredExceptionHandlingContext(node, saveState)
Return New BoundBlock(syntaxNode,
Nothing,
locals,
statements.ToImmutableAndFree)
End Function
Private Function GenerateMonitorEnter(
syntaxNode As SyntaxNode,
boundLockObject As BoundExpression,
<Out> ByRef boundLockTakenLocal As BoundLocal,
<Out> ByRef boundLockTakenInitialization As BoundStatement
) As BoundStatement
boundLockTakenLocal = Nothing
boundLockTakenInitialization = Nothing
Dim parameters As ImmutableArray(Of BoundExpression)
' Figure out what Enter method to call from Monitor.
' In case the "new" Monitor.Enter(Object, ByRef Boolean) method is found, use that one,
' otherwise fall back to the Monitor.Enter() method.
Dim enterMethod As MethodSymbol = Nothing
If TryGetWellknownMember(enterMethod, WellKnownMember.System_Threading_Monitor__Enter2, syntaxNode, isOptional:=True) Then
' create local for the lockTaken boolean and initialize it with "False"
Dim tempLockTaken As LocalSymbol
If syntaxNode.Parent.Kind = SyntaxKind.SyncLockStatement Then
tempLockTaken = New SynthesizedLocal(Me._currentMethodOrLambda, enterMethod.Parameters(1).Type, SynthesizedLocalKind.LockTaken, DirectCast(syntaxNode.Parent, SyncLockStatementSyntax))
Else
tempLockTaken = New SynthesizedLocal(Me._currentMethodOrLambda, enterMethod.Parameters(1).Type, SynthesizedLocalKind.LoweringTemp)
End If
Debug.Assert(tempLockTaken.Type.IsBooleanType())
boundLockTakenLocal = New BoundLocal(syntaxNode, tempLockTaken, tempLockTaken.Type)
boundLockTakenInitialization = New BoundAssignmentOperator(syntaxNode,
boundLockTakenLocal,
New BoundLiteral(syntaxNode, ConstantValue.False, boundLockTakenLocal.Type),
suppressObjectClone:=True,
type:=boundLockTakenLocal.Type).ToStatement
boundLockTakenInitialization.SetWasCompilerGenerated() ' used to not create sequence points
parameters = ImmutableArray.Create(Of BoundExpression)(boundLockObject, boundLockTakenLocal)
boundLockTakenLocal = boundLockTakenLocal.MakeRValue()
Else
TryGetWellknownMember(enterMethod, WellKnownMember.System_Threading_Monitor__Enter, syntaxNode)
parameters = ImmutableArray.Create(Of BoundExpression)(boundLockObject)
End If
If enterMethod IsNot Nothing Then
' create a call to void Enter(object)
Dim boundMonitorEnterCall As BoundExpression
boundMonitorEnterCall = New BoundCall(syntaxNode,
enterMethod,
Nothing,
Nothing,
parameters,
Nothing,
enterMethod.ReturnType,
suppressObjectClone:=True)
Dim boundMonitorEnterCallStatement = boundMonitorEnterCall.ToStatement
boundMonitorEnterCallStatement.SetWasCompilerGenerated() ' used to not create sequence points
Return boundMonitorEnterCallStatement
End If
Return New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, parameters, ErrorTypeSymbol.UnknownResultType, hasErrors:=True).ToStatement()
End Function
Private Function GenerateMonitorExit(
syntaxNode As SyntaxNode,
boundLockObject As BoundExpression,
boundLockTakenLocal As BoundLocal
) As BoundStatement
Dim statementInFinally As BoundStatement
Dim boundMonitorExitCall As BoundExpression
Dim exitMethod As MethodSymbol = Nothing
If TryGetWellknownMember(exitMethod, WellKnownMember.System_Threading_Monitor__Exit, syntaxNode) Then
' create a call to void Monitor.Exit(object)
boundMonitorExitCall = New BoundCall(syntaxNode,
exitMethod,
Nothing,
Nothing,
ImmutableArray.Create(Of BoundExpression)(boundLockObject),
Nothing,
exitMethod.ReturnType,
suppressObjectClone:=True)
Else
boundMonitorExitCall = New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(boundLockObject), ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End If
Dim boundMonitorExitCallStatement = boundMonitorExitCall.ToStatement
boundMonitorExitCallStatement.SetWasCompilerGenerated() ' used to not create sequence points
If boundLockTakenLocal IsNot Nothing Then
Debug.Assert(boundLockTakenLocal.Type.IsBooleanType())
' if the "new" enter method is used we need to check the temporary boolean to see if the lock was really taken.
' (maybe there was an exception after try and before the enter call).
Dim boundCondition = New BoundBinaryOperator(syntaxNode,
BinaryOperatorKind.Equals,
boundLockTakenLocal,
New BoundLiteral(syntaxNode, ConstantValue.True, boundLockTakenLocal.Type),
False,
boundLockTakenLocal.Type)
statementInFinally = RewriteIfStatement(syntaxNode, boundCondition, boundMonitorExitCallStatement, Nothing, instrumentationTargetOpt:=Nothing)
Else
statementInFinally = boundMonitorExitCallStatement
End If
Return statementInFinally
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Analyzers/Core/Analyzers/FileHeaders/AbstractFileHeaderDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FileHeaders
{
internal abstract class AbstractFileHeaderDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
protected AbstractFileHeaderDiagnosticAnalyzer(string language)
: base(
IDEDiagnosticIds.FileHeaderMismatch,
EnforceOnBuildValues.FileHeaderMismatch,
CodeStyleOptions2.FileHeaderTemplate,
language,
new LocalizableResourceString(nameof(AnalyzersResources.The_file_header_is_missing_or_not_located_at_the_top_of_the_file), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.A_source_file_is_missing_a_required_header), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
RoslynDebug.AssertNotNull(DescriptorId);
var invalidHeaderTitle = new LocalizableResourceString(nameof(AnalyzersResources.The_file_header_does_not_match_the_required_text), AnalyzersResources.ResourceManager, typeof(AnalyzersResources));
var invalidHeaderMessage = new LocalizableResourceString(nameof(AnalyzersResources.A_source_file_contains_a_header_that_does_not_match_the_required_text), AnalyzersResources.ResourceManager, typeof(AnalyzersResources));
InvalidHeaderDescriptor = CreateDescriptorWithId(DescriptorId, EnforceOnBuildValues.FileHeaderMismatch, invalidHeaderTitle, invalidHeaderMessage);
}
protected abstract AbstractFileHeaderHelper FileHeaderHelper { get; }
internal DiagnosticDescriptor MissingHeaderDescriptor => Descriptor;
internal DiagnosticDescriptor InvalidHeaderDescriptor { get; }
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(HandleSyntaxTree);
private void HandleSyntaxTree(SyntaxTreeAnalysisContext context)
{
var tree = context.Tree;
var root = tree.GetRoot(context.CancellationToken);
// don't process empty files
if (root.FullSpan.IsEmpty)
{
return;
}
if (!context.Options.TryGetEditorConfigOption<string>(CodeStyleOptions2.FileHeaderTemplate, tree, out var fileHeaderTemplate)
|| string.IsNullOrEmpty(fileHeaderTemplate))
{
return;
}
var fileHeader = FileHeaderHelper.ParseFileHeader(root);
if (fileHeader.IsMissing)
{
context.ReportDiagnostic(Diagnostic.Create(MissingHeaderDescriptor, fileHeader.GetLocation(tree)));
return;
}
var expectedFileHeader = fileHeaderTemplate.Replace("{fileName}", Path.GetFileName(tree.FilePath));
if (!CompareCopyrightText(expectedFileHeader, fileHeader.CopyrightText))
{
context.ReportDiagnostic(Diagnostic.Create(InvalidHeaderDescriptor, fileHeader.GetLocation(tree)));
return;
}
}
private static bool CompareCopyrightText(string expectedFileHeader, string copyrightText)
{
// make sure that both \n and \r\n are accepted from the settings.
var reformattedCopyrightTextParts = expectedFileHeader.Replace("\r\n", "\n").Split('\n');
var fileHeaderCopyrightTextParts = copyrightText.Replace("\r\n", "\n").Split('\n');
if (reformattedCopyrightTextParts.Length != fileHeaderCopyrightTextParts.Length)
{
return false;
}
// compare line by line, ignoring leading and trailing whitespace on each line.
for (var i = 0; i < reformattedCopyrightTextParts.Length; i++)
{
if (string.CompareOrdinal(reformattedCopyrightTextParts[i].Trim(), fileHeaderCopyrightTextParts[i].Trim()) != 0)
{
return false;
}
}
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FileHeaders
{
internal abstract class AbstractFileHeaderDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
protected AbstractFileHeaderDiagnosticAnalyzer(string language)
: base(
IDEDiagnosticIds.FileHeaderMismatch,
EnforceOnBuildValues.FileHeaderMismatch,
CodeStyleOptions2.FileHeaderTemplate,
language,
new LocalizableResourceString(nameof(AnalyzersResources.The_file_header_is_missing_or_not_located_at_the_top_of_the_file), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.A_source_file_is_missing_a_required_header), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
RoslynDebug.AssertNotNull(DescriptorId);
var invalidHeaderTitle = new LocalizableResourceString(nameof(AnalyzersResources.The_file_header_does_not_match_the_required_text), AnalyzersResources.ResourceManager, typeof(AnalyzersResources));
var invalidHeaderMessage = new LocalizableResourceString(nameof(AnalyzersResources.A_source_file_contains_a_header_that_does_not_match_the_required_text), AnalyzersResources.ResourceManager, typeof(AnalyzersResources));
InvalidHeaderDescriptor = CreateDescriptorWithId(DescriptorId, EnforceOnBuildValues.FileHeaderMismatch, invalidHeaderTitle, invalidHeaderMessage);
}
protected abstract AbstractFileHeaderHelper FileHeaderHelper { get; }
internal DiagnosticDescriptor MissingHeaderDescriptor => Descriptor;
internal DiagnosticDescriptor InvalidHeaderDescriptor { get; }
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(HandleSyntaxTree);
private void HandleSyntaxTree(SyntaxTreeAnalysisContext context)
{
var tree = context.Tree;
var root = tree.GetRoot(context.CancellationToken);
// don't process empty files
if (root.FullSpan.IsEmpty)
{
return;
}
if (!context.Options.TryGetEditorConfigOption<string>(CodeStyleOptions2.FileHeaderTemplate, tree, out var fileHeaderTemplate)
|| string.IsNullOrEmpty(fileHeaderTemplate))
{
return;
}
var fileHeader = FileHeaderHelper.ParseFileHeader(root);
if (fileHeader.IsMissing)
{
context.ReportDiagnostic(Diagnostic.Create(MissingHeaderDescriptor, fileHeader.GetLocation(tree)));
return;
}
var expectedFileHeader = fileHeaderTemplate.Replace("{fileName}", Path.GetFileName(tree.FilePath));
if (!CompareCopyrightText(expectedFileHeader, fileHeader.CopyrightText))
{
context.ReportDiagnostic(Diagnostic.Create(InvalidHeaderDescriptor, fileHeader.GetLocation(tree)));
return;
}
}
private static bool CompareCopyrightText(string expectedFileHeader, string copyrightText)
{
// make sure that both \n and \r\n are accepted from the settings.
var reformattedCopyrightTextParts = expectedFileHeader.Replace("\r\n", "\n").Split('\n');
var fileHeaderCopyrightTextParts = copyrightText.Replace("\r\n", "\n").Split('\n');
if (reformattedCopyrightTextParts.Length != fileHeaderCopyrightTextParts.Length)
{
return false;
}
// compare line by line, ignoring leading and trailing whitespace on each line.
for (var i = 0; i < reformattedCopyrightTextParts.Length; i++)
{
if (string.CompareOrdinal(reformattedCopyrightTextParts[i].Trim(), fileHeaderCopyrightTextParts[i].Trim()) != 0)
{
return false;
}
}
return true;
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/VisualBasic/Portable/Declarations/SingleTypeDeclaration.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend Class SingleTypeDeclaration
Inherits SingleNamespaceOrTypeDeclaration
Private ReadOnly _children As ImmutableArray(Of SingleTypeDeclaration)
' CONSIDER: It may be possible to merge the flags and arity into a single
' 32-bit quantity if space is needed.
Private ReadOnly _kind As DeclarationKind
Private ReadOnly _flags As TypeDeclarationFlags
Private ReadOnly _arity As UShort
Private ReadOnly _modifiers As DeclarationModifiers
Friend Enum TypeDeclarationFlags As Byte
None = 0
HasAnyAttributes = 1 << 1
HasBaseDeclarations = 1 << 2
AnyMemberHasAttributes = 1 << 3
HasAnyNontypeMembers = 1 << 4
End Enum
Public Sub New(kind As DeclarationKind,
name As String,
arity As Integer,
modifiers As DeclarationModifiers,
declFlags As TypeDeclarationFlags,
syntaxReference As SyntaxReference,
nameLocation As Location,
memberNames As ImmutableHashSet(Of String),
children As ImmutableArray(Of SingleTypeDeclaration))
MyBase.New(name, syntaxReference, nameLocation)
Debug.Assert(kind <> DeclarationKind.Namespace)
Me._kind = kind
Me._arity = CUShort(arity)
Me._flags = declFlags
Me._modifiers = modifiers
Me.MemberNames = memberNames
Me._children = children
End Sub
Public Overrides ReadOnly Property Kind As DeclarationKind
Get
Return Me._kind
End Get
End Property
Public ReadOnly Property Arity As Integer
Get
Return _arity
End Get
End Property
Public ReadOnly Property HasAnyAttributes As Boolean
Get
Return (_flags And TypeDeclarationFlags.HasAnyAttributes) <> 0
End Get
End Property
Public ReadOnly Property HasBaseDeclarations As Boolean
Get
Return (_flags And TypeDeclarationFlags.HasBaseDeclarations) <> 0
End Get
End Property
Public ReadOnly Property HasAnyNontypeMembers As Boolean
Get
Return (_flags And TypeDeclarationFlags.HasAnyNontypeMembers) <> 0
End Get
End Property
Public ReadOnly Property AnyMemberHasAttributes As Boolean
Get
Return (_flags And TypeDeclarationFlags.AnyMemberHasAttributes) <> 0
End Get
End Property
Public Overloads ReadOnly Property Children As ImmutableArray(Of SingleTypeDeclaration)
Get
Return _children
End Get
End Property
Public ReadOnly Property Modifiers As DeclarationModifiers
Get
Return Me._modifiers
End Get
End Property
Public ReadOnly Property MemberNames As ImmutableHashSet(Of String)
Protected Overrides Function GetNamespaceOrTypeDeclarationChildren() As ImmutableArray(Of SingleNamespaceOrTypeDeclaration)
Return StaticCast(Of SingleNamespaceOrTypeDeclaration).From(_children)
End Function
Private Function GetEmbeddedSymbolKind() As EmbeddedSymbolKind
Return SyntaxReference.SyntaxTree.GetEmbeddedKind()
End Function
Private NotInheritable Class Comparer
Implements IEqualityComparer(Of SingleTypeDeclaration)
Private Shadows Function Equals(decl1 As SingleTypeDeclaration, decl2 As SingleTypeDeclaration) As Boolean Implements IEqualityComparer(Of SingleTypeDeclaration).Equals
' We should not merge types across embedded code / user code boundary.
Return IdentifierComparison.Equals(decl1.Name, decl2.Name) _
AndAlso decl1.Kind = decl2.Kind _
AndAlso decl1.Kind <> DeclarationKind.Enum _
AndAlso decl1.Arity = decl2.Arity _
AndAlso decl1.GetEmbeddedSymbolKind() = decl2.GetEmbeddedSymbolKind()
End Function
Private Shadows Function GetHashCode(decl1 As SingleTypeDeclaration) As Integer Implements IEqualityComparer(Of SingleTypeDeclaration).GetHashCode
Return Hash.Combine(IdentifierComparison.GetHashCode(decl1.Name), Hash.Combine(decl1.Arity.GetHashCode(), CType(decl1.Kind, Integer)))
End Function
End Class
Public Shared ReadOnly EqualityComparer As IEqualityComparer(Of SingleTypeDeclaration) = New Comparer()
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend Class SingleTypeDeclaration
Inherits SingleNamespaceOrTypeDeclaration
Private ReadOnly _children As ImmutableArray(Of SingleTypeDeclaration)
' CONSIDER: It may be possible to merge the flags and arity into a single
' 32-bit quantity if space is needed.
Private ReadOnly _kind As DeclarationKind
Private ReadOnly _flags As TypeDeclarationFlags
Private ReadOnly _arity As UShort
Private ReadOnly _modifiers As DeclarationModifiers
Friend Enum TypeDeclarationFlags As Byte
None = 0
HasAnyAttributes = 1 << 1
HasBaseDeclarations = 1 << 2
AnyMemberHasAttributes = 1 << 3
HasAnyNontypeMembers = 1 << 4
End Enum
Public Sub New(kind As DeclarationKind,
name As String,
arity As Integer,
modifiers As DeclarationModifiers,
declFlags As TypeDeclarationFlags,
syntaxReference As SyntaxReference,
nameLocation As Location,
memberNames As ImmutableHashSet(Of String),
children As ImmutableArray(Of SingleTypeDeclaration))
MyBase.New(name, syntaxReference, nameLocation)
Debug.Assert(kind <> DeclarationKind.Namespace)
Me._kind = kind
Me._arity = CUShort(arity)
Me._flags = declFlags
Me._modifiers = modifiers
Me.MemberNames = memberNames
Me._children = children
End Sub
Public Overrides ReadOnly Property Kind As DeclarationKind
Get
Return Me._kind
End Get
End Property
Public ReadOnly Property Arity As Integer
Get
Return _arity
End Get
End Property
Public ReadOnly Property HasAnyAttributes As Boolean
Get
Return (_flags And TypeDeclarationFlags.HasAnyAttributes) <> 0
End Get
End Property
Public ReadOnly Property HasBaseDeclarations As Boolean
Get
Return (_flags And TypeDeclarationFlags.HasBaseDeclarations) <> 0
End Get
End Property
Public ReadOnly Property HasAnyNontypeMembers As Boolean
Get
Return (_flags And TypeDeclarationFlags.HasAnyNontypeMembers) <> 0
End Get
End Property
Public ReadOnly Property AnyMemberHasAttributes As Boolean
Get
Return (_flags And TypeDeclarationFlags.AnyMemberHasAttributes) <> 0
End Get
End Property
Public Overloads ReadOnly Property Children As ImmutableArray(Of SingleTypeDeclaration)
Get
Return _children
End Get
End Property
Public ReadOnly Property Modifiers As DeclarationModifiers
Get
Return Me._modifiers
End Get
End Property
Public ReadOnly Property MemberNames As ImmutableHashSet(Of String)
Protected Overrides Function GetNamespaceOrTypeDeclarationChildren() As ImmutableArray(Of SingleNamespaceOrTypeDeclaration)
Return StaticCast(Of SingleNamespaceOrTypeDeclaration).From(_children)
End Function
Private Function GetEmbeddedSymbolKind() As EmbeddedSymbolKind
Return SyntaxReference.SyntaxTree.GetEmbeddedKind()
End Function
Private NotInheritable Class Comparer
Implements IEqualityComparer(Of SingleTypeDeclaration)
Private Shadows Function Equals(decl1 As SingleTypeDeclaration, decl2 As SingleTypeDeclaration) As Boolean Implements IEqualityComparer(Of SingleTypeDeclaration).Equals
' We should not merge types across embedded code / user code boundary.
Return IdentifierComparison.Equals(decl1.Name, decl2.Name) _
AndAlso decl1.Kind = decl2.Kind _
AndAlso decl1.Kind <> DeclarationKind.Enum _
AndAlso decl1.Arity = decl2.Arity _
AndAlso decl1.GetEmbeddedSymbolKind() = decl2.GetEmbeddedSymbolKind()
End Function
Private Shadows Function GetHashCode(decl1 As SingleTypeDeclaration) As Integer Implements IEqualityComparer(Of SingleTypeDeclaration).GetHashCode
Return Hash.Combine(IdentifierComparison.GetHashCode(decl1.Name), Hash.Combine(decl1.Arity.GetHashCode(), CType(decl1.Kind, Integer)))
End Function
End Class
Public Shared ReadOnly EqualityComparer As IEqualityComparer(Of SingleTypeDeclaration) = New Comparer()
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/VisualStudio/Core/Test/CommonControls/MemberSelectionViewModelTests.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
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PullMemberUp
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls
Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp
Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CommonControls
<[UseExportProvider]>
Public Class MemberSelectionViewModelTests
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)>
Public Async Function SelectPublicMembers() As Task
Dim markUp = <Text><![CDATA[
interface Level2Interface
{
}
interface Level1Interface : Level2Interface
{
}
class Level1BaseClass: Level2Interface
{
}
class MyClass : Level1BaseClass, Level1Interface
{
public void G$$oo()
{
}
public double e => 2.717;
public const days = 365;
private double pi => 3.1416;
protected float goldenRadio = 0.618;
internal float gravitational = 6.67e-11;
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp)
viewModel.SelectPublic()
For Each member In viewModel.Members.Where(Function(memberViewModel) memberViewModel.Symbol.DeclaredAccessibility = Microsoft.CodeAnalysis.Accessibility.Public)
Assert.True(member.IsChecked)
Next
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)>
Public Async Function TestMemberSelectionViewModelDont_PullDisableItem() As Task
Dim markUp = <Text><![CDATA[
interface Level2Interface
{
}
interface Level1Interface : Level2Interface
{
}
class Level1BaseClass: Level2Interface
{
}
class MyClass : Level1BaseClass, Level1Interface
{
public void G$$oo()
{
}
public double e => 2.717;
public const days = 365;
private double pi => 3.1416;
protected float goldenRadio = 0.618;
internal float gravitational = 6.67e-11;
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp)
viewModel.SelectAll()
' select an interface, all checkbox of field will be disable
viewModel.UpdateMembersBasedOnDestinationKind(TypeKind.Interface)
' Make sure fields are not pulled to interface
Dim checkedMembers = viewModel.CheckedMembers()
Assert.Empty(checkedMembers.WhereAsArray(Function(analysisResult) analysisResult.Symbol.IsKind(SymbolKind.Field)))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)>
Public Async Function SelectDependents() As Task
Dim markUp = <Text><![CDATA[
using System;
class Level1BaseClass
{
}
class MyClass : Level1BaseClass
{
private int i = 100;
private event EventHandler FooEvent;
public void G$$oo()
{
int i = BarBar(e);
What = 1000;
}
public int BarBar(double e)
{
Nested1();
return 1000;
}
private void Nested1()
{
int i = 1000;
gravitational == 1.0;
}
internal float gravitational = 6.67e-11;
private int What {get; set; }
public double e => 2.717;
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp)
viewModel.SelectDependents()
' Dependents of Goo
Assert.True(FindMemberByName("Goo()", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("e", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("What", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("BarBar(double)", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("Nested1()", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("gravitational", viewModel.Members).IsChecked)
' Not the depenents of Goo
Assert.False(FindMemberByName("i", viewModel.Members).IsChecked)
Assert.False(FindMemberByName("FooEvent", viewModel.Members).IsChecked)
End Function
Private Function FindMemberByName(name As String, memberArray As ImmutableArray(Of PullMemberUpSymbolViewModel)) As PullMemberUpSymbolViewModel
Dim member = memberArray.FirstOrDefault(Function(memberViewModel) memberViewModel.SymbolName.Equals(name))
If (member Is Nothing) Then
Assert.True(False, $"No member called {name} found")
End If
Return member
End Function
Private Async Function GetViewModelAsync(markup As XElement, languageName As String) As Task(Of MemberSelectionViewModel)
Dim workspaceXml =
<Workspace>
<Project Language=<%= languageName %> CommonReferences="true">
<Document><%= markup.Value %></Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml)
Dim doc = workspace.Documents.Single()
Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id)
If (Not doc.CursorPosition.HasValue) Then
Throw New ArgumentException("Missing caret location in document.")
End If
Dim tree = Await workspaceDoc.GetSyntaxTreeAsync()
Dim token = Await tree.GetTouchingWordAsync(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None)
Dim memberSymbol = (Await workspaceDoc.GetSemanticModelAsync()).GetDeclaredSymbol(token.Parent)
Dim membersInType = memberSymbol.ContainingType.GetMembers().WhereAsArray(Function(member) MemberAndDestinationValidator.IsMemberValid(member))
Dim membersViewModel = membersInType.SelectAsArray(
Function(member) New PullMemberUpSymbolViewModel(member, glyphService:=Nothing) With {.IsChecked = member.Equals(memberSymbol), .IsCheckable = True, .MakeAbstract = False})
Dim memberToDependents = SymbolDependentsBuilder.FindMemberToDependentsMap(membersInType, workspaceDoc.Project, CancellationToken.None)
Return New MemberSelectionViewModel(
workspace.GetService(Of IUIThreadOperationExecutor),
membersViewModel,
memberToDependents)
End Using
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PullMemberUp
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls
Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp
Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CommonControls
<[UseExportProvider]>
Public Class MemberSelectionViewModelTests
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)>
Public Async Function SelectPublicMembers() As Task
Dim markUp = <Text><![CDATA[
interface Level2Interface
{
}
interface Level1Interface : Level2Interface
{
}
class Level1BaseClass: Level2Interface
{
}
class MyClass : Level1BaseClass, Level1Interface
{
public void G$$oo()
{
}
public double e => 2.717;
public const days = 365;
private double pi => 3.1416;
protected float goldenRadio = 0.618;
internal float gravitational = 6.67e-11;
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp)
viewModel.SelectPublic()
For Each member In viewModel.Members.Where(Function(memberViewModel) memberViewModel.Symbol.DeclaredAccessibility = Microsoft.CodeAnalysis.Accessibility.Public)
Assert.True(member.IsChecked)
Next
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)>
Public Async Function TestMemberSelectionViewModelDont_PullDisableItem() As Task
Dim markUp = <Text><![CDATA[
interface Level2Interface
{
}
interface Level1Interface : Level2Interface
{
}
class Level1BaseClass: Level2Interface
{
}
class MyClass : Level1BaseClass, Level1Interface
{
public void G$$oo()
{
}
public double e => 2.717;
public const days = 365;
private double pi => 3.1416;
protected float goldenRadio = 0.618;
internal float gravitational = 6.67e-11;
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp)
viewModel.SelectAll()
' select an interface, all checkbox of field will be disable
viewModel.UpdateMembersBasedOnDestinationKind(TypeKind.Interface)
' Make sure fields are not pulled to interface
Dim checkedMembers = viewModel.CheckedMembers()
Assert.Empty(checkedMembers.WhereAsArray(Function(analysisResult) analysisResult.Symbol.IsKind(SymbolKind.Field)))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)>
Public Async Function SelectDependents() As Task
Dim markUp = <Text><![CDATA[
using System;
class Level1BaseClass
{
}
class MyClass : Level1BaseClass
{
private int i = 100;
private event EventHandler FooEvent;
public void G$$oo()
{
int i = BarBar(e);
What = 1000;
}
public int BarBar(double e)
{
Nested1();
return 1000;
}
private void Nested1()
{
int i = 1000;
gravitational == 1.0;
}
internal float gravitational = 6.67e-11;
private int What {get; set; }
public double e => 2.717;
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp)
viewModel.SelectDependents()
' Dependents of Goo
Assert.True(FindMemberByName("Goo()", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("e", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("What", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("BarBar(double)", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("Nested1()", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("gravitational", viewModel.Members).IsChecked)
' Not the depenents of Goo
Assert.False(FindMemberByName("i", viewModel.Members).IsChecked)
Assert.False(FindMemberByName("FooEvent", viewModel.Members).IsChecked)
End Function
Private Function FindMemberByName(name As String, memberArray As ImmutableArray(Of PullMemberUpSymbolViewModel)) As PullMemberUpSymbolViewModel
Dim member = memberArray.FirstOrDefault(Function(memberViewModel) memberViewModel.SymbolName.Equals(name))
If (member Is Nothing) Then
Assert.True(False, $"No member called {name} found")
End If
Return member
End Function
Private Async Function GetViewModelAsync(markup As XElement, languageName As String) As Task(Of MemberSelectionViewModel)
Dim workspaceXml =
<Workspace>
<Project Language=<%= languageName %> CommonReferences="true">
<Document><%= markup.Value %></Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml)
Dim doc = workspace.Documents.Single()
Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id)
If (Not doc.CursorPosition.HasValue) Then
Throw New ArgumentException("Missing caret location in document.")
End If
Dim tree = Await workspaceDoc.GetSyntaxTreeAsync()
Dim token = Await tree.GetTouchingWordAsync(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None)
Dim memberSymbol = (Await workspaceDoc.GetSemanticModelAsync()).GetDeclaredSymbol(token.Parent)
Dim membersInType = memberSymbol.ContainingType.GetMembers().WhereAsArray(Function(member) MemberAndDestinationValidator.IsMemberValid(member))
Dim membersViewModel = membersInType.SelectAsArray(
Function(member) New PullMemberUpSymbolViewModel(member, glyphService:=Nothing) With {.IsChecked = member.Equals(memberSymbol), .IsCheckable = True, .MakeAbstract = False})
Dim memberToDependents = SymbolDependentsBuilder.FindMemberToDependentsMap(membersInType, workspaceDoc.Project, CancellationToken.None)
Return New MemberSelectionViewModel(
workspace.GetService(Of IUIThreadOperationExecutor),
membersViewModel,
memberToDependents)
End Using
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/EditorFeatures/VisualBasic/EndConstructGeneration/EndConstructStatementVisitor_LambdaHeader.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.Text.Shared.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Partial Friend Class EndConstructStatementVisitor
Public Overrides Function VisitLambdaHeader(node As LambdaHeaderSyntax) As AbstractEndConstructResult
Dim singleLineExpressionSyntax = TryCast(node.Parent, SingleLineLambdaExpressionSyntax)
If singleLineExpressionSyntax IsNot Nothing Then
Return TransformSingleLineLambda(singleLineExpressionSyntax)
Else
Return SpitNormalLambdaEnding(node)
End If
End Function
Private Function TransformSingleLineLambda(originalNode As SingleLineLambdaExpressionSyntax) As AbstractEndConstructResult
' If there is newline trivia on the end of the node, we need to pull that off to stick it back on at the very end of this transformation
Dim newLineTrivia = originalNode.GetTrailingTrivia().SkipWhile(Function(t) Not t.IsKind(SyntaxKind.EndOfLineTrivia))
Dim node = originalNode.WithTrailingTrivia(originalNode.GetTrailingTrivia().TakeWhile(Function(t) Not t.IsKind(SyntaxKind.EndOfLineTrivia)))
Dim tokenNextToLambda = originalNode.GetLastToken().GetNextToken()
Dim isNextToXmlEmbeddedExpression = tokenNextToLambda.IsKind(SyntaxKind.PercentGreaterThanToken) AndAlso tokenNextToLambda.Parent.IsKind(SyntaxKind.XmlEmbeddedExpression)
Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(originalNode.SpanStart)
Dim indentedWhitespace = aligningWhitespace & " "
' Generate the end statement since we can easily share that code
Dim endStatementKind = If(originalNode.Kind = SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.EndSubStatement, SyntaxKind.EndFunctionStatement)
Dim endStatement = SyntaxFactory.EndBlockStatement(endStatementKind, SyntaxFactory.Token(originalNode.SubOrFunctionHeader.DeclarationKeyword.Kind).WithLeadingTrivia(SyntaxFactory.WhitespaceTrivia(" "))) _
.WithLeadingTrivia(SyntaxFactory.WhitespaceTrivia(aligningWhitespace)) _
.WithTrailingTrivia(If(isNextToXmlEmbeddedExpression, SyntaxFactory.TriviaList(SyntaxFactory.WhitespaceTrivia(" ")), newLineTrivia))
' We are hitting enter after a single line. Let's transform it to a multi-line form
If node.Kind = SyntaxKind.SingleLineSubLambdaExpression Then
' If we have Sub() End Sub as a lambda, we're better off just doing nothing smart
If node.Body.IsKind(SyntaxKind.EndSubStatement) Then
Return Nothing
End If
' Update the new header
Dim newHeader = node.SubOrFunctionHeader
If newHeader.ParameterList Is Nothing OrElse
(newHeader.ParameterList.OpenParenToken.IsMissing AndAlso newHeader.ParameterList.CloseParenToken.IsMissing) Then
newHeader = newHeader.WithParameterList(SyntaxFactory.ParameterList())
End If
newHeader = newHeader.WithTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter))
' Update the body with a newline
Dim newBody = DirectCast(node.Body, StatementSyntax).WithAppendedTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter))
Dim newBodyHasCode = False
' If it actually contains something, intent it too. Otherwise, we'll just let the smart indenter position
If Not String.IsNullOrWhiteSpace(newBody.ToFullString()) Then
newBody = newBody.WithPrependedLeadingTrivia(SyntaxFactory.WhitespaceTrivia(indentedWhitespace))
newBodyHasCode = True
End If
Dim newExpression = SyntaxFactory.MultiLineSubLambdaExpression(
subOrFunctionHeader:=newHeader,
statements:=SyntaxFactory.SingletonList(newBody),
endSubOrFunctionStatement:=endStatement)
Return New ReplaceSpanResult(originalNode.FullSpan.ToSnapshotSpan(_subjectBuffer.CurrentSnapshot),
newExpression.ToFullString(),
If(newBodyHasCode, CType(newExpression.Statements.First().SpanStart, Integer?), Nothing))
Else
If node.Body.IsMissing Then
If node.Body.GetTrailingTrivia().Any(Function(t) t.IsKind(SyntaxKind.SkippedTokensTrivia)) Then
' If we had to skip tokens, we're probably just going to break more than we fix
Return Nothing
End If
' It's still missing entirely, so just spit normally
Return CreateSpitLinesForLambdaHeader(node.SubOrFunctionHeader, isNextToXmlEmbeddedExpression, originalNode.SpanStart)
End If
Dim newHeader = node.SubOrFunctionHeader.WithTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter))
Dim newBody = SyntaxFactory.ReturnStatement(SyntaxFactory.Token(SyntaxKind.ReturnKeyword).WithTrailingTrivia(SyntaxFactory.WhitespaceTrivia(" ")),
DirectCast(node.Body, ExpressionSyntax)) _
.WithPrependedLeadingTrivia(SyntaxFactory.WhitespaceTrivia(indentedWhitespace)) _
.WithAppendedTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter))
Dim newExpression = SyntaxFactory.MultiLineSubLambdaExpression(
subOrFunctionHeader:=newHeader,
statements:=SyntaxFactory.SingletonList(Of StatementSyntax)(newBody),
endSubOrFunctionStatement:=endStatement)
' Fish our body back out so we can figure out relative spans
newBody = DirectCast(newExpression.Statements.First(), ReturnStatementSyntax)
Return New ReplaceSpanResult(originalNode.FullSpan.ToSnapshotSpan(_subjectBuffer.CurrentSnapshot),
newExpression.ToFullString(),
newBody.ReturnKeyword.FullSpan.End)
End If
Return Nothing
End Function
Private Function SpitNormalLambdaEnding(node As LambdaHeaderSyntax) As AbstractEndConstructResult
Dim needsEnd = node.GetAncestorsOrThis(Of MultiLineLambdaExpressionSyntax)().Any(Function(block) block.EndSubOrFunctionStatement.IsMissing AndAlso block.IsMultiLineLambda())
' We have to be careful here: just because the Lambda's End isn't missing doesn't mean we shouldn't spit a
' End Sub / End Function. A good example is an unterminated multi-line sub in a sub, like this:
'
' Sub goo()
' Dim x = Sub()
' End Sub
'
' Obviously the parser has an ambiguity here, and so it chooses to parse the End Sub as being the terminator
' for the lambda. In this case, we'll notice that this lambda has a parent method body that uses the same
' Sub/Function keyword and is missing it's end construct, indicating that we should still spit.
Dim containingMethodBlock = node.GetAncestor(Of MethodBlockBaseSyntax)()
If containingMethodBlock IsNot Nothing AndAlso containingMethodBlock.EndBlockStatement.IsMissing Then
' Is this containing method the same type (Sub/Function) as the lambda?
If containingMethodBlock.BlockStatement.DeclarationKeyword.Kind = node.DeclarationKeyword.Kind Then
needsEnd = True
End If
End If
If needsEnd Then
Return CreateSpitLinesForLambdaHeader(node)
Else
Return Nothing
End If
End Function
Private Function CreateSpitLinesForLambdaHeader(node As LambdaHeaderSyntax, Optional isNextToXmlEmbeddedExpression As Boolean = False, Optional originalNodeSpanStart? As Integer = Nothing) As AbstractEndConstructResult
Dim spanStart As Integer = If(originalNodeSpanStart.HasValue, originalNodeSpanStart.Value, node.SpanStart)
Dim endConstruct = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(spanStart) & "End " & node.DeclarationKeyword.ToString()
' We may wish to spit () at the end of if we are missing our parenthesis
If node.ParameterList Is Nothing OrElse (node.ParameterList.OpenParenToken.IsMissing AndAlso node.ParameterList.CloseParenToken.IsMissing) Then
Return New SpitLinesResult({"()", "", endConstruct}, startOnCurrentLine:=True)
Else
Return New SpitLinesResult({"", If(isNextToXmlEmbeddedExpression, endConstruct & " ", endConstruct)})
End If
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
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Partial Friend Class EndConstructStatementVisitor
Public Overrides Function VisitLambdaHeader(node As LambdaHeaderSyntax) As AbstractEndConstructResult
Dim singleLineExpressionSyntax = TryCast(node.Parent, SingleLineLambdaExpressionSyntax)
If singleLineExpressionSyntax IsNot Nothing Then
Return TransformSingleLineLambda(singleLineExpressionSyntax)
Else
Return SpitNormalLambdaEnding(node)
End If
End Function
Private Function TransformSingleLineLambda(originalNode As SingleLineLambdaExpressionSyntax) As AbstractEndConstructResult
' If there is newline trivia on the end of the node, we need to pull that off to stick it back on at the very end of this transformation
Dim newLineTrivia = originalNode.GetTrailingTrivia().SkipWhile(Function(t) Not t.IsKind(SyntaxKind.EndOfLineTrivia))
Dim node = originalNode.WithTrailingTrivia(originalNode.GetTrailingTrivia().TakeWhile(Function(t) Not t.IsKind(SyntaxKind.EndOfLineTrivia)))
Dim tokenNextToLambda = originalNode.GetLastToken().GetNextToken()
Dim isNextToXmlEmbeddedExpression = tokenNextToLambda.IsKind(SyntaxKind.PercentGreaterThanToken) AndAlso tokenNextToLambda.Parent.IsKind(SyntaxKind.XmlEmbeddedExpression)
Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(originalNode.SpanStart)
Dim indentedWhitespace = aligningWhitespace & " "
' Generate the end statement since we can easily share that code
Dim endStatementKind = If(originalNode.Kind = SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.EndSubStatement, SyntaxKind.EndFunctionStatement)
Dim endStatement = SyntaxFactory.EndBlockStatement(endStatementKind, SyntaxFactory.Token(originalNode.SubOrFunctionHeader.DeclarationKeyword.Kind).WithLeadingTrivia(SyntaxFactory.WhitespaceTrivia(" "))) _
.WithLeadingTrivia(SyntaxFactory.WhitespaceTrivia(aligningWhitespace)) _
.WithTrailingTrivia(If(isNextToXmlEmbeddedExpression, SyntaxFactory.TriviaList(SyntaxFactory.WhitespaceTrivia(" ")), newLineTrivia))
' We are hitting enter after a single line. Let's transform it to a multi-line form
If node.Kind = SyntaxKind.SingleLineSubLambdaExpression Then
' If we have Sub() End Sub as a lambda, we're better off just doing nothing smart
If node.Body.IsKind(SyntaxKind.EndSubStatement) Then
Return Nothing
End If
' Update the new header
Dim newHeader = node.SubOrFunctionHeader
If newHeader.ParameterList Is Nothing OrElse
(newHeader.ParameterList.OpenParenToken.IsMissing AndAlso newHeader.ParameterList.CloseParenToken.IsMissing) Then
newHeader = newHeader.WithParameterList(SyntaxFactory.ParameterList())
End If
newHeader = newHeader.WithTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter))
' Update the body with a newline
Dim newBody = DirectCast(node.Body, StatementSyntax).WithAppendedTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter))
Dim newBodyHasCode = False
' If it actually contains something, intent it too. Otherwise, we'll just let the smart indenter position
If Not String.IsNullOrWhiteSpace(newBody.ToFullString()) Then
newBody = newBody.WithPrependedLeadingTrivia(SyntaxFactory.WhitespaceTrivia(indentedWhitespace))
newBodyHasCode = True
End If
Dim newExpression = SyntaxFactory.MultiLineSubLambdaExpression(
subOrFunctionHeader:=newHeader,
statements:=SyntaxFactory.SingletonList(newBody),
endSubOrFunctionStatement:=endStatement)
Return New ReplaceSpanResult(originalNode.FullSpan.ToSnapshotSpan(_subjectBuffer.CurrentSnapshot),
newExpression.ToFullString(),
If(newBodyHasCode, CType(newExpression.Statements.First().SpanStart, Integer?), Nothing))
Else
If node.Body.IsMissing Then
If node.Body.GetTrailingTrivia().Any(Function(t) t.IsKind(SyntaxKind.SkippedTokensTrivia)) Then
' If we had to skip tokens, we're probably just going to break more than we fix
Return Nothing
End If
' It's still missing entirely, so just spit normally
Return CreateSpitLinesForLambdaHeader(node.SubOrFunctionHeader, isNextToXmlEmbeddedExpression, originalNode.SpanStart)
End If
Dim newHeader = node.SubOrFunctionHeader.WithTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter))
Dim newBody = SyntaxFactory.ReturnStatement(SyntaxFactory.Token(SyntaxKind.ReturnKeyword).WithTrailingTrivia(SyntaxFactory.WhitespaceTrivia(" ")),
DirectCast(node.Body, ExpressionSyntax)) _
.WithPrependedLeadingTrivia(SyntaxFactory.WhitespaceTrivia(indentedWhitespace)) _
.WithAppendedTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter))
Dim newExpression = SyntaxFactory.MultiLineSubLambdaExpression(
subOrFunctionHeader:=newHeader,
statements:=SyntaxFactory.SingletonList(Of StatementSyntax)(newBody),
endSubOrFunctionStatement:=endStatement)
' Fish our body back out so we can figure out relative spans
newBody = DirectCast(newExpression.Statements.First(), ReturnStatementSyntax)
Return New ReplaceSpanResult(originalNode.FullSpan.ToSnapshotSpan(_subjectBuffer.CurrentSnapshot),
newExpression.ToFullString(),
newBody.ReturnKeyword.FullSpan.End)
End If
Return Nothing
End Function
Private Function SpitNormalLambdaEnding(node As LambdaHeaderSyntax) As AbstractEndConstructResult
Dim needsEnd = node.GetAncestorsOrThis(Of MultiLineLambdaExpressionSyntax)().Any(Function(block) block.EndSubOrFunctionStatement.IsMissing AndAlso block.IsMultiLineLambda())
' We have to be careful here: just because the Lambda's End isn't missing doesn't mean we shouldn't spit a
' End Sub / End Function. A good example is an unterminated multi-line sub in a sub, like this:
'
' Sub goo()
' Dim x = Sub()
' End Sub
'
' Obviously the parser has an ambiguity here, and so it chooses to parse the End Sub as being the terminator
' for the lambda. In this case, we'll notice that this lambda has a parent method body that uses the same
' Sub/Function keyword and is missing it's end construct, indicating that we should still spit.
Dim containingMethodBlock = node.GetAncestor(Of MethodBlockBaseSyntax)()
If containingMethodBlock IsNot Nothing AndAlso containingMethodBlock.EndBlockStatement.IsMissing Then
' Is this containing method the same type (Sub/Function) as the lambda?
If containingMethodBlock.BlockStatement.DeclarationKeyword.Kind = node.DeclarationKeyword.Kind Then
needsEnd = True
End If
End If
If needsEnd Then
Return CreateSpitLinesForLambdaHeader(node)
Else
Return Nothing
End If
End Function
Private Function CreateSpitLinesForLambdaHeader(node As LambdaHeaderSyntax, Optional isNextToXmlEmbeddedExpression As Boolean = False, Optional originalNodeSpanStart? As Integer = Nothing) As AbstractEndConstructResult
Dim spanStart As Integer = If(originalNodeSpanStart.HasValue, originalNodeSpanStart.Value, node.SpanStart)
Dim endConstruct = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(spanStart) & "End " & node.DeclarationKeyword.ToString()
' We may wish to spit () at the end of if we are missing our parenthesis
If node.ParameterList Is Nothing OrElse (node.ParameterList.OpenParenToken.IsMissing AndAlso node.ParameterList.CloseParenToken.IsMissing) Then
Return New SpitLinesResult({"()", "", endConstruct}, startOnCurrentLine:=True)
Else
Return New SpitLinesResult({"", If(isNextToXmlEmbeddedExpression, endConstruct & " ", endConstruct)})
End If
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/CSharp/Test/Semantic/Semantics/PatternMatchingTests_Scope.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.Patterns)]
public class PatternMatchingTests_Scope : PatternMatchingTestBase
{
[Fact]
[WorkItem(13029, "https://github.com/dotnet/roslyn/issues/13029")]
public void ScopeOfLocalFunction()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test14(int val)
{
switch (val)
{
case 1 when TakeOutParam(true, out var x14):
void x14() {return;};
break;
case 2:
x14();
break;
}
switch (val)
{
case 1 when Dummy(1 is var x14):
void x14() {return;};
break;
case 2:
x14();
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,52): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when TakeOutParam(true, out var x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(14, 52),
// (24,40): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(1 is var x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(24, 40));
}
[Fact]
public void ScopeOfPatternVariables_ExpressionStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
Dummy(true is var x1, x1);
{
Dummy(true is var x1, x1);
}
Dummy(true is var x1, x1);
}
void Test2()
{
Dummy(x2, true is var x2);
}
void Test3(int x3)
{
Dummy(true is var x3, x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
Dummy(true is var x4, x4);
}
void Test5()
{
Dummy(true is var x5, x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
// Dummy(true is var x6, x6);
//}
//void Test7()
//{
// Dummy(true is var x7, x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
Dummy(true is var x8, x8, false is var x8, x8);
}
void Test9(bool y9)
{
if (y9)
Dummy(true is var x9, x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
Dummy(true is var x10, x10);
};
}
void Test11()
{
Dummy(x11);
Dummy(true is var x11, x11);
}
void Test12()
{
Dummy(true is var x12, x12);
Dummy(x12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (14,31): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 31),
// (16,27): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 27),
// (21,15): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2, true is var x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15),
// (26,27): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x3, x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 27),
// (33,27): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 27),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,48): error CS0128: A local variable or function named 'x8' is already defined in this scope
// Dummy(true is var x8, x8, false is var x8, x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 48),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref);
}
[Fact]
public void ScopeOfPatternVariables_ExpressionStatement_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(2 is var x1);
System.Console.WriteLine(x1);
}
static object Test1(bool x)
{
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_ExpressionStatement_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
bool test = true;
if (test)
Test2(1 is var x1, x1);
if (test)
{
Test2(2 is var x1, x1);
}
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "12").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_ExpressionStatement_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
if (true)
Dummy(true is var x1);
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_ExpressionStatement_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@"
Dummy(11 is var x1, x1);
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact, WorkItem(9258, "https://github.com/dotnet/roslyn/issues/9258")]
public void PatternVariableOrder()
{
var source =
@"
public class X
{
public static void Main()
{
}
static void Dummy(params object[] x) {}
void Test1(object o1, object o2)
{
Dummy(o1 is int i && i < 10,
o2 is int @i && @i > 10);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,25): error CS0128: A local variable named 'i' is already defined in this scope
// o2 is int @i && @i > 10);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "@i").WithArguments("i").WithLocation(13, 25),
// (13,31): error CS0165: Use of unassigned local variable 'i'
// o2 is int @i && @i > 10);
Diagnostic(ErrorCode.ERR_UseDefViolation, "@i").WithArguments("i").WithLocation(13, 31)
);
}
[Fact]
public void ScopeOfPatternVariables_ReturnStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null; }
object Test1()
{
return Dummy(true is var x1, x1);
{
return Dummy(true is var x1, x1);
}
return Dummy(true is var x1, x1);
}
object Test2()
{
return Dummy(x2, true is var x2);
}
object Test3(int x3)
{
return Dummy(true is var x3, x3);
}
object Test4()
{
var x4 = 11;
Dummy(x4);
return Dummy(true is var x4, x4);
}
object Test5()
{
return Dummy(true is var x5, x5);
var x5 = 11;
Dummy(x5);
}
//object Test6()
//{
// let x6 = 11;
// Dummy(x6);
// return Dummy(true is var x6, x6);
//}
//object Test7()
//{
// return Dummy(true is var x7, x7);
// let x7 = 11;
// Dummy(x7);
//}
object Test8()
{
return Dummy(true is var x8, x8, false is var x8, x8);
}
object Test9(bool y9)
{
if (y9)
return Dummy(true is var x9, x9);
return null;
}
System.Func<object> Test10(bool y10)
{
return () =>
{
if (y10)
return Dummy(true is var x10, x10);
return null;};
}
object Test11()
{
Dummy(x11);
return Dummy(true is var x11, x11);
}
object Test12()
{
return Dummy(true is var x12, x12);
Dummy(x12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (14,38): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// return Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 38),
// (16,34): error CS0128: A local variable or function named 'x1' is already defined in this scope
// return Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 34),
// (14,13): warning CS0162: Unreachable code detected
// return Dummy(true is var x1, x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(14, 13),
// (21,22): error CS0841: Cannot use local variable 'x2' before it is declared
// return Dummy(x2, true is var x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 22),
// (26,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// return Dummy(true is var x3, x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 34),
// (33,34): error CS0128: A local variable or function named 'x4' is already defined in this scope
// return Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 34),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,9): warning CS0162: Unreachable code detected
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,55): error CS0128: A local variable or function named 'x8' is already defined in this scope
// return Dummy(true is var x8, x8, false is var x8, x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 55),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (86,9): warning CS0162: Unreachable code detected
// Dummy(x12);
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref);
}
[Fact]
public void ScopeOfPatternVariables_ReturnStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
int Dummy(params object[] x) {return 0;}
int Test1(bool val)
{
if (val)
return Dummy(true is var x1);
x1++;
return 0;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_ReturnStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ReturnStatementSyntax)SyntaxFactory.ParseStatement(@"
return Dummy(11 is var x1, x1);
");
bool success = model.TryGetSpeculativeSemanticModel(
tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_ThrowStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Exception Dummy(params object[] x) { return null;}
void Test1()
{
throw Dummy(true is var x1, x1);
{
throw Dummy(true is var x1, x1);
}
throw Dummy(true is var x1, x1);
}
void Test2()
{
throw Dummy(x2, true is var x2);
}
void Test3(int x3)
{
throw Dummy(true is var x3, x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
throw Dummy(true is var x4, x4);
}
void Test5()
{
throw Dummy(true is var x5, x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
// throw Dummy(true is var x6, x6);
//}
//void Test7()
//{
// throw Dummy(true is var x7, x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
throw Dummy(true is var x8, x8, false is var x8, x8);
}
void Test9(bool y9)
{
if (y9)
throw Dummy(true is var x9, x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
throw Dummy(true is var x10, x10);
};
}
void Test11()
{
Dummy(x11);
throw Dummy(true is var x11, x11);
}
void Test12()
{
throw Dummy(true is var x12, x12);
Dummy(x12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (14,37): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// throw Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 37),
// (16,33): error CS0128: A local variable or function named 'x1' is already defined in this scope
// throw Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 33),
// (21,21): error CS0841: Cannot use local variable 'x2' before it is declared
// throw Dummy(x2, true is var x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 21),
// (26,33): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// throw Dummy(true is var x3, x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 33),
// (33,33): error CS0128: A local variable or function named 'x4' is already defined in this scope
// throw Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 33),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,9): warning CS0162: Unreachable code detected
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,54): error CS0128: A local variable or function named 'x8' is already defined in this scope
// throw Dummy(true is var x8, x8, false is var x8, x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 54),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (86,9): warning CS0162: Unreachable code detected
// Dummy(x12);
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref);
}
[Fact]
public void ScopeOfPatternVariables_ThrowStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Exception Dummy(params object[] x) { return null;}
void Test1(bool val)
{
if (val)
throw Dummy(true is var x1);
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_TrowStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ThrowStatementSyntax)SyntaxFactory.ParseStatement(@"
throw Dummy(11 is var x1, x1);
");
bool success = model.TryGetSpeculativeSemanticModel(
tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact, WorkItem(9121, "https://github.com/dotnet/roslyn/issues/9121")]
public void ScopeOfPatternVariables_If_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true is var x1)
{
Dummy(x1);
}
else
{
System.Console.WriteLine(x1);
}
}
void Test2()
{
if (true is var x2)
Dummy(x2);
else
System.Console.WriteLine(x2);
}
void Test3()
{
if (true is var x3)
Dummy(x3);
else
{
var x3 = 12;
System.Console.WriteLine(x3);
}
}
void Test4()
{
var x4 = 11;
Dummy(x4);
if (true is var x4)
Dummy(x4);
}
void Test5(int x5)
{
if (true is var x5)
Dummy(x5);
}
void Test6()
{
if (x6 && true is var x6)
Dummy(x6);
}
void Test7()
{
if (true is var x7 && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
if (true is var x8)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
if (true is var x9)
{
Dummy(x9);
if (true is var x9) // 2
Dummy(x9);
}
}
void Test10()
{
if (y10 is var x10)
{
var y10 = 12;
Dummy(y10);
}
}
void Test12()
{
if (y12 is var x12)
var y12 = 12;
}
//void Test13()
//{
// if (y13 is var x13)
// let y13 = 12;
//}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (110,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(110, 13),
// (36,17): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x3 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(36, 17),
// (46,25): error CS0128: A local variable named 'x4' is already defined in this scope
// if (true is var x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(46, 25),
// (52,25): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// if (true is var x5)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(52, 25),
// (58,13): error CS0841: Cannot use local variable 'x6' before it is declared
// if (x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(58, 13),
// (66,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(66, 17),
// (83,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(83, 19),
// (84,29): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// if (true is var x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(84, 29),
// (91,13): error CS0103: The name 'y10' does not exist in the current context
// if (y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(91, 13),
// (109,13): error CS0103: The name 'y12' does not exist in the current context
// if (y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(109, 13),
// (110,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(110, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref[0]);
VerifyNotAPatternLocal(model, x3Ref[1]);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
}
[Fact]
public void ScopeOfPatternVariables_If_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
if (true is var x1)
{
}
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (17,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_If_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (IfStatementSyntax)SyntaxFactory.ParseStatement(@"
if (Dummy(11 is var x1, x1));
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_Lambda_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
System.Action<object> Test1()
{
return (o) => let x1 = o;
}
System.Action<object> Test2()
{
return (o) => let var x2 = o;
}
void Test3()
{
Dummy((System.Func<object, bool>) (o => o is int x3 && x3 > 0));
}
void Test4()
{
Dummy((System.Func<object, bool>) (o => x4 && o is int x4));
}
void Test5()
{
Dummy((System.Func<object, object, bool>) ((o1, o2) => o1 is int x5 &&
o2 is int x5 &&
x5 > 0));
}
void Test6()
{
Dummy((System.Func<object, bool>) (o => o is int x6 && x6 > 0), (System.Func<object, bool>) (o => o is int x6 && x6 > 0));
}
void Test7()
{
Dummy(x7, 1);
Dummy(x7,
(System.Func<object, bool>) (o => o is int x7 && x7 > 0),
x7);
Dummy(x7, 2);
}
void Test8()
{
Dummy(true is var x8 && x8, (System.Func<object, bool>) (o => o is int y8 && x8));
}
void Test9()
{
Dummy(true is var x9,
(System.Func<object, bool>) (o => o is int x9 &&
x9 > 0), x9);
}
void Test10()
{
Dummy((System.Func<object, bool>) (o => o is int x10 &&
x10 > 0),
true is var x10, x10);
}
void Test11()
{
var x11 = 11;
Dummy(x11);
Dummy((System.Func<object, bool>) (o => o is int x11 &&
x11 > 0), x11);
}
void Test12()
{
Dummy((System.Func<object, bool>) (o => o is int x12 &&
x12 > 0),
x12);
var x12 = 11;
Dummy(x12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (12,27): error CS1002: ; expected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27),
// (17,27): error CS1002: ; expected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27),
// (12,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23),
// (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23),
// (12,27): error CS0103: The name 'x1' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27),
// (12,32): error CS0103: The name 'o' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32),
// (12,27): warning CS0162: Unreachable code detected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27),
// (17,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23),
// (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23),
// (17,36): error CS0103: The name 'o' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36),
// (17,27): warning CS0162: Unreachable code detected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27),
// (27,49): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && o is int x4));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49),
// (33,74): error CS0128: A local variable or function named 'x5' is already defined in this scope
// o2 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 74),
// (44,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15),
// (45,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15),
// (47,15): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15),
// (48,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15),
// (82,15): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15)
);
compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (12,27): error CS1002: ; expected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27),
// (17,27): error CS1002: ; expected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27),
// (12,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23),
// (12,23): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23),
// (12,27): error CS0103: The name 'x1' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27),
// (12,32): error CS0103: The name 'o' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32),
// (12,27): warning CS0162: Unreachable code detected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27),
// (17,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23),
// (17,23): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23),
// (17,36): error CS0103: The name 'o' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36),
// (17,27): warning CS0162: Unreachable code detected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27),
// (27,49): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && o is int x4));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49),
// (33,74): error CS0128: A local variable or function named 'x5' is already defined in this scope
// o2 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 74),
// (44,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15),
// (45,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15),
// (47,15): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15),
// (48,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15),
// (59,58): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// (System.Func<object, bool>) (o => o is int x9 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(59, 58),
// (65,58): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => o is int x10 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(65, 58),
// (74,58): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => o is int x11 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(74, 58),
// (80,58): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => o is int x12 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(80, 58),
// (82,15): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetPatternDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl[0], x10Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAPatternLocal(model, x11Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref[1]);
VerifyNotAPatternLocal(model, x11Ref[2]);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref[0]);
VerifyNotAPatternLocal(model, x12Ref[1]);
VerifyNotAPatternLocal(model, x12Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_Query_01()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x in new[] { 1 is var y1 ? y1 : 0, y1}
select x + y1;
Dummy(y1);
}
void Test2()
{
var res = from x1 in new[] { 1 is var y2 ? y2 : 0}
from x2 in new[] { x1 is var z2 ? z2 : 0, z2, y2}
select x1 + x2 + y2 +
z2;
Dummy(z2);
}
void Test3()
{
var res = from x1 in new[] { 1 is var y3 ? y3 : 0}
let x2 = x1 is var z3 && z3 > 0 && y3 < 0
select new { x1, x2, y3,
z3};
Dummy(z3);
}
void Test4()
{
var res = from x1 in new[] { 1 is var y4 ? y4 : 0}
join x2 in new[] { 2 is var z4 ? z4 : 0, z4, y4}
on x1 + y4 + z4 + 3 is var u4 ? u4 : 0 +
v4
equals x2 + y4 + z4 + 4 is var v4 ? v4 : 0 +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
}
void Test5()
{
var res = from x1 in new[] { 1 is var y5 ? y5 : 0}
join x2 in new[] { 2 is var z5 ? z5 : 0, z5, y5}
on x1 + y5 + z5 + 3 is var u5 ? u5 : 0 +
v5
equals x2 + y5 + z5 + 4 is var v5 ? v5 : 0 +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
}
void Test6()
{
var res = from x in new[] { 1 is var y6 ? y6 : 0}
where x > y6 && 1 is var z6 && z6 == 1
select x + y6 +
z6;
Dummy(z6);
}
void Test7()
{
var res = from x in new[] { 1 is var y7 ? y7 : 0}
orderby x > y7 && 1 is var z7 && z7 ==
u7,
x > y7 && 1 is var u7 && u7 ==
z7
select x + y7 +
z7 + u7;
Dummy(z7);
Dummy(u7);
}
void Test8()
{
var res = from x in new[] { 1 is var y8 ? y8 : 0}
select x > y8 && 1 is var z8 && z8 == 1;
Dummy(z8);
}
void Test9()
{
var res = from x in new[] { 1 is var y9 ? y9 : 0}
group x > y9 && 1 is var z9 && z9 ==
u9
by
x > y9 && 1 is var u9 && u9 ==
z9;
Dummy(z9);
Dummy(u9);
}
void Test10()
{
var res = from x1 in new[] { 1 is var y10 ? y10 : 0}
from y10 in new[] { 1 }
select x1 + y10;
}
void Test11()
{
var res = from x1 in new[] { 1 is var y11 ? y11 : 0}
let y11 = x1 + 1
select x1 + y11;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (25,26): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(25, 26),
// (27,15): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(27, 15),
// (35,32): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(35, 32),
// (37,15): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(37, 15),
// (45,35): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(45, 35),
// (47,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(47, 35),
// (49,32): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(49, 32),
// (49,36): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(49, 36),
// (52,15): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(52, 15),
// (53,15): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(53, 15),
// (61,35): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(61, 35),
// (63,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(63, 35),
// (66,32): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(66, 32),
// (66,36): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(66, 36),
// (69,15): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(69, 15),
// (70,15): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(70, 15),
// (78,26): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(78, 26),
// (80,15): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(80, 15),
// (87,27): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(87, 27),
// (89,27): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(89, 27),
// (91,26): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(91, 26),
// (91,31): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(91, 31),
// (93,15): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(93, 15),
// (94,15): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(94, 15),
// (102,15): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(102, 15),
// (112,25): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(112, 25),
// (109,25): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(109, 25),
// (114,15): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(114, 15),
// (115,15): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(115, 15),
// (121,24): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10'
// from y10 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(121, 24),
// (128,23): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11'
// let y11 = x1 + 1
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(128, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetPatternDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y1Decl, y1Ref);
var y2Decl = GetPatternDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y2Decl, y2Ref);
var z2Decl = GetPatternDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetPatternDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y3Decl, y3Ref);
var z3Decl = GetPatternDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetPatternDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y4Decl, y4Ref);
var z4Decl = GetPatternDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z4Decl, z4Ref);
var u4Decl = GetPatternDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetPatternDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetPatternDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y5Decl, y5Ref);
var z5Decl = GetPatternDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z5Decl, z5Ref);
var u5Decl = GetPatternDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetPatternDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetPatternDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y6Decl, y6Ref);
var z6Decl = GetPatternDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetPatternDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y7Decl, y7Ref);
var z7Decl = GetPatternDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetPatternDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetPatternDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y8Decl, y8Ref);
var z8Decl = GetPatternDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetPatternDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y9Decl, y9Ref);
var z9Decl = GetPatternDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetPatternDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetPatternDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y10Decl, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y11Decl = GetPatternDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y11Decl, y11Ref[0]);
VerifyNotAPatternLocal(model, y11Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_Query_03()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test4()
{
var res = from x1 in new[] { 1 is var y4 ? y4 : 0}
select x1 into x1
join x2 in new[] { 2 is var z4 ? z4 : 0, z4, y4}
on x1 + y4 + z4 + 3 is var u4 ? u4 : 0 +
v4
equals x2 + y4 + z4 + 4 is var v4 ? v4 : 0 +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
}
void Test5()
{
var res = from x1 in new[] { 1 is var y5 ? y5 : 0}
select x1 into x1
join x2 in new[] { 2 is var z5 ? z5 : 0, z5, y5}
on x1 + y5 + z5 + 3 is var u5 ? u5 : 0 +
v5
equals x2 + y5 + z5 + 4 is var v5 ? v5 : 0 +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (18,35): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(18, 35),
// (20,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(20, 35),
// (22,32): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(22, 32),
// (22,36): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(22, 36),
// (25,15): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(25, 15),
// (26,15): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(26, 15),
// (35,35): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(35, 35),
// (37,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(37, 35),
// (40,32): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(40, 32),
// (40,36): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(40, 36),
// (43,15): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(43, 15),
// (44,15): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(44, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y4Decl = GetPatternDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y4Decl, y4Ref);
var z4Decl = GetPatternDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z4Decl, z4Ref);
var u4Decl = GetPatternDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetPatternDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetPatternDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y5Decl, y5Ref);
var z5Decl = GetPatternDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z5Decl, z5Ref);
var u5Decl = GetPatternDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetPatternDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void ScopeOfPatternVariables_Query_05()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
int y1 = 0, y2 = 0, y3 = 0, y4 = 0, y5 = 0, y6 = 0, y7 = 0, y8 = 0, y9 = 0, y10 = 0, y11 = 0, y12 = 0;
var res = from x1 in new[] { 1 is var y1 ? y1 : 0}
from x2 in new[] { 2 is var y2 ? y2 : 0}
join x3 in new[] { 3 is var y3 ? y3 : 0}
on 4 is var y4 ? y4 : 0
equals 5 is var y5 ? y5 : 0
where 6 is var y6 && y6 == 1
orderby 7 is var y7 && y7 > 0,
8 is var y8 && y8 > 0
group 9 is var y9 && y9 > 0
by 10 is var y10 && y10 > 0
into g
let x11 = 11 is var y11 && y11 > 0
select 12 is var y12 && y12 > 0
into s
select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12;
Dummy(y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (16,47): error CS0128: A local variable or function named 'y1' is already defined in this scope
// var res = from x1 in new[] { 1 is var y1 ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 47),
// (18,47): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { 3 is var y3 ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 47)
);
compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (16,47): error CS0128: A local variable or function named 'y1' is already defined in this scope
// var res = from x1 in new[] { 1 is var y1 ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 47),
// (17,47): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { 2 is var y2 ? y2 : 0}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(17, 47),
// (18,47): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { 3 is var y3 ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 47),
// (19,36): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on 4 is var y4 ? y4 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(19, 36),
// (20,43): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals 5 is var y5 ? y5 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(20, 43),
// (21,34): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where 6 is var y6 && y6 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(21, 34),
// (22,36): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby 7 is var y7 && y7 > 0,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(22, 36),
// (23,36): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// 8 is var y8 && y8 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(23, 36),
// (25,32): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by 10 is var y10 && y10 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(25, 32),
// (24,34): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group 9 is var y9 && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(24, 34),
// (27,39): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x11 = 11 is var y11 && y11 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(27, 39),
// (28,36): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select 12 is var y12 && y12 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(28, 36)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetPatternDeclarations(tree, id).Single();
var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).ToArray();
Assert.Equal(3, yRef.Length);
switch (i)
{
case 1:
case 3:
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, yDecl);
VerifyNotAPatternLocal(model, yRef[0]);
break;
default:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef[0]);
break;
}
VerifyNotAPatternLocal(model, yRef[2]);
switch (i)
{
case 1:
case 3:
case 12:
VerifyNotAPatternLocal(model, yRef[1]);
break;
default:
VerifyNotAPatternLocal(model, yRef[1]);
break;
}
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void ScopeOfPatternVariables_Query_06()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
Dummy(1 is int y1,
2 is int y2,
3 is int y3,
4 is int y4,
5 is int y5,
6 is int y6,
7 is int y7,
8 is int y8,
9 is int y9,
10 is int y10,
11 is int y11,
12 is int y12,
from x1 in new[] { 1 is var y1 ? y1 : 0}
from x2 in new[] { 2 is var y2 ? y2 : 0}
join x3 in new[] { 3 is var y3 ? y3 : 0}
on 4 is var y4 ? y4 : 0
equals 5 is var y5 ? y5 : 0
where 6 is var y6 && y6 == 1
orderby 7 is var y7 && y7 > 0,
8 is var y8 && y8 > 0
group 9 is var y9 && y9 > 0
by 10 is var y10 && y10 > 0
into g
let x11 = 11 is var y11 && y11 > 0
select 12 is var y12 && y12 > 0
into s
select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (26,47): error CS0128: A local variable or function named 'y1' is already defined in this scope
// from x1 in new[] { 1 is var y1 ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 47),
// (28,47): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { 3 is var y3 ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 47)
);
compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (26,47): error CS0128: A local variable or function named 'y1' is already defined in this scope
// from x1 in new[] { 1 is var y1 ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 47),
// (27,47): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { 2 is var y2 ? y2 : 0}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(27, 47),
// (28,47): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { 3 is var y3 ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 47),
// (29,36): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on 4 is var y4 ? y4 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(29, 36),
// (30,43): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals 5 is var y5 ? y5 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(30, 43),
// (31,34): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where 6 is var y6 && y6 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(31, 34),
// (32,36): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby 7 is var y7 && y7 > 0,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(32, 36),
// (33,36): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// 8 is var y8 && y8 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(33, 36),
// (35,32): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by 10 is var y10 && y10 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(35, 32),
// (34,34): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group 9 is var y9 && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(34, 34),
// (37,39): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x11 = 11 is var y11 && y11 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(37, 39),
// (38,36): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select 12 is var y12 && y12 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(38, 36)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetPatternDeclarations(tree, id).ToArray();
var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).ToArray();
Assert.Equal(2, yDecl.Length);
Assert.Equal(2, yRef.Length);
switch (i)
{
case 1:
case 3:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl[0], yRef);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, yDecl[1]);
break;
case 12:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl[0], yRef[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl[1], yRef[0]);
break;
default:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl[0], yRef[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl[1], yRef[0]);
break;
}
}
}
[Fact]
public void ScopeOfPatternVariables_Query_07()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
Dummy(7 is int y3,
from x1 in new[] { 0 }
select x1
into x1
join x3 in new[] { 3 is var y3 ? y3 : 0}
on x1 equals x3
select y3);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (18,47): error CS0128: A local variable named 'y3' is already defined in this scope
// join x3 in new[] { 3 is var y3 ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
const string id = "y3";
var yDecl = GetPatternDeclarations(tree, id).ToArray();
var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).ToArray();
Assert.Equal(2, yDecl.Length);
Assert.Equal(2, yRef.Length);
// Since the name is declared twice in the same scope,
// both references are to the same declaration.
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl[0], yRef);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, yDecl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Query_08()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x1 in new[] { Dummy(1 is var y1,
2 is var y2,
3 is var y3,
4 is var y4
) ? 1 : 0}
from y1 in new[] { 1 }
join y2 in new[] { 0 }
on y1 equals y2
let y3 = 0
group y3
by x1
into y4
select y4;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (19,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1'
// from y1 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(19, 24),
// (20,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2'
// join y2 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(20, 24),
// (22,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3'
// let y3 = 0
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(22, 23),
// (25,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4'
// into y4
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(25, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 5; i++)
{
var id = "y" + i;
var yDecl = GetPatternDeclarations(tree, id).Single();
var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).Single();
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl);
VerifyNotAPatternLocal(model, yRef);
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void ScopeOfPatternVariables_Query_09()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from y1 in new[] { 0 }
join y2 in new[] { 0 }
on y1 equals y2
let y3 = 0
group y3
by 1
into y4
select y4 == null ? 1 : 0
into x2
join y5 in new[] { Dummy(1 is var y1,
2 is var y2,
3 is var y3,
4 is var y4,
5 is var y5
) ? 1 : 0 }
on x2 equals y5
select x2;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (14,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1'
// var res = from y1 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(14, 24),
// (15,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2'
// join y2 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(15, 24),
// (17,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3'
// let y3 = 0
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(17, 23),
// (20,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4'
// into y4
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(20, 24),
// (23,24): error CS1931: The range variable 'y5' conflicts with a previous declaration of 'y5'
// join y5 in new[] { Dummy(1 is var y1,
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y5").WithArguments("y5").WithLocation(23, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 6; i++)
{
var id = "y" + i;
var yDecl = GetPatternDeclarations(tree, id).Single();
var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).Single();
switch (i)
{
case 4:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl);
VerifyNotAPatternLocal(model, yRef);
break;
case 5:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl);
VerifyNotAPatternLocal(model, yRef);
break;
default:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl);
VerifyNotAPatternLocal(model, yRef);
break;
}
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
[WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")]
public void ScopeOfPatternVariables_Query_10()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from y1 in new[] { 0 }
from x2 in new[] { 1 is var y1 ? y1 : 1 }
select y1;
}
void Test2()
{
var res = from y2 in new[] { 0 }
join x3 in new[] { 1 }
on 2 is var y2 ? y2 : 0
equals x3
select y2;
}
void Test3()
{
var res = from x3 in new[] { 0 }
join y3 in new[] { 1 }
on x3
equals 3 is var y3 ? y3 : 0
select y3;
}
void Test4()
{
var res = from y4 in new[] { 0 }
where 4 is var y4 && y4 == 1
select y4;
}
void Test5()
{
var res = from y5 in new[] { 0 }
orderby 5 is var y5 && y5 > 1,
1
select y5;
}
void Test6()
{
var res = from y6 in new[] { 0 }
orderby 1,
6 is var y6 && y6 > 1
select y6;
}
void Test7()
{
var res = from y7 in new[] { 0 }
group 7 is var y7 && y7 == 3
by y7;
}
void Test8()
{
var res = from y8 in new[] { 0 }
group y8
by 8 is var y8 && y8 == 3;
}
void Test9()
{
var res = from y9 in new[] { 0 }
let x4 = 9 is var y9 && y9 > 0
select y9;
}
void Test10()
{
var res = from y10 in new[] { 0 }
select 10 is var y10 && y10 > 0;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
// error CS0412 is misleading and reported due to preexisting bug https://github.com/dotnet/roslyn/issues/12052
compilation.VerifyDiagnostics(
// (15,47): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { 1 is var y1 ? y1 : 1 }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(15, 47),
// (23,36): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on 2 is var y2 ? y2 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(23, 36),
// (33,40): error CS0136: A local or parameter named 'y3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals 3 is var y3 ? y3 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y3").WithArguments("y3").WithLocation(33, 40),
// (40,34): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where 4 is var y4 && y4 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(40, 34),
// (47,36): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby 5 is var y5 && y5 > 1,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(47, 36),
// (56,36): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// 6 is var y6 && y6 > 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(56, 36),
// (63,34): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group 7 is var y7 && y7 == 3
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(63, 34),
// (71,31): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by 8 is var y8 && y8 == 3;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(71, 31),
// (77,37): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x4 = 9 is var y9 && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(77, 37),
// (84,36): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select 10 is var y10 && y10 > 0;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(84, 36)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 11; i++)
{
var id = "y" + i;
var yDecl = GetPatternDeclarations(tree, id).Single();
var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).ToArray();
Assert.Equal(i == 10 ? 1 : 2, yRef.Length);
switch (i)
{
case 4:
case 6:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef[0]);
VerifyNotAPatternLocal(model, yRef[1]);
break;
case 8:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef[1]);
VerifyNotAPatternLocal(model, yRef[0]);
break;
case 10:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef[0]);
break;
default:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef[0]);
VerifyNotAPatternLocal(model, yRef[1]);
break;
}
}
}
[Fact]
public void ScopeOfPatternVariables_Query_11()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x1 in new [] { 1 }
where Dummy(x1 is var y1,
from x2 in new [] { 1 }
where x1 is var y1
select x2)
select x1;
}
void Test2()
{
var res = from x1 in new [] { 1 }
where Dummy(x1 is var y2,
x1 + 1 is var y2)
select x1;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (26,45): error CS0128: A local variable or function named 'y2' is already defined in this scope
// x1 + 1 is var y2)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 45)
);
compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (17,47): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where x1 is var y1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(17, 47),
// (26,45): error CS0128: A local variable or function named 'y2' is already defined in this scope
// x1 + 1 is var y2)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 45)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetPatternDeclarations(tree, "y1").ToArray();
Assert.Equal(2, y1Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y1Decl[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, y1Decl[1]);
var y2Decl = GetPatternDeclarations(tree, "y2").ToArray();
Assert.Equal(2, y2Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y2Decl[0]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, y2Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_ExpressionBodiedLocalFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
void f(object o) => let x1 = o;
f(null);
}
void Test2()
{
void f(object o) => let var x2 = o;
f(null);
}
void Test3()
{
bool f (object o) => o is int x3 && x3 > 0;
f(null);
}
void Test4()
{
bool f (object o) => x4 && o is int x4;
f(null);
}
void Test5()
{
bool f (object o1, object o2) => o1 is int x5 &&
o2 is int x5 &&
x5 > 0;
f(null, null);
}
void Test6()
{
bool f1 (object o) => o is int x6 && x6 > 0; bool f2 (object o) => o is int x6 && x6 > 0;
f1(null);
f2(null);
}
void Test7()
{
Dummy(x7, 1);
bool f (object o) => o is int x7 && x7 > 0;
Dummy(x7, 2);
f(null);
}
void Test11()
{
var x11 = 11;
Dummy(x11);
bool f (object o) => o is int x11 &&
x11 > 0;
f(null);
}
void Test12()
{
bool f (object o) => o is int x12 &&
x12 > 0;
var x12 = 11;
Dummy(x12);
f(null);
}
System.Action Test13()
{
return () =>
{
bool f (object o) => o is int x13 && x13 > 0;
f(null);
};
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (12,33): error CS1002: ; expected
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 33),
// (18,33): error CS1002: ; expected
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(18, 33),
// (12,29): error CS0103: The name 'let' does not exist in the current context
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 29),
// (12,29): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 29),
// (12,33): error CS0103: The name 'x1' does not exist in the current context
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 33),
// (12,38): error CS0103: The name 'o' does not exist in the current context
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 38),
// (18,29): error CS0103: The name 'let' does not exist in the current context
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(18, 29),
// (18,29): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(18, 29),
// (18,42): error CS0103: The name 'o' does not exist in the current context
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(18, 42),
// (30,30): error CS0841: Cannot use local variable 'x4' before it is declared
// bool f (object o) => x4 && o is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(30, 30),
// (37,52): error CS0128: A local variable or function named 'x5' is already defined in this scope
// o2 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(37, 52),
// (51,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(51, 15),
// (55,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(55, 15)
);
compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (12,29): error CS0103: The name 'let' does not exist in the current context
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 29),
// (12,29): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 29),
// (12,33): error CS1002: ; expected
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 33),
// (12,33): error CS0103: The name 'x1' does not exist in the current context
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 33),
// (12,38): error CS0103: The name 'o' does not exist in the current context
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 38),
// (18,29): error CS0103: The name 'let' does not exist in the current context
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(18, 29),
// (18,29): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(18, 29),
// (18,33): error CS1002: ; expected
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(18, 33),
// (18,42): error CS0103: The name 'o' does not exist in the current context
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(18, 42),
// (30,30): error CS0841: Cannot use local variable 'x4' before it is declared
// bool f (object o) => x4 && o is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(30, 30),
// (37,52): error CS0128: A local variable or function named 'x5' is already defined in this scope
// o2 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(37, 52),
// (51,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(51, 15),
// (55,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(55, 15),
// (63,39): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool f (object o) => o is int x11 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(63, 39),
// (70,39): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool f (object o) => o is int x12 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(70, 39)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyNotAPatternLocal(model, x11Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref[1]);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref[0]);
VerifyNotAPatternLocal(model, x12Ref[1]);
var x13Decl = GetPatternDeclarations(tree, "x13").Single();
var x13Ref = GetReferences(tree, "x13").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl, x13Ref);
}
[Fact]
public void ExpressionBodiedLocalFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
bool f() => 1 is int x1 && Dummy(x1);
return f();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void ScopeOfPatternVariables_ExpressionBodiedFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1(object o) => let x1 = o;
void Test2(object o) => let var x2 = o;
bool Test3(object o) => o is int x3 && x3 > 0;
bool Test4(object o) => x4 && o is int x4;
bool Test5(object o1, object o2) => o1 is int x5 &&
o2 is int x5 &&
x5 > 0;
bool Test61 (object o) => o is int x6 && x6 > 0; bool Test62 (object o) => o is int x6 && x6 > 0;
bool Test71(object o) => o is int x7 && x7 > 0;
void Test72() => Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Test11(object x11) => 1 is int x11 &&
x11 > 0;
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (9,33): error CS1002: ; expected
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(9, 33),
// (9,36): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 36),
// (9,36): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 36),
// (9,39): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(9, 39),
// (9,39): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(9, 39),
// (11,33): error CS1002: ; expected
// void Test2(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(11, 33),
// (11,33): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// void Test2(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(11, 33),
// (11,42): error CS0103: The name 'o' does not exist in the current context
// void Test2(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(11, 42),
// (9,29): error CS0103: The name 'let' does not exist in the current context
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(9, 29),
// (9,29): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(9, 29),
// (11,29): error CS0103: The name 'let' does not exist in the current context
// void Test2(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(11, 29),
// (11,29): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
// void Test2(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(11, 29),
// (15,29): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4(object o) => x4 && o is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(15, 29),
// (18,52): error CS0128: A local variable or function named 'x5' is already defined in this scope
// o2 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 52),
// (24,28): error CS0103: The name 'x7' does not exist in the current context
// void Test72() => Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(24, 28),
// (25,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(25, 27),
// (27,41): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool Test11(object x11) => 1 is int x11 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(27, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
}
[Fact]
public void ScopeOfPatternVariables_ExpressionBodiedProperties_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test1 => let x1 = 11;
bool this[int o] => let var x2 = o;
bool Test3 => 3 is int x3 && x3 > 0;
bool Test4 => x4 && 4 is int x4;
bool Test5 => 51 is int x5 &&
52 is int x5 &&
x5 > 0;
bool Test61 => 6 is int x6 && x6 > 0; bool Test62 => 6 is int x6 && x6 > 0;
bool Test71 => 7 is int x7 && x7 > 0;
bool Test72 => Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool this[object x11] => 1 is int x11 &&
x11 > 0;
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (9,23): error CS1002: ; expected
// bool Test1 => let x1 = 11;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(9, 23),
// (9,26): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration
// bool Test1 => let x1 = 11;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 26),
// (9,26): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration
// bool Test1 => let x1 = 11;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 26),
// (11,29): error CS1002: ; expected
// bool this[int o] => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(11, 29),
// (11,29): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// bool this[int o] => let var x2 = o;
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(11, 29),
// (11,38): error CS0103: The name 'o' does not exist in the current context
// bool this[int o] => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(11, 38),
// (9,19): error CS0103: The name 'let' does not exist in the current context
// bool Test1 => let x1 = 11;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(9, 19),
// (11,25): error CS0103: The name 'let' does not exist in the current context
// bool this[int o] => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(11, 25),
// (15,19): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 => x4 && 4 is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(15, 19),
// (18,29): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 29),
// (24,26): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 => Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(24, 26),
// (25,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(25, 27),
// (27,39): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool this[object x11] => 1 is int x11 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(27, 39)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
}
[Fact]
public void ScopeOfPatternVariables_FieldInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 = 3 is int x3 && x3 > 0;
bool Test4 = x4 && 4 is int x4;
bool Test5 = 51 is int x5 &&
52 is int x5 &&
x5 > 0;
bool Test61 = 6 is int x6 && x6 > 0, Test62 = 6 is int x6 && x6 > 0;
bool Test71 = 7 is int x7 && x7 > 0;
bool Test72 = Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Test81 = 8 is int x8, Test82 = x8 > 0;
bool Test91 = x9 > 0, Test92 = 9 is int x9;
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (10,18): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 = x4 && 4 is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18),
// (13,28): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 28),
// (19,25): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 = Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,41): error CS0103: The name 'x8' does not exist in the current context
// bool Test81 = 8 is int x8, Test82 = x8 > 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(22, 41),
// (23,19): error CS0103: The name 'x9' does not exist in the current context
// bool Test91 = x9 > 0, Test92 = 9 is int x9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(23, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReference(tree, "x8");
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl);
VerifyNotInScope(model, x8Ref);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReference(tree, "x9");
VerifyNotInScope(model, x9Ref);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl);
}
[Fact]
public void ScopeOfPatternVariables_FieldInitializers_02()
{
var source =
@"
public enum X
{
Test3 = 3 is int x3 ? x3 : 0,
Test4 = x4 && 4 is int x4 ? 1 : 0,
Test5 = 51 is int x5 &&
52 is int x5 &&
x5 > 0 ? 1 : 0,
Test61 = 6 is int x6 && x6 > 0 ? 1 : 0, Test62 = 6 is int x6 && x6 > 0 ? 1 : 0,
Test71 = 7 is int x7 && x7 > 0 ? 1 : 0,
Test72 = x7,
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics(
// (6,13): error CS0841: Cannot use local variable 'x4' before it is declared
// Test4 = x4 && 4 is int x4 ? 1 : 0,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 13),
// (9,23): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 23),
// (12,14): error CS0133: The expression being assigned to 'X.Test61' must be constant
// Test61 = 6 is int x6 && x6 > 0 ? 1 : 0, Test62 = 6 is int x6 && x6 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "6 is int x6 && x6 > 0 ? 1 : 0").WithArguments("X.Test61").WithLocation(12, 14),
// (12,54): error CS0133: The expression being assigned to 'X.Test62' must be constant
// Test61 = 6 is int x6 && x6 > 0 ? 1 : 0, Test62 = 6 is int x6 && x6 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "6 is int x6 && x6 > 0 ? 1 : 0").WithArguments("X.Test62").WithLocation(12, 54),
// (14,14): error CS0133: The expression being assigned to 'X.Test71' must be constant
// Test71 = 7 is int x7 && x7 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "7 is int x7 && x7 > 0 ? 1 : 0").WithArguments("X.Test71").WithLocation(14, 14),
// (15,14): error CS0103: The name 'x7' does not exist in the current context
// Test72 = x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 14),
// (4,13): error CS0133: The expression being assigned to 'X.Test3' must be constant
// Test3 = 3 is int x3 ? x3 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "3 is int x3 ? x3 : 0").WithArguments("X.Test3").WithLocation(4, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_FieldInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
const bool Test3 = 3 is int x3 && x3 > 0;
const bool Test4 = x4 && 4 is int x4;
const bool Test5 = 51 is int x5 &&
52 is int x5 &&
x5 > 0;
const bool Test61 = 6 is int x6 && x6 > 0, Test62 = 6 is int x6 && x6 > 0;
const bool Test71 = 7 is int x7 && x7 > 0;
const bool Test72 = x7 > 2;
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (8,24): error CS0133: The expression being assigned to 'X.Test3' must be constant
// const bool Test3 = 3 is int x3 && x3 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "3 is int x3 && x3 > 0").WithArguments("X.Test3").WithLocation(8, 24),
// (10,24): error CS0841: Cannot use local variable 'x4' before it is declared
// const bool Test4 = x4 && 4 is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 24),
// (13,34): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 34),
// (16,25): error CS0133: The expression being assigned to 'X.Test61' must be constant
// const bool Test61 = 6 is int x6 && x6 > 0, Test62 = 6 is int x6 && x6 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "6 is int x6 && x6 > 0").WithArguments("X.Test61").WithLocation(16, 25),
// (16,57): error CS0133: The expression being assigned to 'X.Test62' must be constant
// const bool Test61 = 6 is int x6 && x6 > 0, Test62 = 6 is int x6 && x6 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "6 is int x6 && x6 > 0").WithArguments("X.Test62").WithLocation(16, 57),
// (18,25): error CS0133: The expression being assigned to 'X.Test71' must be constant
// const bool Test71 = 7 is int x7 && x7 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "7 is int x7 && x7 > 0").WithArguments("X.Test71").WithLocation(18, 25),
// (19,25): error CS0103: The name 'x7' does not exist in the current context
// const bool Test72 = x7 > 2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_PropertyInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 {get;} = 3 is int x3 && x3 > 0;
bool Test4 {get;} = x4 && 4 is int x4;
bool Test5 {get;} = 51 is int x5 &&
52 is int x5 &&
x5 > 0;
bool Test61 {get;} = 6 is int x6 && x6 > 0; bool Test62 {get;} = 6 is int x6 && x6 > 0;
bool Test71 {get;} = 7 is int x7 && x7 > 0;
bool Test72 {get;} = Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (10,25): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 {get;} = x4 && 4 is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 25),
// (13,28): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 28),
// (19,32): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 {get;} = Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 32),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_ParameterDefault_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test3(bool p = 3 is int x3 && x3 > 0)
{}
void Test4(bool p = x4 && 4 is int x4)
{}
void Test5(bool p = 51 is int x5 &&
52 is int x5 &&
x5 > 0)
{}
void Test61(bool p1 = 6 is int x6 && x6 > 0, bool p2 = 6 is int x6 && x6 > 0)
{}
void Test71(bool p = 7 is int x7 && x7 > 0)
{
}
void Test72(bool p = x7 > 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test3(bool p = 3 is int x3 && x3 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "3 is int x3 && x3 > 0").WithArguments("p").WithLocation(8, 25),
// (11,25): error CS0841: Cannot use local variable 'x4' before it is declared
// void Test4(bool p = x4 && 4 is int x4)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25),
// (15,35): error CS0128: A local variable or function named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 35),
// (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant
// void Test61(bool p1 = 6 is int x6 && x6 > 0, bool p2 = 6 is int x6 && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "6 is int x6 && x6 > 0").WithArguments("p1").WithLocation(19, 27),
// (19,60): error CS1736: Default parameter value for 'p2' must be a compile-time constant
// void Test61(bool p1 = 6 is int x6 && x6 > 0, bool p2 = 6 is int x6 && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "6 is int x6 && x6 > 0").WithArguments("p2").WithLocation(19, 60),
// (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test71(bool p = 7 is int x7 && x7 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "7 is int x7 && x7 > 0").WithArguments("p").WithLocation(22, 26),
// (26,26): error CS0103: The name 'x7' does not exist in the current context
// void Test72(bool p = x7 > 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26),
// (29,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_Attribute_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(p = 3 is int x3 && x3 > 0)]
[Test(p = x4 && 4 is int x4)]
[Test(p = 51 is int x5 &&
52 is int x5 &&
x5 > 0)]
[Test(p1 = 6 is int x6 && x6 > 0, p2 = 6 is int x6 && x6 > 0)]
[Test(p = 7 is int x7 && x7 > 0)]
[Test(p = x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = 3 is int x3 && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "3 is int x3 && x3 > 0").WithLocation(8, 15),
// (9,15): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && 4 is int x4)]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15),
// (11,25): error CS0128: A local variable or function named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 25),
// (13,53): error CS0128: A local variable or function named 'x6' is already defined in this scope
// [Test(p1 = 6 is int x6 && x6 > 0, p2 = 6 is int x6 && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 53),
// (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p1 = 6 is int x6 && x6 > 0, p2 = 6 is int x6 && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "6 is int x6 && x6 > 0").WithLocation(13, 16),
// (14,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = 7 is int x7 && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "7 is int x7 && x7 > 0").WithLocation(14, 15),
// (15,15): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 15),
// (16,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_Attribute_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(3 is int x3 && x3 > 0)]
[Test(x4 && 4 is int x4)]
[Test(51 is int x5 &&
52 is int x5 &&
x5 > 0)]
[Test(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)]
[Test(7 is int x7 && x7 > 0)]
[Test(x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(3 is int x3 && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "3 is int x3 && x3 > 0").WithLocation(8, 11),
// (9,11): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && 4 is int x4)]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11),
// (11,21): error CS0128: A local variable or function named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 21),
// (13,43): error CS0128: A local variable or function named 'x6' is already defined in this scope
// [Test(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 43),
// (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "6 is int x6 && x6 > 0").WithLocation(13, 11),
// (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(7 is int x7 && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "7 is int x7 && x7 > 0").WithLocation(14, 11),
// (15,11): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 11),
// (16,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_ConstructorInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
X(byte x)
: this(3 is int x3 && x3 > 0)
{}
X(sbyte x)
: this(x4 && 4 is int x4)
{}
X(short x)
: this(51 is int x5 &&
52 is int x5 &&
x5 > 0)
{}
X(ushort x)
: this(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)
{}
X(int x)
: this(7 is int x7 && x7 > 0)
{}
X(uint x)
: this(x7, 2)
{}
void Test73() { Dummy(x7, 3); }
X(params object[] x) {}
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,16): error CS0841: Cannot use local variable 'x4' before it is declared
// : this(x4 && 4 is int x4)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16),
// (18,26): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 26),
// (23,48): error CS0128: A local variable named 'x6' is already defined in this scope
// : this(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(23, 48),
// (30,16): error CS0103: The name 'x7' does not exist in the current context
// : this(x7, 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16),
// (32,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_ConstructorInitializers_02()
{
var source =
@"
public class X : Y
{
public static void Main()
{
}
X(byte x)
: base(3 is int x3 && x3 > 0)
{}
X(sbyte x)
: base(x4 && 4 is int x4)
{}
X(short x)
: base(51 is int x5 &&
52 is int x5 &&
x5 > 0)
{}
X(ushort x)
: base(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)
{}
X(int x)
: base(7 is int x7 && x7 > 0)
{}
X(uint x)
: base(x7, 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
public class Y
{
public Y(params object[] x) {}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,16): error CS0841: Cannot use local variable 'x4' before it is declared
// : base(x4 && 4 is int x4)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16),
// (18,26): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 26),
// (23,48): error CS0128: A local variable named 'x6' is already defined in this scope
// : base(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(23, 48),
// (30,16): error CS0103: The name 'x7' does not exist in the current context
// : base(x7, 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16),
// (32,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_ConstructorInitializers_03()
{
var source =
@"using System;
public class X
{
public static void Main()
{
new D(1);
new D(10);
new D(1.2);
}
}
class D
{
public D(object o) : this(o is int x && x >= 5)
{
Console.WriteLine(x);
}
public D(bool b) { Console.WriteLine(b); }
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (15,27): error CS0165: Use of unassigned local variable 'x'
// Console.WriteLine(x);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(15, 27)
);
}
[Fact]
public void ScopeOfPatternVariables_ConstructorInitializers_04()
{
var source =
@"using System;
public class X
{
public static void Main()
{
new D(1);
new D(10);
new D(1.2);
}
}
class D : C
{
public D(object o) : base(o is int x && x >= 5)
{
Console.WriteLine(x);
}
}
class C
{
public C(bool b) { Console.WriteLine(b); }
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (15,27): error CS0165: Use of unassigned local variable 'x'
// Console.WriteLine(x);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(15, 27)
);
}
[Fact]
public void ScopeOfPatternVariables_ConstructorInitializers_07()
{
var source =
@"
public class X : Y
{
public static void Main()
{
}
X(byte x3)
: base(3 is int x3)
{}
X(sbyte x)
: base(4 is int x4)
{
int x4 = 1;
System.Console.WriteLine(x4);
}
X(ushort x)
: base(51 is int x5)
=> Dummy(52 is int x5, x5);
bool Dummy(params object[] x) {return true;}
}
public class Y
{
public Y(params object[] x) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (9,25): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// : base(3 is int x3)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(9, 25),
// (15,13): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x4 = 1;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 13),
// (21,24): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// => Dummy(52 is int x5, x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl);
VerifyNotAPatternLocal(model, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[1], x5Ref);
}
[Fact]
public void ScopeOfPatternVariables_SwitchLabelGuard_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test1(int val)
{
switch (val)
{
case 0 when Dummy(true is var x1, x1):
Dummy(x1);
break;
case 1 when Dummy(true is var x1, x1):
Dummy(x1);
break;
case 2 when Dummy(true is var x1, x1):
Dummy(x1);
break;
}
}
void Test2(int val)
{
switch (val)
{
case 0 when Dummy(x2, true is var x2):
Dummy(x2);
break;
}
}
void Test3(int x3, int val)
{
switch (val)
{
case 0 when Dummy(true is var x3, x3):
Dummy(x3);
break;
}
}
void Test4(int val)
{
var x4 = 11;
switch (val)
{
case 0 when Dummy(true is var x4, x4):
Dummy(x4);
break;
case 1 when Dummy(x4): Dummy(x4); break;
}
}
void Test5(int val)
{
switch (val)
{
case 0 when Dummy(true is var x5, x5):
Dummy(x5);
break;
}
var x5 = 11;
Dummy(x5);
}
//void Test6(int val)
//{
// let x6 = 11;
// switch (val)
// {
// case 0 when Dummy(x6):
// Dummy(x6);
// break;
// case 1 when Dummy(true is var x6, x6):
// Dummy(x6);
// break;
// }
//}
//void Test7(int val)
//{
// switch (val)
// {
// case 0 when Dummy(true is var x7, x7):
// Dummy(x7);
// break;
// }
// let x7 = 11;
// Dummy(x7);
//}
void Test8(int val)
{
switch (val)
{
case 0 when Dummy(true is var x8, x8, false is var x8, x8):
Dummy(x8);
break;
}
}
void Test9(int val)
{
switch (val)
{
case 0 when Dummy(x9):
int x9 = 9;
Dummy(x9);
break;
case 2 when Dummy(x9 = 9):
Dummy(x9);
break;
case 1 when Dummy(true is var x9, x9):
Dummy(x9);
break;
}
}
//void Test10(int val)
//{
// switch (val)
// {
// case 1 when Dummy(true is var x10, x10):
// Dummy(x10);
// break;
// case 0 when Dummy(x10):
// let x10 = 10;
// Dummy(x10);
// break;
// case 2 when Dummy(x10 = 10, x10):
// Dummy(x10);
// break;
// }
//}
void Test11(int val)
{
switch (x11 ? val : 0)
{
case 0 when Dummy(x11):
Dummy(x11, 0);
break;
case 1 when Dummy(true is var x11, x11):
Dummy(x11, 1);
break;
}
}
void Test12(int val)
{
switch (x12 ? val : 0)
{
case 0 when Dummy(true is var x12, x12):
Dummy(x12, 0);
break;
case 1 when Dummy(x12):
Dummy(x12, 1);
break;
}
}
void Test13()
{
switch (1 is var x13 ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case 1 when Dummy(true is var x13, x13):
Dummy(x13);
break;
}
}
void Test14(int val)
{
switch (val)
{
case 1 when Dummy(true is var x14, x14):
Dummy(x14);
Dummy(true is var x14, x14);
Dummy(x14);
break;
}
}
void Test15(int val)
{
switch (val)
{
case 0 when Dummy(true is var x15, x15):
case 1 when Dummy(true is var x15, x15):
Dummy(x15);
break;
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (30,31): error CS0841: Cannot use local variable 'x2' before it is declared
// case 0 when Dummy(x2, true is var x2):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(30, 31),
// (40,43): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(true is var x3, x3):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(40, 43),
// (51,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(true is var x4, x4):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(51, 43),
// (62,43): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(true is var x5, x5):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(62, 43),
// (102,64): error CS0128: A local variable named 'x8' is already defined in this scope
// case 0 when Dummy(true is var x8, x8, false is var x8, x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(102, 64),
// (112,31): error CS0841: Cannot use local variable 'x9' before it is declared
// case 0 when Dummy(x9):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(112, 31),
// (119,43): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(true is var x9, x9):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(119, 43),
// (144,17): error CS0103: The name 'x11' does not exist in the current context
// switch (x11 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(144, 17),
// (146,31): error CS0103: The name 'x11' does not exist in the current context
// case 0 when Dummy(x11):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(146, 31),
// (147,23): error CS0103: The name 'x11' does not exist in the current context
// Dummy(x11, 0);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(147, 23),
// (157,17): error CS0103: The name 'x12' does not exist in the current context
// switch (x12 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(157, 17),
// (162,31): error CS0103: The name 'x12' does not exist in the current context
// case 1 when Dummy(x12):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(162, 31),
// (163,23): error CS0103: The name 'x12' does not exist in the current context
// Dummy(x12, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(163, 23),
// (175,43): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(true is var x13, x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(175, 43),
// (185,43): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(true is var x14, x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(185, 43),
// (198,43): error CS0128: A local variable named 'x15' is already defined in this scope
// case 1 when Dummy(true is var x15, x15):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(198, 43),
// (198,48): error CS0165: Use of unassigned local variable 'x15'
// case 1 when Dummy(true is var x15, x15):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(198, 48)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(6, x1Ref.Length);
for (int i = 0; i < x1Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]);
}
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(4, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[0], x4Ref[1]);
VerifyNotAPatternLocal(model, x4Ref[2]);
VerifyNotAPatternLocal(model, x4Ref[3]);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(3, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref[0], x5Ref[1]);
VerifyNotAPatternLocal(model, x5Ref[2]);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(6, x9Ref.Length);
VerifyNotAPatternLocal(model, x9Ref[0]);
VerifyNotAPatternLocal(model, x9Ref[1]);
VerifyNotAPatternLocal(model, x9Ref[2]);
VerifyNotAPatternLocal(model, x9Ref[3]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref[4], x9Ref[5]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(5, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyNotInScope(model, x11Ref[1]);
VerifyNotInScope(model, x11Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref[3], x11Ref[4]);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(5, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref[1], x12Ref[2]);
VerifyNotInScope(model, x12Ref[3]);
VerifyNotInScope(model, x12Ref[4]);
var x13Decl = GetPatternDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(5, x13Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[1], x13Ref[3], x13Ref[4]);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[1], true);
var x15Decl = GetPatternDeclarations(tree, "x15").ToArray();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Decl.Length);
Assert.Equal(3, x15Ref.Length);
for (int i = 0; i < x15Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x15Decl[0], x15Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x15Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_SwitchLabelPattern_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test1(object val)
{
switch (val)
{
case byte x1 when Dummy(x1):
Dummy(x1);
break;
case int x1 when Dummy(x1):
Dummy(x1);
break;
case long x1 when Dummy(x1):
Dummy(x1);
break;
}
}
void Test2(object val)
{
switch (val)
{
case 0 when Dummy(x2):
case int x2:
Dummy(x2);
break;
}
}
void Test3(int x3, object val)
{
switch (val)
{
case int x3 when Dummy(x3):
Dummy(x3);
break;
}
}
void Test4(object val)
{
var x4 = 11;
switch (val)
{
case int x4 when Dummy(x4):
Dummy(x4);
break;
case 1 when Dummy(x4):
Dummy(x4);
break;
}
}
void Test5(object val)
{
switch (val)
{
case int x5 when Dummy(x5):
Dummy(x5);
break;
}
var x5 = 11;
Dummy(x5);
}
//void Test6(object val)
//{
// let x6 = 11;
// switch (val)
// {
// case 0 when Dummy(x6):
// Dummy(x6);
// break;
// case int x6 when Dummy(x6):
// Dummy(x6);
// break;
// }
//}
//void Test7(object val)
//{
// switch (val)
// {
// case int x7 when Dummy(x7):
// Dummy(x7);
// break;
// }
// let x7 = 11;
// Dummy(x7);
//}
void Test8(object val)
{
switch (val)
{
case int x8
when Dummy(x8, false is var x8, x8):
Dummy(x8);
break;
}
}
void Test9(object val)
{
switch (val)
{
case 0 when Dummy(x9):
int x9 = 9;
Dummy(x9);
break;
case 2 when Dummy(x9 = 9):
Dummy(x9);
break;
case int x9 when Dummy(x9):
Dummy(x9);
break;
}
}
//void Test10(object val)
//{
// switch (val)
// {
// case int x10 when Dummy(x10):
// Dummy(x10);
// break;
// case 0 when Dummy(x10):
// let x10 = 10;
// Dummy(x10);
// break;
// case 2 when Dummy(x10 = 10, x10):
// Dummy(x10);
// break;
// }
//}
void Test11(object val)
{
switch (x11 ? val : 0)
{
case 0 when Dummy(x11):
Dummy(x11, 0);
break;
case int x11 when Dummy(x11):
Dummy(x11, 1);
break;
}
}
void Test12(object val)
{
switch (x12 ? val : 0)
{
case int x12 when Dummy(x12):
Dummy(x12, 0);
break;
case 1 when Dummy(x12):
Dummy(x12, 1);
break;
}
}
void Test13()
{
switch (1 is var x13 ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case int x13 when Dummy(x13):
Dummy(x13);
break;
}
}
void Test14(object val)
{
switch (val)
{
case int x14 when Dummy(x14):
Dummy(x14);
Dummy(true is var x14, x14);
Dummy(x14);
break;
}
}
void Test15(object val)
{
switch (val)
{
case int x15 when Dummy(x15):
case long x15 when Dummy(x15):
Dummy(x15);
break;
}
}
void Test16(object val)
{
switch (val)
{
case int x16 when Dummy(x16):
case 1 when Dummy(true is var x16, x16):
Dummy(x16);
break;
}
}
void Test17(object val)
{
switch (val)
{
case 0 when Dummy(true is var x17, x17):
case int x17 when Dummy(x17):
Dummy(x17);
break;
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (30,31): error CS0841: Cannot use local variable 'x2' before it is declared
// case 0 when Dummy(x2):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(30, 31),
// (32,23): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(32, 23),
// (41,22): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x3 when Dummy(x3):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(41, 22),
// (52,22): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x4 when Dummy(x4):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(52, 22),
// (65,22): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x5 when Dummy(x5):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(65, 22),
// (106,49): error CS0128: A local variable named 'x8' is already defined in this scope
// when Dummy(x8, false is var x8, x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(106, 49),
// (116,31): error CS0841: Cannot use local variable 'x9' before it is declared
// case 0 when Dummy(x9):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(116, 31),
// (123,22): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x9 when Dummy(x9):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(123, 22),
// (148,17): error CS0103: The name 'x11' does not exist in the current context
// switch (x11 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(148, 17),
// (150,31): error CS0103: The name 'x11' does not exist in the current context
// case 0 when Dummy(x11):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(150, 31),
// (151,23): error CS0103: The name 'x11' does not exist in the current context
// Dummy(x11, 0);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(151, 23),
// (161,17): error CS0103: The name 'x12' does not exist in the current context
// switch (x12 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(161, 17),
// (166,31): error CS0103: The name 'x12' does not exist in the current context
// case 1 when Dummy(x12):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(166, 31),
// (167,23): error CS0103: The name 'x12' does not exist in the current context
// Dummy(x12, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(167, 23),
// (179,22): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x13 when Dummy(x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(179, 22),
// (189,22): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x14 when Dummy(x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(189, 22),
// (202,23): error CS0128: A local variable named 'x15' is already defined in this scope
// case long x15 when Dummy(x15):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(202, 23),
// (202,38): error CS0165: Use of unassigned local variable 'x15'
// case long x15 when Dummy(x15):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(202, 38),
// (213,43): error CS0128: A local variable named 'x16' is already defined in this scope
// case 1 when Dummy(true is var x16, x16):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x16").WithArguments("x16").WithLocation(213, 43),
// (213,48): error CS0165: Use of unassigned local variable 'x16'
// case 1 when Dummy(true is var x16, x16):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x16").WithArguments("x16").WithLocation(213, 48),
// (224,22): error CS0128: A local variable named 'x17' is already defined in this scope
// case int x17 when Dummy(x17):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x17").WithArguments("x17").WithLocation(224, 22),
// (224,37): error CS0165: Use of unassigned local variable 'x17'
// case int x17 when Dummy(x17):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x17").WithArguments("x17").WithLocation(224, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(6, x1Ref.Length);
for (int i = 0; i < x1Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]);
}
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(4, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[0], x4Ref[1]);
VerifyNotAPatternLocal(model, x4Ref[2]);
VerifyNotAPatternLocal(model, x4Ref[3]);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(3, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref[0], x5Ref[1]);
VerifyNotAPatternLocal(model, x5Ref[2]);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(6, x9Ref.Length);
VerifyNotAPatternLocal(model, x9Ref[0]);
VerifyNotAPatternLocal(model, x9Ref[1]);
VerifyNotAPatternLocal(model, x9Ref[2]);
VerifyNotAPatternLocal(model, x9Ref[3]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref[4], x9Ref[5]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(5, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyNotInScope(model, x11Ref[1]);
VerifyNotInScope(model, x11Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref[3], x11Ref[4]);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(5, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref[1], x12Ref[2]);
VerifyNotInScope(model, x12Ref[3]);
VerifyNotInScope(model, x12Ref[4]);
var x13Decl = GetPatternDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(5, x13Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[1], x13Ref[3], x13Ref[4]);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[1], true);
var x15Decl = GetPatternDeclarations(tree, "x15").ToArray();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Decl.Length);
Assert.Equal(3, x15Ref.Length);
for (int i = 0; i < x15Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x15Decl[0], x15Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x15Decl[1]);
var x16Decl = GetPatternDeclarations(tree, "x16").ToArray();
var x16Ref = GetReferences(tree, "x16").ToArray();
Assert.Equal(2, x16Decl.Length);
Assert.Equal(3, x16Ref.Length);
for (int i = 0; i < x16Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x16Decl[0], x16Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x16Decl[1]);
var x17Decl = GetPatternDeclarations(tree, "x17").ToArray();
var x17Ref = GetReferences(tree, "x17").ToArray();
Assert.Equal(2, x17Decl.Length);
Assert.Equal(3, x17Ref.Length);
for (int i = 0; i < x17Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x17Decl[0], x17Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x17Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Switch_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
switch (1 is var x1 ? x1 : 0)
{
case 0:
Dummy(x1, 0);
break;
}
Dummy(x1, 1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
switch (4 is var x4 ? x4 : 0)
{
case 4:
Dummy(x4);
break;
}
}
void Test5(int x5)
{
switch (5 is var x5 ? x5 : 0)
{
case 5:
Dummy(x5);
break;
}
}
void Test6()
{
switch (x6 + 6 is var x6 ? x6 : 0)
{
case 6:
Dummy(x6);
break;
}
}
void Test7()
{
switch (7 is var x7 ? x7 : 0)
{
case 7:
var x7 = 12;
Dummy(x7);
break;
}
}
void Test9()
{
switch (9 is var x9 ? x9 : 0)
{
case 9:
Dummy(x9, 0);
switch (9 is var x9 ? x9 : 0)
{
case 9:
Dummy(x9, 1);
break;
}
break;
}
}
void Test10()
{
switch (y10 + 10 is var x10 ? x10 : 0)
{
case 0 when y10:
break;
case y10:
var y10 = 12;
Dummy(y10);
break;
}
}
//void Test11()
//{
// switch (y11 + 11 is var x11 ? x11 : 0)
// {
// case 0 when y11 > 0:
// break;
// case y11:
// let y11 = 12;
// Dummy(y11);
// break;
// }
//}
void Test14()
{
switch (Dummy(1 is var x14,
2 is var x14,
x14) ? 1 : 0)
{
case 0:
Dummy(x14);
break;
}
}
void Test15(int val)
{
switch (val)
{
case 0 when y15 > 0:
break;
case y15:
var y15 = 15;
Dummy(y15);
break;
}
}
//void Test16(int val)
//{
// switch (val)
// {
// case 0 when y16 > 0:
// break;
// case y16:
// let y16 = 16;
// Dummy(y16);
// break;
// }
//}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (27,26): error CS0128: A local variable or function named 'x4' is already defined in this scope
// switch (4 is var x4 ? x4 : 0)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(27, 26),
// (37,26): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// switch (5 is var x5 ? x5 : 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(37, 26),
// (47,17): error CS0841: Cannot use local variable 'x6' before it is declared
// switch (x6 + 6 is var x6 ? x6 : 0)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(47, 17),
// (60,21): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(60, 21),
// (71,23): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9, 0);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(71, 23),
// (72,34): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// switch (9 is var x9 ? x9 : 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(72, 34),
// (85,17): error CS0103: The name 'y10' does not exist in the current context
// switch (y10 + 10 is var x10 ? x10 : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 17),
// (87,25): error CS0841: Cannot use local variable 'y10' before it is declared
// case 0 when y10:
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y10").WithArguments("y10").WithLocation(87, 25),
// (89,18): error CS0841: Cannot use local variable 'y10' before it is declared
// case y10:
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y10").WithArguments("y10").WithLocation(89, 18),
// (89,18): error CS0150: A constant value is expected
// case y10:
Diagnostic(ErrorCode.ERR_ConstantExpected, "y10").WithLocation(89, 18),
// (112,28): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(112, 28),
// (125,25): error CS0841: Cannot use local variable 'y15' before it is declared
// case 0 when y15 > 0:
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y15").WithArguments("y15").WithLocation(125, 25),
// (127,18): error CS0841: Cannot use local variable 'y15' before it is declared
// case y15:
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y15").WithArguments("y15").WithLocation(127, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyNotAPatternLocal(model, x4Ref[2]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(3, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(4, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
VerifyNotAPatternLocal(model, y10Ref[2]);
VerifyNotAPatternLocal(model, y10Ref[3]);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
var y15Ref = GetReferences(tree, "y15").ToArray();
Assert.Equal(3, y15Ref.Length);
VerifyNotAPatternLocal(model, y15Ref[0]);
VerifyNotAPatternLocal(model, y15Ref[1]);
VerifyNotAPatternLocal(model, y15Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_Switch_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
switch (1 is var x1 ? 1 : 0)
{
case 0:
break;
}
Dummy(x1, 1);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (19,15): error CS0103: The name 'x1' does not exist in the current context
// Dummy(x1, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(19, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_Switch_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (SwitchStatementSyntax)SyntaxFactory.ParseStatement(@"
switch (Dummy(11 is var x1, x1)) {}
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_Using_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (Dummy(true is var x1, x1))
{
Dummy(x1);
}
}
void Test2()
{
using (Dummy(true is var x2, x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (Dummy(true is var x4, x4))
Dummy(x4);
}
void Test6()
{
using (Dummy(x6 && true is var x6))
Dummy(x6);
}
void Test7()
{
using (Dummy(true is var x7 && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (Dummy(true is var x8, x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (Dummy(true is var x9, x9))
{
Dummy(x9);
using (Dummy(true is var x9, x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (Dummy(y10 is var x10, x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (Dummy(y11 is var x11, x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (Dummy(y12 is var x12, x12))
var y12 = 12;
}
//void Test13()
//{
// using (Dummy(y13 is var x13, x13))
// let y13 = 12;
//}
void Test14()
{
using (Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,34): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(true is var x4, x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 34),
// (35,22): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && true is var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 22),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(true is var x9, x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 38),
// (68,22): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(y10 is var x10, x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 22),
// (86,22): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(y12 is var x12, x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 22),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,31): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 31)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Using_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d = Dummy(true is var x1, x1))
{
Dummy(x1);
}
}
void Test2()
{
using (var d = Dummy(true is var x2, x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (var d = Dummy(true is var x4, x4))
Dummy(x4);
}
void Test6()
{
using (var d = Dummy(x6 && true is var x6))
Dummy(x6);
}
void Test7()
{
using (var d = Dummy(true is var x7 && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (var d = Dummy(true is var x8, x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (var d = Dummy(true is var x9, x9))
{
Dummy(x9);
using (var e = Dummy(true is var x9, x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (var d = Dummy(y10 is var x10, x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (var d = Dummy(y11 is var x11, x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (var d = Dummy(y12 is var x12, x12))
var y12 = 12;
}
//void Test13()
//{
// using (var d = Dummy(y13 is var x13, x13))
// let y13 = 12;
//}
void Test14()
{
using (var d = Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var d = Dummy(true is var x4, x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 42),
// (35,30): error CS0841: Cannot use local variable 'x6' before it is declared
// using (var d = Dummy(x6 && true is var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var e = Dummy(true is var x9, x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 46),
// (68,30): error CS0103: The name 'y10' does not exist in the current context
// using (var d = Dummy(y10 is var x10, x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 30),
// (86,30): error CS0103: The name 'y12' does not exist in the current context
// using (var d = Dummy(y12 is var x12, x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 30),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,39): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 39)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Using_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d = Dummy(true is var x1, x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d = Dummy(true is var x2, x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (System.IDisposable d = Dummy(true is var x4, x4))
Dummy(x4);
}
void Test6()
{
using (System.IDisposable d = Dummy(x6 && true is var x6))
Dummy(x6);
}
void Test7()
{
using (System.IDisposable d = Dummy(true is var x7 && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (System.IDisposable d = Dummy(true is var x8, x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (System.IDisposable d = Dummy(true is var x9, x9))
{
Dummy(x9);
using (System.IDisposable c = Dummy(true is var x9, x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (System.IDisposable d = Dummy(y10 is var x10, x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (System.IDisposable d = Dummy(y11 is var x11, x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (System.IDisposable d = Dummy(y12 is var x12, x12))
var y12 = 12;
}
//void Test13()
//{
// using (System.IDisposable d = Dummy(y13 is var x13, x13))
// let y13 = 12;
//}
void Test14()
{
using (System.IDisposable d = Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (System.IDisposable d = Dummy(true is var x4, x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57),
// (35,45): error CS0841: Cannot use local variable 'x6' before it is declared
// using (System.IDisposable d = Dummy(x6 && true is var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 45),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (System.IDisposable c = Dummy(true is var x9, x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61),
// (68,45): error CS0103: The name 'y10' does not exist in the current context
// using (System.IDisposable d = Dummy(y10 is var x10, x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 45),
// (86,45): error CS0103: The name 'y12' does not exist in the current context
// using (System.IDisposable d = Dummy(y12 is var x12, x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 45),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,54): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Using_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var x1 = Dummy(true is var x1, x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable x2 = Dummy(true is var x2, x2))
{
Dummy(x2);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (12,43): error CS0128: A local variable named 'x1' is already defined in this scope
// using (var x1 = Dummy(true is var x1, x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 43),
// (12,47): error CS0841: Cannot use local variable 'x1' before it is declared
// using (var x1 = Dummy(true is var x1, x1))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(12, 47),
// (20,58): error CS0128: A local variable named 'x2' is already defined in this scope
// using (System.IDisposable x2 = Dummy(true is var x2, x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 58),
// (20,62): error CS0165: Use of unassigned local variable 'x2'
// using (System.IDisposable x2 = Dummy(true is var x2, x2))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 62)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl);
VerifyNotAPatternLocal(model, x2Ref[0]);
VerifyNotAPatternLocal(model, x2Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_Using_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d = Dummy(true is var x1, x1),
x1 = Dummy(x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d1 = Dummy(true is var x2, x2),
d2 = Dummy(true is var x2, x2))
{
Dummy(x2);
}
}
void Test3()
{
using (System.IDisposable d1 = Dummy(true is var x3, x3),
d2 = Dummy(x3))
{
Dummy(x3);
}
}
void Test4()
{
using (System.IDisposable d1 = Dummy(x4),
d2 = Dummy(true is var x4, x4))
{
Dummy(x4);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,35): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35),
// (22,58): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(true is var x2, x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 58),
// (39,46): error CS0841: Cannot use local variable 'x4' before it is declared
// using (System.IDisposable d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(3, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
}
[Fact]
public void ScopeOfPatternVariables_LocalDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var d = Dummy(true is var x1, x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
var d = Dummy(true is var x4, x4);
}
void Test6()
{
var d = Dummy(x6 && true is var x6);
}
void Test8()
{
var d = Dummy(true is var x8, x8);
System.Console.WriteLine(x8);
}
void Test14()
{
var d = Dummy(1 is var x14,
2 is var x14,
x14);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (19,35): error CS0128: A local variable named 'x4' is already defined in this scope
// var d = Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 35),
// (24,23): error CS0841: Cannot use local variable 'x6' before it is declared
// var d = Dummy(x6 && true is var x6);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23),
// (36,32): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 32)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_LocalDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d = Dummy(true is var x1, x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
object d = Dummy(true is var x4, x4);
}
void Test6()
{
object d = Dummy(x6 && true is var x6);
}
void Test8()
{
object d = Dummy(true is var x8, x8);
System.Console.WriteLine(x8);
}
void Test14()
{
object d = Dummy(1 is var x14,
2 is var x14,
x14);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (19,38): error CS0128: A local variable named 'x4' is already defined in this scope
// object d = Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 38),
// (24,26): error CS0841: Cannot use local variable 'x6' before it is declared
// object d = Dummy(x6 && true is var x6);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 26),
// (36,35): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 35)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_LocalDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var x1 =
Dummy(true is var x1, x1);
Dummy(x1);
}
void Test2()
{
object x2 =
Dummy(true is var x2, x2);
Dummy(x2);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,36): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 36),
// (13,40): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 40),
// (20,39): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(true is var x2, x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 39),
// (20,43): error CS0165: Use of unassigned local variable 'x2'
// Dummy(true is var x2, x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 43)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyNotAPatternLocal(model, x2Ref[0]);
VerifyNotAPatternLocal(model, x2Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl);
}
[Fact]
public void ScopeOfPatternVariables_LocalDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d = Dummy(true is var x1, x1),
x1 = Dummy(x1);
Dummy(x1);
}
void Test2()
{
object d1 = Dummy(true is var x2, x2),
d2 = Dummy(true is var x2, x2);
}
void Test3()
{
object d1 = Dummy(true is var x3, x3),
d2 = Dummy(x3);
}
void Test4()
{
object d1 = Dummy(x4),
d2 = Dummy(true is var x4, x4);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (20,39): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(true is var x2, x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 39),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
}
[Fact]
public void ScopeOfPatternVariables_LocalDeclarationStmt_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
long Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"
var y1 = Dummy(11 is var x1, x1);
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
Assert.Equal("System.Int64 y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_LocalDeclarationStmt_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var d = true is var x1;
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var d = true is var x1;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d = true is var x1;").WithLocation(11, 13),
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
var d = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "d").Single();
Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void ScopeOfPatternVariables_DeconstructionDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var (d, dd) = ((true is var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
var (d, dd) = ((true is var x4), x4);
}
void Test6()
{
var (d, dd) = (x6 && (true is var x6), 1);
}
void Test8()
{
var (d, dd) = ((true is var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
var (d, dd, ddd) = ((1 is var x14),
(2 is var x14),
x14);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,37): error CS0128: A local variable named 'x4' is already defined in this scope
// var (d, dd) = ((true is var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 37),
// (24,24): error CS0841: Cannot use local variable 'x6' before it is declared
// var (d, dd) = (x6 && (true is var x6), 1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 24),
// (36,33): error CS0128: A local variable named 'x14' is already defined in this scope
// (2 is var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x4Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x4").Single();
var x4Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x6Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x6").Single();
var x6Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x6").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x8Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x8").Single();
var x8Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x14Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x14").ToArray();
var x14Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void ScopeOfPatternVariables_DeconstructionDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
(object d, object dd) = ((true is var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
(object d, object dd) = ((true is var x4), x4);
}
void Test6()
{
(object d, object dd) = (x6 && (true is var x6), 1);
}
void Test8()
{
(object d, object dd) = ((true is var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
(object d, object dd, object ddd) = ((1 is var x14),
(2 is var x14),
x14);
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,47): error CS0128: A local variable named 'x4' is already defined in this scope
// (object d, object dd) = ((true is var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 47),
// (24,34): error CS0841: Cannot use local variable 'x6' before it is declared
// (object d, object dd) = (x6 && (true is var x6), 1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 34),
// (36,33): error CS0128: A local variable named 'x14' is already defined in this scope
// (2 is var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x4Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x4").Single();
var x4Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x6Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x6").Single();
var x6Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x6").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x8Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x8").Single();
var x8Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x14Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x14").ToArray();
var x14Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void ScopeOfPatternVariables_DeconstructionDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var (x1, dd) =
((true is var x1), x1);
Dummy(x1);
}
void Test2()
{
(object x2, object dd) =
((true is var x2), x2);
Dummy(x2);
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,37): error CS0128: A local variable named 'x1' is already defined in this scope
// ((true is var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 37),
// (13,42): error CS0841: Cannot use local variable 'x1' before it is declared
// ((true is var x1), x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 42),
// (20,40): error CS0128: A local variable named 'x2' is already defined in this scope
// ((true is var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 40),
// (20,45): error CS0165: Use of unassigned local variable 'x2'
// ((true is var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 45)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
var x2Decl = GetPatternDeclaration(tree, "x2");
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyNotAPatternLocal(model, x2Ref[0]);
VerifyNotAPatternLocal(model, x2Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void ScopeOfPatternVariables_DeconstructionDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
(object d, object x1) = (Dummy((true is var x1), x1),
Dummy(x1));
Dummy(x1);
}
void Test2()
{
(object d1, object d2) = (Dummy((true is var x2), x2),
Dummy((true is var x2), x2));
}
void Test3()
{
(object d1, object d2) = (Dummy((true is var x3), x3),
Dummy(x3));
}
void Test4()
{
(object d1, object d2) = (Dummy(x4),
Dummy((true is var x4), x4));
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,53): error CS0128: A local variable named 'x1' is already defined in this scope
// (object d, object x1) = (Dummy((true is var x1), x1),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 53),
// (12,58): error CS0165: Use of unassigned local variable 'x1'
// (object d, object x1) = (Dummy((true is var x1), x1),
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(12, 58),
// (20,40): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy((true is var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 40),
// (31,41): error CS0841: Cannot use local variable 'x4' before it is declared
// (object d1, object d2) = (Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
VerifyNotAPatternLocal(model, x1Ref[2]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
var x2Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x2").ToArray();
var x2Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x3").Single();
var x3Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x4").Single();
var x4Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void ScopeOfPatternVariables_DeconstructionDeclarationStmt_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@"
var (y1, dd) = ((123 is var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
Assert.Equal("System.Boolean y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void ScopeOfPatternVariables_DeconstructionDeclarationStmt_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var (d, dd) = ((true is var x1), x1);
x1++;
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var d = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(id => id.Identifier.ValueText == "d").Single();
Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_While_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
while (true is var x1 && x1)
{
Dummy(x1);
}
}
void Test2()
{
while (true is var x2 && x2)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
while (true is var x4 && x4)
Dummy(x4);
}
void Test6()
{
while (x6 && true is var x6)
Dummy(x6);
}
void Test7()
{
while (true is var x7 && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
while (true is var x8 && x8)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
while (true is var x9 && x9)
{
Dummy(x9);
while (true is var x9 && x9) // 2
Dummy(x9);
}
}
void Test10()
{
while (y10 is var x10)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// while (y11 is var x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
while (y12 is var x12)
var y12 = 12;
}
//void Test13()
//{
// while (y13 is var x13)
// let y13 = 12;
//}
void Test14()
{
while (Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,28): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 28),
// (35,16): error CS0841: Cannot use local variable 'x6' before it is declared
// while (x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 16),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,32): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 32),
// (68,16): error CS0103: The name 'y10' does not exist in the current context
// while (y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 16),
// (86,16): error CS0103: The name 'y12' does not exist in the current context
// while (y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 16),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,31): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 31)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_While_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
while (true is var x1)
{
}
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (17,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_While_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (WhileStatementSyntax)SyntaxFactory.ParseStatement(@"
while (Dummy(11 is var x1, x1)) ;
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_Do_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
do
{
Dummy(x1);
}
while (true is var x1 && x1);
}
void Test2()
{
do
Dummy(x2);
while (true is var x2 && x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
do
Dummy(x4);
while (true is var x4 && x4);
}
void Test6()
{
do
Dummy(x6);
while (x6 && true is var x6);
}
void Test7()
{
do
{
var x7 = 12;
Dummy(x7);
}
while (true is var x7 && x7);
}
void Test8()
{
do
Dummy(x8);
while (true is var x8 && x8);
System.Console.WriteLine(x8);
}
void Test9()
{
do
{
Dummy(x9);
do
Dummy(x9);
while (true is var x9 && x9); // 2
}
while (true is var x9 && x9);
}
void Test10()
{
do
{
var y10 = 12;
Dummy(y10);
}
while (y10 is var x10);
}
//void Test11()
//{
// do
// {
// let y11 = 12;
// Dummy(y11);
// }
// while (y11 is var x11);
//}
void Test12()
{
do
var y12 = 12;
while (y12 is var x12);
}
//void Test13()
//{
// do
// let y13 = 12;
// while (y13 is var x13);
//}
void Test14()
{
do
{
Dummy(x14);
}
while (Dummy(1 is var x14,
2 is var x14,
x14));
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (97,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(97, 13),
// (14,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(14, 19),
// (22,19): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(22, 19),
// (33,28): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (true is var x4 && x4);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(33, 28),
// (32,19): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy(x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(32, 19),
// (40,16): error CS0841: Cannot use local variable 'x6' before it is declared
// while (x6 && true is var x6);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(40, 16),
// (39,19): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(39, 19),
// (47,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(47, 17),
// (56,19): error CS0841: Cannot use local variable 'x8' before it is declared
// Dummy(x8);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x8").WithArguments("x8").WithLocation(56, 19),
// (59,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(59, 34),
// (66,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(66, 19),
// (69,32): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (true is var x9 && x9); // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(69, 32),
// (68,23): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(68, 23),
// (81,16): error CS0103: The name 'y10' does not exist in the current context
// while (y10 is var x10);
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(81, 16),
// (98,16): error CS0103: The name 'y12' does not exist in the current context
// while (y12 is var x12);
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(98, 16),
// (97,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(97, 17),
// (115,31): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(115, 31),
// (112,19): error CS0841: Cannot use local variable 'x14' before it is declared
// Dummy(x14);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x14").WithArguments("x14").WithLocation(112, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[1]);
VerifyNotAPatternLocal(model, x7Ref[0]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[1], x9Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[0], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[1]);
VerifyNotAPatternLocal(model, y10Ref[0]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Do_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
do
{
}
while (true is var x1);
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (18,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_Do_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (DoStatementSyntax)SyntaxFactory.ParseStatement(@"
do {} while (Dummy(11 is var x1, x1));
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_For_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (
Dummy(true is var x1 && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (
Dummy(true is var x2 && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (
Dummy(true is var x4 && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (
Dummy(x6 && true is var x6)
;;)
Dummy(x6);
}
void Test7()
{
for (
Dummy(true is var x7 && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (
Dummy(true is var x8 && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (
Dummy(true is var x9 && x9)
;;)
{
Dummy(x9);
for (
Dummy(true is var x9 && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (
Dummy(y10 is var x10)
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (
// Dummy(y11 is var x11)
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (
Dummy(y12 is var x12)
;;)
var y12 = 12;
}
//void Test13()
//{
// for (
// Dummy(y13 is var x13)
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (
Dummy(1 is var x14,
2 is var x14,
x14)
;;)
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,32): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 32),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,36): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 36),
// (85,20): error CS0103: The name 'y10' does not exist in the current context
// Dummy(y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 20),
// (107,20): error CS0103: The name 'y12' does not exist in the current context
// Dummy(y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 20),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,29): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_For_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;
Dummy(true is var x1 && x1)
;)
{
Dummy(x1);
}
}
void Test2()
{
for (;
Dummy(true is var x2 && x2)
;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (;
Dummy(true is var x4 && x4)
;)
Dummy(x4);
}
void Test6()
{
for (;
Dummy(x6 && true is var x6)
;)
Dummy(x6);
}
void Test7()
{
for (;
Dummy(true is var x7 && x7)
;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (;
Dummy(true is var x8 && x8)
;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (;
Dummy(true is var x9 && x9)
;)
{
Dummy(x9);
for (;
Dummy(true is var x9 && x9) // 2
;)
Dummy(x9);
}
}
void Test10()
{
for (;
Dummy(y10 is var x10)
;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (;
// Dummy(y11 is var x11)
// ;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (;
Dummy(y12 is var x12)
;)
var y12 = 12;
}
//void Test13()
//{
// for (;
// Dummy(y13 is var x13)
// ;)
// let y13 = 12;
//}
void Test14()
{
for (;
Dummy(1 is var x14,
2 is var x14,
x14)
;)
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,32): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 32),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (76,36): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 36),
// (85,20): error CS0103: The name 'y10' does not exist in the current context
// Dummy(y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 20),
// (107,20): error CS0103: The name 'y12' does not exist in the current context
// Dummy(y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 20),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,29): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_For_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;;
Dummy(true is var x1 && x1)
)
{
Dummy(x1);
}
}
void Test2()
{
for (;;
Dummy(true is var x2 && x2)
)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (;;
Dummy(true is var x4 && x4)
)
Dummy(x4);
}
void Test6()
{
for (;;
Dummy(x6 && true is var x6)
)
Dummy(x6);
}
void Test7()
{
for (;;
Dummy(true is var x7 && x7)
)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (;;
Dummy(true is var x8 && x8)
)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (;;
Dummy(true is var x9 && x9)
)
{
Dummy(x9);
for (;;
Dummy(true is var x9 && x9) // 2
)
Dummy(x9);
}
}
void Test10()
{
for (;;
Dummy(y10 is var x10)
)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (;;
// Dummy(y11 is var x11)
// )
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (;;
Dummy(y12 is var x12)
)
var y12 = 12;
}
//void Test13()
//{
// for (;;
// Dummy(y13 is var x13)
// )
// let y13 = 12;
//}
void Test14()
{
for (;;
Dummy(1 is var x14,
2 is var x14,
x14)
)
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (16,19): error CS0103: The name 'x1' does not exist in the current context
// Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(16, 19),
// (25,19): error CS0103: The name 'x2' does not exist in the current context
// Dummy(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(25, 19),
// (34,32): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 32),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (44,19): error CS0103: The name 'x6' does not exist in the current context
// Dummy(x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(44, 19),
// (63,19): error CS0103: The name 'x8' does not exist in the current context
// Dummy(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(63, 19),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (74,19): error CS0103: The name 'x9' does not exist in the current context
// Dummy(x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(74, 19),
// (78,23): error CS0103: The name 'x9' does not exist in the current context
// Dummy(x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(78, 23),
// (71,14): warning CS0162: Unreachable code detected
// Dummy(true is var x9 && x9)
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(71, 14),
// (85,20): error CS0103: The name 'y10' does not exist in the current context
// Dummy(y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 20),
// (107,20): error CS0103: The name 'y12' does not exist in the current context
// Dummy(y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 20),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,29): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 29),
// (128,19): error CS0103: The name 'x14' does not exist in the current context
// Dummy(x14);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(128, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref[0]);
VerifyNotInScope(model, x2Ref[1]);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1]);
VerifyNotAPatternLocal(model, x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref[0]);
VerifyNotInScope(model, x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0]);
VerifyNotInScope(model, x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0]);
VerifyNotInScope(model, x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2]);
VerifyNotInScope(model, x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref[0]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
VerifyNotInScope(model, x14Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_For_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (var b =
Dummy(true is var x1 && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (var b =
Dummy(true is var x2 && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (var b =
Dummy(true is var x4 && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (var b =
Dummy(x6 && true is var x6)
;;)
Dummy(x6);
}
void Test7()
{
for (var b =
Dummy(true is var x7 && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (var b =
Dummy(true is var x8 && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (var b1 =
Dummy(true is var x9 && x9)
;;)
{
Dummy(x9);
for (var b2 =
Dummy(true is var x9 && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (var b =
Dummy(y10 is var x10)
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (var b =
// Dummy(y11 is var x11)
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (var b =
Dummy(y12 is var x12)
;;)
var y12 = 12;
}
//void Test13()
//{
// for (var b =
// Dummy(y13 is var x13)
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (var b =
Dummy(1 is var x14,
2 is var x14,
x14)
;;)
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,32): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 32),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,36): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 36),
// (85,20): error CS0103: The name 'y10' does not exist in the current context
// Dummy(y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 20),
// (107,20): error CS0103: The name 'y12' does not exist in the current context
// Dummy(y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 20),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,29): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_For_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (bool b =
Dummy(true is var x1 && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (bool b =
Dummy(true is var x2 && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (bool b =
Dummy(true is var x4 && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (bool b =
Dummy(x6 && true is var x6)
;;)
Dummy(x6);
}
void Test7()
{
for (bool b =
Dummy(true is var x7 && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (bool b =
Dummy(true is var x8 && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (bool b1 =
Dummy(true is var x9 && x9)
;;)
{
Dummy(x9);
for (bool b2 =
Dummy(true is var x9 && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (bool b =
Dummy(y10 is var x10)
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (bool b =
// Dummy(y11 is var x11)
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (bool b =
Dummy(y12 is var x12)
;;)
var y12 = 12;
}
//void Test13()
//{
// for (bool b =
// Dummy(y13 is var x13)
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (bool b =
Dummy(1 is var x14,
2 is var x14,
x14)
;;)
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,32): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 32),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,36): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 36),
// (85,20): error CS0103: The name 'y10' does not exist in the current context
// Dummy(y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 20),
// (107,20): error CS0103: The name 'y12' does not exist in the current context
// Dummy(y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 20),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,29): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_For_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (var x1 =
Dummy(true is var x1 && x1)
;;)
{}
}
void Test2()
{
for (var x2 = true;
Dummy(true is var x2 && x2)
;)
{}
}
void Test3()
{
for (var x3 = true;;
Dummy(true is var x3 && x3)
)
{}
}
void Test4()
{
for (bool x4 =
Dummy(true is var x4 && x4)
;;)
{}
}
void Test5()
{
for (bool x5 = true;
Dummy(true is var x5 && x5)
;)
{}
}
void Test6()
{
for (bool x6 = true;;
Dummy(true is var x6 && x6)
)
{}
}
void Test7()
{
for (bool x7 = true, b =
Dummy(true is var x7 && x7)
;;)
{}
}
void Test8()
{
for (bool b1 = Dummy(true is var x8 && x8),
b2 = Dummy(true is var x8 && x8);
Dummy(true is var x8 && x8);
Dummy(true is var x8 && x8))
{}
}
void Test9()
{
for (bool b = x9,
b2 = Dummy(true is var x9 && x9);
Dummy(true is var x9 && x9);
Dummy(true is var x9 && x9))
{}
}
void Test10()
{
for (var b = x10;
Dummy(true is var x10 && x10) &&
Dummy(true is var x10 && x10);
Dummy(true is var x10 && x10))
{}
}
void Test11()
{
for (bool b = x11;
Dummy(true is var x11 && x11) &&
Dummy(true is var x11 && x11);
Dummy(true is var x11 && x11))
{}
}
void Test12()
{
for (Dummy(x12);
Dummy(x12) &&
Dummy(true is var x12 && x12);
Dummy(true is var x12 && x12))
{}
}
void Test13()
{
for (var b = x13;
Dummy(x13);
Dummy(true is var x13 && x13),
Dummy(true is var x13 && x13))
{}
}
void Test14()
{
for (bool b = x14;
Dummy(x14);
Dummy(true is var x14 && x14),
Dummy(true is var x14 && x14))
{}
}
void Test15()
{
for (Dummy(x15);
Dummy(x15);
Dummy(x15),
Dummy(true is var x15 && x15))
{}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,32): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(true is var x1 && x1)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 32),
// (13,38): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(true is var x1 && x1)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 38),
// (21,32): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x2 && x2)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 32),
// (20,18): warning CS0219: The variable 'x2' is assigned but its value is never used
// for (var x2 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(20, 18),
// (29,32): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x3 && x3)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 32),
// (28,18): warning CS0219: The variable 'x3' is assigned but its value is never used
// for (var x3 = true;;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(28, 18),
// (37,32): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(37, 32),
// (37,38): error CS0165: Use of unassigned local variable 'x4'
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(37, 38),
// (45,32): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x5 && x5)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(45, 32),
// (44,19): warning CS0219: The variable 'x5' is assigned but its value is never used
// for (bool x5 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(44, 19),
// (53,32): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x6 && x6)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(53, 32),
// (52,19): warning CS0219: The variable 'x6' is assigned but its value is never used
// for (bool x6 = true;;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(52, 19),
// (61,32): error CS0128: A local variable or function named 'x7' is already defined in this scope
// Dummy(true is var x7 && x7)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(61, 32),
// (69,37): error CS0128: A local variable or function named 'x8' is already defined in this scope
// b2 = Dummy(true is var x8 && x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(69, 37),
// (70,32): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x8 && x8);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(70, 32),
// (71,32): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x8 && x8))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(71, 32),
// (77,23): error CS0841: Cannot use local variable 'x9' before it is declared
// for (bool b = x9,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(77, 23),
// (79,32): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(79, 32),
// (80,32): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(80, 32),
// (86,22): error CS0103: The name 'x10' does not exist in the current context
// for (var b = x10;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x10").WithArguments("x10").WithLocation(86, 22),
// (88,32): error CS0128: A local variable or function named 'x10' is already defined in this scope
// Dummy(true is var x10 && x10);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x10").WithArguments("x10").WithLocation(88, 32),
// (89,32): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x10 && x10))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(89, 32),
// (95,23): error CS0103: The name 'x11' does not exist in the current context
// for (bool b = x11;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(95, 23),
// (97,32): error CS0128: A local variable or function named 'x11' is already defined in this scope
// Dummy(true is var x11 && x11);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x11").WithArguments("x11").WithLocation(97, 32),
// (98,32): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x11 && x11))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(98, 32),
// (104,20): error CS0103: The name 'x12' does not exist in the current context
// for (Dummy(x12);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(104, 20),
// (105,20): error CS0841: Cannot use local variable 'x12' before it is declared
// Dummy(x12) &&
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(105, 20),
// (107,32): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x12 && x12))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(107, 32),
// (113,22): error CS0103: The name 'x13' does not exist in the current context
// for (var b = x13;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(113, 22),
// (114,20): error CS0103: The name 'x13' does not exist in the current context
// Dummy(x13);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(114, 20),
// (116,32): error CS0128: A local variable or function named 'x13' is already defined in this scope
// Dummy(true is var x13 && x13))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x13").WithArguments("x13").WithLocation(116, 32),
// (122,23): error CS0103: The name 'x14' does not exist in the current context
// for (bool b = x14;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(122, 23),
// (123,20): error CS0103: The name 'x14' does not exist in the current context
// Dummy(x14);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(123, 20),
// (125,32): error CS0128: A local variable or function named 'x14' is already defined in this scope
// Dummy(true is var x14 && x14))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(125, 32),
// (131,20): error CS0103: The name 'x15' does not exist in the current context
// for (Dummy(x15);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(131, 20),
// (132,20): error CS0103: The name 'x15' does not exist in the current context
// Dummy(x15);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(132, 20),
// (133,20): error CS0841: Cannot use local variable 'x15' before it is declared
// Dummy(x15),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x15").WithArguments("x15").WithLocation(133, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
VerifyNotAPatternLocal(model, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
VerifyNotAPatternLocal(model, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x7Decl);
VerifyNotAPatternLocal(model, x7Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(4, x8Decl.Length);
Assert.Equal(4, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[0], x8Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[2], x8Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[3], x8Ref[3]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(3, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[2], x9Ref[3]);
var x10Decl = GetPatternDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(3, x10Decl.Length);
Assert.Equal(4, x10Ref.Length);
VerifyNotInScope(model, x10Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl[0], x10Ref[1], x10Ref[2]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x10Decl[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl[2], x10Ref[3]);
var x11Decl = GetPatternDeclarations(tree, "x11").ToArray();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Decl.Length);
Assert.Equal(4, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl[0], x11Ref[1], x11Ref[2]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x11Decl[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl[2], x11Ref[3]);
var x12Decl = GetPatternDeclarations(tree, "x12").ToArray();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Decl.Length);
Assert.Equal(4, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl[0], x12Ref[1], x12Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl[1], x12Ref[3]);
var x13Decl = GetPatternDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(4, x13Ref.Length);
VerifyNotInScope(model, x13Ref[0]);
VerifyNotInScope(model, x13Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[0], x13Ref[2], x13Ref[3]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x13Decl[1]);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyNotInScope(model, x14Ref[0]);
VerifyNotInScope(model, x14Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref[2], x14Ref[3]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetPatternDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(4, x15Ref.Length);
VerifyNotInScope(model, x15Ref[0]);
VerifyNotInScope(model, x15Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x15Decl, x15Ref[2], x15Ref[3]);
}
[Fact]
public void ScopeOfPatternVariables_For_07()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;;
Dummy(x1),
Dummy(true is var x1 && x1))
{}
}
void Test2()
{
for (;;
Dummy(true is var x2 && x2),
Dummy(true is var x2 && x2))
{}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,20): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(x1),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 20),
// (22,32): error CS0128: A local variable or function named 'x2' is already defined in this scope
// Dummy(true is var x2 && x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 32)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Foreach_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Collections.IEnumerable Dummy(params object[] x) {return null;}
void Test1()
{
foreach (var i in Dummy(true is var x1 && x1))
{
Dummy(x1);
}
}
void Test2()
{
foreach (var i in Dummy(true is var x2 && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
foreach (var i in Dummy(true is var x4 && x4))
Dummy(x4);
}
void Test6()
{
foreach (var i in Dummy(x6 && true is var x6))
Dummy(x6);
}
void Test7()
{
foreach (var i in Dummy(true is var x7 && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
foreach (var i in Dummy(true is var x8 && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
foreach (var i1 in Dummy(true is var x9 && x9))
{
Dummy(x9);
foreach (var i2 in Dummy(true is var x9 && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
foreach (var i in Dummy(y10 is var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// foreach (var i in Dummy(y11 is var x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
foreach (var i in Dummy(y12 is var x12))
var y12 = 12;
}
//void Test13()
//{
// foreach (var i in Dummy(y13 is var x13))
// let y13 = 12;
//}
void Test14()
{
foreach (var i in Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
void Test15()
{
foreach (var x15 in
Dummy(1 is var x15, x15))
{
Dummy(x15);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,45): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i in Dummy(true is var x4 && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 45),
// (35,33): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && true is var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 33),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,50): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(true is var x9 && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 50),
// (68,33): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(y10 is var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 33),
// (86,33): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(y12 is var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 33),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,42): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 42),
// (108,22): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(108, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetPatternDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x15Decl, x15Ref[0]);
VerifyNotAPatternLocal(model, x15Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_Lock_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
lock (Dummy(true is var x1 && x1))
{
Dummy(x1);
}
}
void Test2()
{
lock (Dummy(true is var x2 && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
lock (Dummy(true is var x4 && x4))
Dummy(x4);
}
void Test6()
{
lock (Dummy(x6 && true is var x6))
Dummy(x6);
}
void Test7()
{
lock (Dummy(true is var x7 && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
lock (Dummy(true is var x8 && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
lock (Dummy(true is var x9 && x9))
{
Dummy(x9);
lock (Dummy(true is var x9 && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
lock (Dummy(y10 is var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// lock (Dummy(y11 is var x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
lock (Dummy(y12 is var x12))
var y12 = 12;
}
//void Test13()
//{
// lock (Dummy(y13 is var x13))
// let y13 = 12;
//}
void Test14()
{
lock (Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,33): error CS0128: A local variable named 'x4' is already defined in this scope
// lock (Dummy(true is var x4 && x4))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(29, 33),
// (35,21): error CS0841: Cannot use local variable 'x6' before it is declared
// lock (Dummy(x6 && true is var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 21),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (60,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(60, 19),
// (61,37): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// lock (Dummy(true is var x9 && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 37),
// (68,21): error CS0103: The name 'y10' does not exist in the current context
// lock (Dummy(y10 is var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 21),
// (86,21): error CS0103: The name 'y12' does not exist in the current context
// lock (Dummy(y12 is var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 21),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,30): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 30)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyNotAPatternLocal(model, x4Ref[2]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Lock_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
if (true)
lock (Dummy(true is var x1))
{
}
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (17,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_Lock_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LockStatementSyntax)SyntaxFactory.ParseStatement(@"
lock (Dummy(11 is var x1, x1));
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_Fixed_01()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
void Test1()
{
fixed (int* p = Dummy(true is var x1 && x1))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p = Dummy(true is var x2 && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
fixed (int* p = Dummy(true is var x4 && x4))
Dummy(x4);
}
void Test6()
{
fixed (int* p = Dummy(x6 && true is var x6))
Dummy(x6);
}
void Test7()
{
fixed (int* p = Dummy(true is var x7 && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
fixed (int* p = Dummy(true is var x8 && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
fixed (int* p1 = Dummy(true is var x9 && x9))
{
Dummy(x9);
fixed (int* p2 = Dummy(true is var x9 && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
fixed (int* p = Dummy(y10 is var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// fixed (int* p = Dummy(y11 is var x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
fixed (int* p = Dummy(y12 is var x12))
var y12 = 12;
}
//void Test13()
//{
// fixed (int* p = Dummy(y13 is var x13))
// let y13 = 12;
//}
void Test14()
{
fixed (int* p = Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p = Dummy(true is var x4 && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 43),
// (35,31): error CS0841: Cannot use local variable 'x6' before it is declared
// fixed (int* p = Dummy(x6 && true is var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,48): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p2 = Dummy(true is var x9 && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 48),
// (68,31): error CS0103: The name 'y10' does not exist in the current context
// fixed (int* p = Dummy(y10 is var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 31),
// (86,31): error CS0103: The name 'y12' does not exist in the current context
// fixed (int* p = Dummy(y12 is var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 31),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,40): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Fixed_02()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
int[] Dummy(int* x) {return null;}
void Test1()
{
fixed (int* x1 =
Dummy(true is var x1 && x1))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p = Dummy(true is var x2 && x2),
x2 = Dummy())
{
Dummy(x2);
}
}
void Test3()
{
fixed (int* x3 = Dummy(),
p = Dummy(true is var x3 && x3))
{
Dummy(x3);
}
}
void Test4()
{
fixed (int* p1 = Dummy(true is var x4 && x4),
p2 = Dummy(true is var x4 && x4))
{
Dummy(x4);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
// (14,44): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(true is var x1 && x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 44),
// (14,50): error CS0165: Use of unassigned local variable 'x1'
// Dummy(true is var x1 && x1))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 50),
// (23,21): error CS0128: A local variable named 'x2' is already defined in this scope
// x2 = Dummy())
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21),
// (32,43): error CS0128: A local variable named 'x3' is already defined in this scope
// p = Dummy(true is var x3 && x3))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 43),
// (41,44): error CS0128: A local variable named 'x4' is already defined in this scope
// p2 = Dummy(true is var x4 && x4))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x3Decl);
VerifyNotAPatternLocal(model, x3Ref[0]);
VerifyNotAPatternLocal(model, x3Ref[1]);
var x4Decl = GetPatternDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Decl.Length);
Assert.Equal(3, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl[0], x4Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Yield_01()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null;}
IEnumerable Test1()
{
yield return Dummy(true is var x1, x1);
{
yield return Dummy(true is var x1, x1);
}
yield return Dummy(true is var x1, x1);
}
IEnumerable Test2()
{
yield return Dummy(x2, true is var x2);
}
IEnumerable Test3(int x3)
{
yield return Dummy(true is var x3, x3);
}
IEnumerable Test4()
{
var x4 = 11;
Dummy(x4);
yield return Dummy(true is var x4, x4);
}
IEnumerable Test5()
{
yield return Dummy(true is var x5, x5);
var x5 = 11;
Dummy(x5);
}
//IEnumerable Test6()
//{
// let x6 = 11;
// Dummy(x6);
// yield return Dummy(true is var x6, x6);
//}
//IEnumerable Test7()
//{
// yield return Dummy(true is var x7, x7);
// let x7 = 11;
// Dummy(x7);
//}
IEnumerable Test8()
{
yield return Dummy(true is var x8, x8, false is var x8, x8);
}
IEnumerable Test9(bool y9)
{
if (y9)
yield return Dummy(true is var x9, x9);
}
IEnumerable Test11()
{
Dummy(x11);
yield return Dummy(true is var x11, x11);
}
IEnumerable Test12()
{
yield return Dummy(true is var x12, x12);
Dummy(x12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (16,44): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// yield return Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(16, 44),
// (18,40): error CS0128: A local variable or function named 'x1' is already defined in this scope
// yield return Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(18, 40),
// (23,28): error CS0841: Cannot use local variable 'x2' before it is declared
// yield return Dummy(x2, true is var x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(23, 28),
// (28,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// yield return Dummy(true is var x3, x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(28, 40),
// (35,40): error CS0128: A local variable or function named 'x4' is already defined in this scope
// yield return Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(35, 40),
// (41,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(41, 13),
// (41,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(41, 13),
// (61,61): error CS0128: A local variable or function named 'x8' is already defined in this scope
// yield return Dummy(true is var x8, x8, false is var x8, x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(61, 61),
// (72,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(72, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref);
}
[Fact]
public void ScopeOfPatternVariables_Yield_02()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null;}
IEnumerable Test1()
{
if (true)
yield return Dummy(true is var x1);
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (17,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_Yield_03()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null;}
IEnumerable Test1()
{
SpeculateHere();
yield 0;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (YieldStatementSyntax)SyntaxFactory.ParseStatement(@"
yield return (Dummy(11 is var x1, x1));
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_Catch_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
try {}
catch when (true is var x1 && x1)
{
Dummy(x1);
}
}
void Test4()
{
var x4 = 11;
Dummy(x4);
try {}
catch when (true is var x4 && x4)
{
Dummy(x4);
}
}
void Test6()
{
try {}
catch when (x6 && true is var x6)
{
Dummy(x6);
}
}
void Test7()
{
try {}
catch when (true is var x7 && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
try {}
catch when (true is var x8 && x8)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
}
void Test9()
{
try {}
catch when (true is var x9 && x9)
{
Dummy(x9);
try {}
catch when (true is var x9 && x9) // 2
{
Dummy(x9);
}
}
}
void Test10()
{
try {}
catch when (y10 is var x10)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// try {}
// catch when (y11 is var x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test14()
{
try {}
catch when (Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
void Test15()
{
try {}
catch (System.Exception x15)
when (Dummy(1 is var x15, x15))
{
Dummy(x15);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (25,33): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 33),
// (34,21): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21),
// (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17),
// (58,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34),
// (68,37): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 37),
// (78,21): error CS0103: The name 'y10' does not exist in the current context
// catch when (y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 21),
// (99,36): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 36),
// (110,36): error CS0128: A local variable named 'x15' is already defined in this scope
// when (Dummy(1 is var x15, x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 36)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetPatternDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x15Decl);
VerifyNotAPatternLocal(model, x15Ref[0]);
VerifyNotAPatternLocal(model, x15Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_LabeledStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
a: Dummy(true is var x1, x1);
{
b: Dummy(true is var x1, x1);
}
c: Dummy(true is var x1, x1);
}
void Test2()
{
Dummy(x2, true is var x2);
}
void Test3(int x3)
{
a: Dummy(true is var x3, x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
a: Dummy(true is var x4, x4);
}
void Test5()
{
a: Dummy(true is var x5, x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
//a: Dummy(true is var x6, x6);
//}
//void Test7()
//{
//a: Dummy(true is var x7, x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
a: Dummy(true is var x8, x8, false is var x8, x8);
}
void Test9(bool y9)
{
if (y9)
a: Dummy(true is var x9, x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
a: Dummy(true is var x10, x10);
};
}
void Test11()
{
Dummy(x11);
a: Dummy(true is var x11, x11);
}
void Test12()
{
a: Dummy(true is var x12, x12);
Dummy(x12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// b: Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 31),
// (16,27): error CS0128: A local variable or function named 'x1' is already defined in this scope
// c: Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 27),
// (12,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x1, x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(12, 1),
// (14,1): warning CS0164: This label has not been referenced
// b: Dummy(true is var x1, x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(14, 1),
// (16,1): warning CS0164: This label has not been referenced
// c: Dummy(true is var x1, x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(16, 1),
// (21,15): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2, true is var x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15),
// (26,27): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// a: Dummy(true is var x3, x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 27),
// (26,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x3, x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(26, 1),
// (33,27): error CS0128: A local variable or function named 'x4' is already defined in this scope
// a: Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 27),
// (33,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x4, x4);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(33, 1),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (38,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x5, x5);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(38, 1),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,48): error CS0128: A local variable or function named 'x8' is already defined in this scope
// a: Dummy(true is var x8, x8, false is var x8, x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 48),
// (59,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x8, x8, false is var x8, x8);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(59, 1),
// (65,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(true is var x9, x9);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(true is var x9, x9);").WithLocation(65, 1),
// (65,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x9, x9);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(65, 1),
// (73,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(true is var x10, x10);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(true is var x10, x10);").WithLocation(73, 1),
// (73,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x10, x10);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(73, 1),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (80,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x11, x11);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(80, 1),
// (85,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x12, x12);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(85, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x2").Single();
var x2Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x3").Single();
var x3Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x4").Single();
var x4Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x5").Single();
var x5Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x8Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x8").ToArray();
var x8Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x9").Single();
var x9Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x9").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref);
var x10Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x10").Single();
var x10Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var x11Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x11").Single();
var x11Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
var x12Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x12").Single();
var x12Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref);
}
[Fact]
public void ScopeOfPatternVariables_LabeledStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
if (true)
a: Dummy(true is var x1);
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(true is var x1);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(true is var x1);").WithLocation(13, 1),
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9),
// (13,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_LabeledStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LabeledStatementSyntax)SyntaxFactory.ParseStatement(@"
a: b: c:Dummy(11 is var x1, x1);
");
bool success = model.TryGetSpeculativeSemanticModel(
tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
public static int Data = 2;
void Test1(int val)
{
switch (val)
{
case 0 when Dummy(Dummy(Data is var x1), x1):
Dummy(x1);
break;
case 1 when Dummy(Dummy(Data is var x1), x1):
Dummy(x1);
break;
case 2 when Dummy(Dummy(Data is var x1), x1):
Dummy(x1);
break;
}
}
void Test2(int val)
{
switch (val)
{
case 0 when Dummy(x2, Dummy(Data is var x2)):
Dummy(x2);
break;
}
}
void Test3(int x3, int val)
{
switch (val)
{
case 0 when Dummy(Dummy(Data is var x3), x3):
Dummy(x3);
break;
}
}
void Test4(int val)
{
var x4 = 11;
switch (val)
{
case 0 when Dummy(Dummy(Data is var x4), x4):
Dummy(x4);
break;
case 1 when Dummy(x4): Dummy(x4); break;
}
}
void Test5(int val)
{
switch (val)
{
case 0 when Dummy(Dummy(Data is var x5), x5):
Dummy(x5);
break;
}
var x5 = 11;
Dummy(x5);
}
//void Test6(int val)
//{
// let x6 = 11;
// switch (val)
// {
// case 0 when Dummy(x6):
// Dummy(x6);
// break;
// case 1 when Dummy(Dummy(Data is var x6), x6):
// Dummy(x6);
// break;
// }
//}
//void Test7(int val)
//{
// switch (val)
// {
// case 0 when Dummy(Dummy(Data is var x7), x7):
// Dummy(x7);
// break;
// }
// let x7 = 11;
// Dummy(x7);
//}
void Test8(int val)
{
switch (val)
{
case 0 when Dummy(Dummy(Data is var x8), x8, Dummy(Data is var x8), x8):
Dummy(x8);
break;
}
}
void Test9(int val)
{
switch (val)
{
case 0 when Dummy(x9):
int x9 = 9;
Dummy(x9);
break;
case 2 when Dummy(x9 = 9):
Dummy(x9);
break;
case 1 when Dummy(Dummy(Data is var x9), x9):
Dummy(x9);
break;
}
}
//void Test10(int val)
//{
// switch (val)
// {
// case 1 when Dummy(Dummy(Data is var x10), x10):
// Dummy(x10);
// break;
// case 0 when Dummy(x10):
// let x10 = 10;
// Dummy(x10);
// break;
// case 2 when Dummy(x10 = 10, x10):
// Dummy(x10);
// break;
// }
//}
void Test11(int val)
{
switch (x11 ? val : 0)
{
case 0 when Dummy(x11):
Dummy(x11, 0);
break;
case 1 when Dummy(Dummy(Data is var x11), x11):
Dummy(x11, 1);
break;
}
}
void Test12(int val)
{
switch (x12 ? val : 0)
{
case 0 when Dummy(Dummy(Data is var x12), x12):
Dummy(x12, 0);
break;
case 1 when Dummy(x12):
Dummy(x12, 1);
break;
}
}
void Test13()
{
switch (Dummy(1, Data is var x13) ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case 1 when Dummy(Dummy(Data is var x13), x13):
Dummy(x13);
break;
}
}
void Test14(int val)
{
switch (val)
{
case 1 when Dummy(Dummy(Data is var x14), x14):
Dummy(x14);
Dummy(Dummy(Data is var x14), x14);
Dummy(x14);
break;
}
}
void Test15(int val)
{
switch (val)
{
case 0 when Dummy(Dummy(Data is var x15), x15):
case 1 when Dummy(Dummy(Data is var x15), x15):
Dummy(x15);
break;
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (32,31): error CS0841: Cannot use local variable 'x2' before it is declared
// case 0 when Dummy(x2, Dummy(Data is var x2)):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(32, 31),
// (42,49): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(Dummy(Data is var x3), x3):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(42, 49),
// (53,49): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(Dummy(Data is var x4), x4):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(53, 49),
// (64,49): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(Dummy(Data is var x5), x5):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(64, 49),
// (104,76): error CS0128: A local variable named 'x8' is already defined in this scope
// case 0 when Dummy(Dummy(Data is var x8), x8, Dummy(Data is var x8), x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(104, 76),
// (114,31): error CS0841: Cannot use local variable 'x9' before it is declared
// case 0 when Dummy(x9):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(114, 31),
// (121,49): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(Dummy(Data is var x9), x9):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(121, 49),
// (146,17): error CS0103: The name 'x11' does not exist in the current context
// switch (x11 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(146, 17),
// (148,31): error CS0103: The name 'x11' does not exist in the current context
// case 0 when Dummy(x11):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(148, 31),
// (149,23): error CS0103: The name 'x11' does not exist in the current context
// Dummy(x11, 0);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(149, 23),
// (159,17): error CS0103: The name 'x12' does not exist in the current context
// switch (x12 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(159, 17),
// (164,31): error CS0103: The name 'x12' does not exist in the current context
// case 1 when Dummy(x12):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(164, 31),
// (165,23): error CS0103: The name 'x12' does not exist in the current context
// Dummy(x12, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(165, 23),
// (177,49): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(Dummy(Data is var x13), x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(177, 49),
// (187,49): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(Dummy(Data is var x14), x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(187, 49),
// (200,49): error CS0128: A local variable named 'x15' is already defined in this scope
// case 1 when Dummy(Dummy(Data is var x15), x15):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(200, 49),
// (200,55): error CS0165: Use of unassigned local variable 'x15'
// case 1 when Dummy(Dummy(Data is var x15), x15):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(200, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(6, x1Ref.Length);
for (int i = 0; i < x1Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]);
}
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(4, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[0], x4Ref[1]);
VerifyNotAPatternLocal(model, x4Ref[2]);
VerifyNotAPatternLocal(model, x4Ref[3]);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(3, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref[0], x5Ref[1]);
VerifyNotAPatternLocal(model, x5Ref[2]);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(6, x9Ref.Length);
VerifyNotAPatternLocal(model, x9Ref[0]);
VerifyNotAPatternLocal(model, x9Ref[1]);
VerifyNotAPatternLocal(model, x9Ref[2]);
VerifyNotAPatternLocal(model, x9Ref[3]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref[4], x9Ref[5]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(5, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyNotInScope(model, x11Ref[1]);
VerifyNotInScope(model, x11Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref[3], x11Ref[4]);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(5, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref[1], x12Ref[2]);
VerifyNotInScope(model, x12Ref[3]);
VerifyNotInScope(model, x12Ref[4]);
var x13Decl = GetPatternDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(5, x13Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[1], x13Ref[3], x13Ref[4]);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[1], true);
var x15Decl = GetPatternDeclarations(tree, "x15").ToArray();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Decl.Length);
Assert.Equal(3, x15Ref.Length);
for (int i = 0; i < x15Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x15Decl[0], x15Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x15Decl[1]);
}
[Fact]
public void Scope_SwitchLabelGuard_02()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
Dummy(x1 is var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool Dummy(params object[] trash)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_03()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
while (Dummy(x1 is var y1) && Print(y1)) break;
break;
}
}
static bool Print(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_04()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
do
val = 0;
while (Dummy(x1 is var y1) && Print(y1));
break;
}
}
static bool Print(int x)
{
System.Console.WriteLine(x);
return false;
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_05()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
lock ((object)Dummy(x1 is var y1)) {}
System.Console.WriteLine(y1);
break;
}
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_06()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
if (Dummy(x1 is var y1)) {}
System.Console.WriteLine(y1);
break;
}
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_07()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
switch (Dummy(x1 is var y1))
{
default: break;
}
System.Console.WriteLine(y1);
break;
}
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_08()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
foreach (var x in Test(1)) {}
}
static System.Collections.IEnumerable Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
yield return Dummy(x1 is var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_09()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
var z1 = x1 > 0 & Dummy(x1 is var y1);
System.Console.WriteLine(y1);
System.Console.WriteLine(z1);
break;
}
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
True").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(yRef).Type.ToTestDisplayString());
var zRef = GetReferences(tree, "z1").Single();
Assert.Equal("System.Boolean", compilation.GetSemanticModel(tree).GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_10()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
var z1 = Dummy(123, x1 is var y1);
System.Console.WriteLine(y1);
System.Console.WriteLine(z1);
break;
}
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
True").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var xRef = GetReferences(tree, "x1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef).Type.ToTestDisplayString());
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(yRef).Type.ToTestDisplayString());
var zRef = GetReferences(tree, "z1").Single();
Assert.Equal("System.Boolean", compilation.GetSemanticModel(tree).GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_11()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
System.Console.WriteLine(Test(1));
}
static bool Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
return Dummy(123, x1 is var y1) && Dummy(y1);
System.Console.WriteLine(y1);
break;
}
return false;
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "True").VerifyDiagnostics(
// (17,17): warning CS0162: Unreachable code detected
// System.Console.WriteLine(y1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(17, 17));
var tree = compilation.SyntaxTrees.Single();
var xRef = GetReferences(tree, "x1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef).Type.ToTestDisplayString());
var yRefs = GetReferences(tree, "y1");
Assert.Equal(2, yRefs.Count());
foreach (var yRef in yRefs)
{
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(yRef).Type.ToTestDisplayString());
}
}
[Fact]
public void Scope_SwitchLabelGuard_12()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static bool Test(int val)
{
try
{
switch (val)
{
case 1 when Data is var x1:
throw Dummy(123, x1 is var y1);
System.Console.WriteLine(y1);
break;
}
}
catch { }
return false;
}
static System.Exception Dummy(params object[] data)
{
foreach(var obj in data)
{
System.Console.WriteLine(obj);
}
return new System.Exception();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123
True").VerifyDiagnostics(
// (19,21): warning CS0162: Unreachable code detected
// System.Console.WriteLine(y1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(19, 21));
var tree = compilation.SyntaxTrees.Single();
var xRef = GetReferences(tree, "x1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef).Type.ToTestDisplayString());
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_SwitchLabelGuard_13()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
System.Console.WriteLine(Test(1));
}
static bool Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
var (z0, z1) = (x1, Dummy(x1, x1 is var y1));
System.Console.WriteLine(y1);
System.Console.WriteLine(z0);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
return false;
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(
source: source,
options: TestOptions.DebugExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
2
1
False").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var y1Ref = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(y1Ref).Type.ToTestDisplayString());
var z0Ref = GetReferences(tree, "z0").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(z0Ref).Type.ToTestDisplayString());
var z1Ref = GetReferences(tree, "z1").Single();
Assert.Equal("System.Boolean", compilation.GetSemanticModel(tree).GetTypeInfo(z1Ref).Type.ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_SwitchLabelGuard_14()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
System.Console.WriteLine(Test(1));
}
static bool Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
var (z0, (z1, z2)) = (x1, (Data, Dummy(x1, x1 is var y1)));
System.Console.WriteLine(y1);
System.Console.WriteLine(z0);
System.Console.WriteLine(z1);
System.Console.WriteLine(z2);
break;
}
return false;
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(
source: source,
options: TestOptions.DebugExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
2
2
True
False").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var y1Ref = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(y1Ref).Type.ToTestDisplayString());
var z0Ref = GetReferences(tree, "z0").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(z0Ref).Type.ToTestDisplayString());
var z1Ref = GetReferences(tree, "z1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(z1Ref).Type.ToTestDisplayString());
var z2Ref = GetReferences(tree, "z2").Single();
Assert.Equal("System.Boolean", compilation.GetSemanticModel(tree).GetTypeInfo(z2Ref).Type.ToTestDisplayString());
}
[Fact]
public void Scope_DeclaratorArguments_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
int d,e(Dummy(true is var x1, x1));
}
void Test4()
{
var x4 = 11;
Dummy(x4);
int d,e(Dummy(true is var x4, x4));
}
void Test6()
{
int d,e(Dummy(x6 && true is var x6));
}
void Test8()
{
int d,e(Dummy(true is var x8, x8));
System.Console.WriteLine(x8);
}
void Test14()
{
int d,e(Dummy(1 is var x14,
2 is var x14,
x14));
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (19,35): error CS0128: A local variable or function named 'x4' is already defined in this scope
// int d,e(Dummy(true is var x4, x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 35),
// (24,23): error CS0841: Cannot use local variable 'x6' before it is declared
// int d,e(Dummy(x6 && true is var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23),
// (30,34): error CS0165: Use of unassigned local variable 'x8'
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(30, 34),
// (36,32): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 32)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x6Decl, x6Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x8Decl, x8Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var d, x1(
Dummy(true is var x1, x1));
Dummy(x1);
}
void Test2()
{
object d, x2(
Dummy(true is var x2, x2));
Dummy(x2);
}
void Test3()
{
object x3, d(
Dummy(true is var x3, x3));
Dummy(x3);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (12,13): error CS0818: Implicitly-typed variables must be initialized
// var d, x1(
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(12, 13),
// (13,36): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(true is var x1, x1));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 36),
// (20,39): error CS0128: A local variable or function named 'x2' is already defined in this scope
// Dummy(true is var x2, x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 39),
// (21,15): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 15),
// (27,39): error CS0128: A local variable or function named 'x3' is already defined in this scope
// Dummy(true is var x3, x3));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(27, 39),
// (28,15): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(28, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyNotAPatternLocal(model, x2Ref[0]);
VerifyNotAPatternLocal(model, x2Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyNotAPatternLocal(model, x3Ref[0]);
VerifyNotAPatternLocal(model, x3Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x3Decl);
}
[Fact]
public void Scope_DeclaratorArguments_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d,e(Dummy(true is var x1, x1)],
x1( Dummy(x1));
Dummy(x1);
}
void Test2()
{
object d1,e(Dummy(true is var x2, x2)],
d2(Dummy(true is var x2, x2));
}
void Test3()
{
object d1,e(Dummy(true is var x3, x3)],
d2(Dummy(x3));
}
void Test4()
{
object d1,e(Dummy(x4)],
d2(Dummy(true is var x4, x4));
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,16): error CS0128: A local variable or function named 'x1' is already defined in this scope
// x1( Dummy(x1));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (14,15): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 15),
// (20,39): error CS0128: A local variable or function named 'x2' is already defined in this scope
// d2(Dummy(true is var x2, x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 39),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1,e(Dummy(x4)],
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d,e(Dummy(true is var x1, x1)],
x1 = Dummy(x1);
Dummy(x1);
}
void Test2()
{
object d1,e(Dummy(true is var x2, x2)],
d2 = Dummy(true is var x2, x2);
}
void Test3()
{
object d1,e(Dummy(true is var x3, x3)],
d2 = Dummy(x3);
}
void Test4()
{
object d1 = Dummy(x4),
d2 (Dummy(true is var x4, x4));
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,16): error CS0128: A local variable or function named 'x1' is already defined in this scope
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (13,27): error CS0165: Use of unassigned local variable 'x1'
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 27),
// (20,39): error CS0128: A local variable or function named 'x2' is already defined in this scope
// d2 = Dummy(true is var x2, x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 39),
// (20,43): error CS0165: Use of unassigned local variable 'x2'
// d2 = Dummy(true is var x2, x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 43),
// (26,27): error CS0165: Use of unassigned local variable 'x3'
// d2 = Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(26, 27),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl[0]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
long Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"
var y, y1(Dummy(3 is var x1, x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
var y1 = model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single();
Assert.Equal("var y1", y1.ToTestDisplayString());
Assert.True(((ILocalSymbol)y1).Type.IsErrorType());
}
[Fact]
public void Scope_DeclaratorArguments_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var d,e(string.Empty is var x1 && x1 != null);
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var d,e(string.Empty is var x1 && x1 != null);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d,e(string.Empty is var x1 && x1 != null);").WithLocation(11, 13),
// (11,17): error CS0818: Implicitly-typed variables must be initialized
// var d,e(string.Empty is var x1 && x1 != null);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(11, 17),
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var e = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "e").Single();
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(e);
Assert.Equal("var e", symbol.ToTestDisplayString());
Assert.True(symbol.Type.IsErrorType());
}
[Fact]
[WorkItem(13460, "https://github.com/dotnet/roslyn/issues/13460")]
public void Scope_DeclaratorArguments_07()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when 123 is var x1:
var z, z1(x1, out var u1, x1 > 0 & x1 is var y1];
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetPatternDeclarations(tree, "y1").Single();
AssertContainedInDeclaratorArguments(y1Decl);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.True(model.GetTypeInfo(zRef).Type.IsErrorType());
}
[Fact]
[WorkItem(13459, "https://github.com/dotnet/roslyn/issues/13459")]
public void Scope_DeclaratorArguments_08()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (bool a, b(
Dummy(true is var x1 && x1)
);;)
{
Dummy(x1);
}
}
void Test2()
{
for (bool a, b(
Dummy(true is var x2 && x2)
);;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (bool a, b(
Dummy(true is var x4 && x4)
);;)
Dummy(x4);
}
void Test6()
{
for (bool a, b(
Dummy(x6 && true is var x6)
);;)
Dummy(x6);
}
void Test7()
{
for (bool a, b(
Dummy(true is var x7 && x7)
);;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (bool a, b(
Dummy(true is var x8 && x8)
);;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (bool a1, b1(
Dummy(true is var x9 && x9)
);;)
{
Dummy(x9);
for (bool a2, b2(
Dummy(true is var x9 && x9) // 2
);;)
Dummy(x9);
}
}
void Test10()
{
for (bool a, b(
Dummy(y10 is var x10)
);;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (bool a, b(
// Dummy(y11 is var x11)
// );;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (bool a, b(
Dummy(y12 is var x12)
);;)
var y12 = 12;
}
//void Test13()
//{
// for (bool a, b(
// Dummy(y13 is var x13)
// );;)
// let y13 = 12;
//}
void Test14()
{
for (bool a, b(
Dummy(1 is var x14,
2 is var x14,
x14)
);;)
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,32): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 32),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,36): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 36),
// (85,20): error CS0103: The name 'y10' does not exist in the current context
// Dummy(y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 20),
// (107,20): error CS0103: The name 'y12' does not exist in the current context
// Dummy(y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 20),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,29): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_09()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test4()
{
for (bool d, x4(
Dummy(true is var x4 && x4)
);;)
{}
}
void Test7()
{
for (bool x7 = true, b(
Dummy(true is var x7 && x7)
);;)
{}
}
void Test8()
{
for (bool d,b1(Dummy(true is var x8 && x8)],
b2(Dummy(true is var x8 && x8));
Dummy(true is var x8 && x8);
Dummy(true is var x8 && x8))
{}
}
void Test9()
{
for (bool b = x9,
b2(Dummy(true is var x9 && x9));
Dummy(true is var x9 && x9);
Dummy(true is var x9 && x9))
{}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,32): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 32),
// (21,32): error CS0128: A local variable or function named 'x7' is already defined in this scope
// Dummy(true is var x7 && x7)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(21, 32),
// (20,19): warning CS0219: The variable 'x7' is assigned but its value is never used
// for (bool x7 = true, b(
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x7").WithArguments("x7").WithLocation(20, 19),
// (29,37): error CS0128: A local variable or function named 'x8' is already defined in this scope
// b2(Dummy(true is var x8 && x8));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(29, 37),
// (30,32): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x8 && x8);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(30, 32),
// (31,32): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x8 && x8))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(31, 32),
// (37,23): error CS0841: Cannot use local variable 'x9' before it is declared
// for (bool b = x9,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(37, 23),
// (39,32): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(39, 32),
// (40,32): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(40, 32)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
VerifyNotAPatternLocal(model, x4Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x7Decl);
VerifyNotAPatternLocal(model, x7Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(4, x8Decl.Length);
Assert.Equal(4, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl[0]);
AssertContainedInDeclaratorArguments(x8Decl[1]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x8Decl[0], x8Ref[0], x8Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[2], x8Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[3], x8Ref[3]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(3, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl[0]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[2], x9Ref[3]);
}
[Fact]
public void Scope_DeclaratorArguments_10()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d,e(Dummy(true is var x1, x1)))
{
Dummy(x1);
}
}
void Test2()
{
using (var d,e(Dummy(true is var x2, x2)))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (var d,e(Dummy(true is var x4, x4)))
Dummy(x4);
}
void Test6()
{
using (var d,e(Dummy(x6 && true is var x6)))
Dummy(x6);
}
void Test7()
{
using (var d,e(Dummy(true is var x7 && x7)))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (var d,e(Dummy(true is var x8, x8)))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (var d,a(Dummy(true is var x9, x9)))
{
Dummy(x9);
using (var e,b(Dummy(true is var x9, x9))) // 2
Dummy(x9);
}
}
void Test10()
{
using (var d,e(Dummy(y10 is var x10, x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (var d,e(Dummy(y11 is var x11, x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (var d,e(Dummy(y12 is var x12, x12)))
var y12 = 12;
}
//void Test13()
//{
// using (var d,e(Dummy(y13 is var x13, x13)))
// let y13 = 12;
//}
void Test14()
{
using (var d,e(Dummy(1 is var x14,
2 is var x14,
x14)))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var d,e(Dummy(true is var x4, x4)))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 42),
// (35,30): error CS0841: Cannot use local variable 'x6' before it is declared
// using (var d,e(Dummy(x6 && true is var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var e,b(Dummy(true is var x9, x9))) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 46),
// (68,30): error CS0103: The name 'y10' does not exist in the current context
// using (var d,e(Dummy(y10 is var x10, x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 30),
// (86,30): error CS0103: The name 'y12' does not exist in the current context
// using (var d,e(Dummy(y12 is var x12, x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 30),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,39): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 39)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
AssertContainedInDeclaratorArguments(x10Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_11()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d,x1(Dummy(true is var x1, x1)))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d,x2(Dummy(true is var x2, x2)))
{
Dummy(x2);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (12,43): error CS0128: A local variable or function named 'x1' is already defined in this scope
// using (var d,x1(Dummy(true is var x1, x1)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 43),
// (20,58): error CS0128: A local variable or function named 'x2' is already defined in this scope
// using (System.IDisposable d,x2(Dummy(true is var x2, x2)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 58)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
AssertContainedInDeclaratorArguments(x2Decl);
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl);
VerifyNotAPatternLocal(model, x2Ref[0]);
VerifyNotAPatternLocal(model, x2Ref[1]);
}
[Fact]
public void Scope_DeclaratorArguments_12()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d,e(Dummy(true is var x1, x1)],
x1 = Dummy(x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d1,e(Dummy(true is var x2, x2)],
d2(Dummy(true is var x2, x2)))
{
Dummy(x2);
}
}
void Test3()
{
using (System.IDisposable d1,e(Dummy(true is var x3, x3)],
d2 = Dummy(x3))
{
Dummy(x3);
}
}
void Test4()
{
using (System.IDisposable d1 = Dummy(x4),
d2(Dummy(true is var x4, x4)))
{
Dummy(x4);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,35): error CS0128: A local variable or function named 'x1' is already defined in this scope
// x1 = Dummy(x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35),
// (22,58): error CS0128: A local variable or function named 'x2' is already defined in this scope
// d2(Dummy(true is var x2, x2)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 58),
// (39,46): error CS0841: Cannot use local variable 'x4' before it is declared
// using (System.IDisposable d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(3, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_13()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
void Test1()
{
fixed (int* p,e(Dummy(true is var x1 && x1)))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p,e(Dummy(true is var x2 && x2)))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
fixed (int* p,e(Dummy(true is var x4 && x4)))
Dummy(x4);
}
void Test6()
{
fixed (int* p,e(Dummy(x6 && true is var x6)))
Dummy(x6);
}
void Test7()
{
fixed (int* p,e(Dummy(true is var x7 && x7)))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
fixed (int* p,e(Dummy(true is var x8 && x8)))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
fixed (int* p1,a(Dummy(true is var x9 && x9)))
{
Dummy(x9);
fixed (int* p2,b(Dummy(true is var x9 && x9))) // 2
Dummy(x9);
}
}
void Test10()
{
fixed (int* p,e(Dummy(y10 is var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// fixed (int* p,e(Dummy(y11 is var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
fixed (int* p,e(Dummy(y12 is var x12)))
var y12 = 12;
}
//void Test13()
//{
// fixed (int* p,e(Dummy(y13 is var x13)))
// let y13 = 12;
//}
void Test14()
{
fixed (int* p,e(Dummy(1 is var x14,
2 is var x14,
x14)))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p,e(Dummy(true is var x4 && x4)))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 43),
// (35,31): error CS0841: Cannot use local variable 'x6' before it is declared
// fixed (int* p,e(Dummy(x6 && true is var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,48): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p2,b(Dummy(true is var x9 && x9))) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 48),
// (68,31): error CS0103: The name 'y10' does not exist in the current context
// fixed (int* p,e(Dummy(y10 is var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 31),
// (86,31): error CS0103: The name 'y12' does not exist in the current context
// fixed (int* p,e(Dummy(y12 is var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 31),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,40): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_14()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
int[] Dummy(int* x) {return null;}
void Test1()
{
fixed (int* d,x1(
Dummy(true is var x1 && x1)))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* d,p(Dummy(true is var x2 && x2)],
x2 = Dummy())
{
Dummy(x2);
}
}
void Test3()
{
fixed (int* x3 = Dummy(),
p(Dummy(true is var x3 && x3)))
{
Dummy(x3);
}
}
void Test4()
{
fixed (int* d,p1(Dummy(true is var x4 && x4)],
p2(Dummy(true is var x4 && x4)))
{
Dummy(x4);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (14,44): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(true is var x1 && x1)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 44),
// (23,21): error CS0128: A local variable or function named 'x2' is already defined in this scope
// x2 = Dummy())
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21),
// (32,43): error CS0128: A local variable or function named 'x3' is already defined in this scope
// p(Dummy(true is var x3 && x3)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 43),
// (41,44): error CS0128: A local variable or function named 'x4' is already defined in this scope
// p2(Dummy(true is var x4 && x4)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x3Decl);
VerifyNotAPatternLocal(model, x3Ref[0]);
VerifyNotAPatternLocal(model, x3Ref[1]);
var x4Decl = GetPatternDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Decl.Length);
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl[0], x4Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_15()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 [3 is var x3 && x3 > 0];
bool Test4 [x4 && 4 is var x4];
bool Test5 [51 is var x5 &&
52 is var x5 &&
x5 > 0];
bool Test61 [6 is var x6 && x6 > 0], Test62 [6 is var x6 && x6 > 0];
bool Test71 [7 is var x7 && x7 > 0];
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.WRN_UnreferencedField
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_16()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed
bool Test3 [3 is var x3 && x3 > 0];
fixed
bool Test4 [x4 && 4 is var x4];
fixed
bool Test5 [51 is var x5 &&
52 is var x5 &&
x5 > 0];
fixed
bool Test61 [6 is var x6 && x6 > 0], Test62 [6 is var x6 && x6 > 0];
fixed
bool Test71 [7 is var x7 && x7 > 0];
fixed
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.WRN_UnreferencedField,
(int)ErrorCode.ERR_NoImplicitConv
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (10,18): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 [x4 && 4 is var x4];
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18),
// (13,28): error CS0128: A local variable or function named 'x5' is already defined in this scope
// 52 is var x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 28),
// (20,25): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 [Dummy(x7, 2)];
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 25),
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_17()
{
var source =
@"
public class X
{
public static void Main()
{
}
const
bool Test3 [3 is var x3 && x3 > 0];
const
bool Test4 [x4 && 4 is var x4];
const
bool Test5 [51 is var x5 &&
52 is var x5 &&
x5 > 0];
const
bool Test61 [6 is var x6 && x6 > 0], Test62 [6 is var x6 && x6 > 0];
const
bool Test71 [7 is var x7 && x7 > 0];
const
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_18()
{
var source =
@"
public class X
{
public static void Main()
{
}
event
bool Test3 [3 is var x3 && x3 > 0];
event
bool Test4 [x4 && 4 is var x4];
event
bool Test5 [51 is var x5 &&
52 is var x5 &&
x5 > 0];
event
bool Test61 [6 is var x6 && x6 > 0], Test62 [6 is var x6 && x6 > 0];
event
bool Test71 [7 is var x7 && x7 > 0];
event
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.ERR_EventNotDelegate,
(int)ErrorCode.WRN_UnreferencedEvent
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_19()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed bool d[2], Test3 (string.Empty is var x3);
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (8,28): error CS1003: Syntax error, '[' expected
// fixed bool d[2], Test3 (string.Empty is var x3);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(8, 28),
// (8,51): error CS1003: Syntax error, ']' expected
// fixed bool d[2], Test3 (string.Empty is var x3);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(8, 51),
// (8,29): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed bool d[2], Test3 (string.Empty is var x3);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty is var x3").WithArguments("bool", "int").WithLocation(8, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl);
}
[Fact]
public void Scope_DeclaratorArguments_20()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed bool Test3[string.Empty is var x3];
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,22): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed bool Test3[string.Empty is var x3];
Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty is var x3").WithArguments("bool", "int").WithLocation(8, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl);
}
[Fact]
public void DeclarationInsideNameof()
{
string source = @"
class Program
{
static void Main(int i)
{
string s = nameof(M(i is var x1, x1)).ToString();
string s1 = x1;
}
static void M(bool b, int i) {}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,27): error CS8081: Expression does not have a name.
// string s = nameof(M(i is var x1, x1)).ToString();
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(i is var x1, x1)").WithLocation(6, 27),
// (7,21): error CS0029: Cannot implicitly convert type 'int' to 'string'
// string s1 = x1;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("int", "string").WithLocation(7, 21),
// (7,21): error CS0165: Use of unassigned local variable 'x1'
// string s1 = x1;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 21)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designation = GetPatternDeclarations(tree).Single();
var refs = GetReferences(tree, "x1").ToArray();
VerifyModelForDeclarationOrVarSimplePattern(model, designation, refs);
var x1 = (ILocalSymbol)model.GetDeclaredSymbol(designation);
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_ArrayDeclarationInvalidDimensions()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
int[true is var x1, x1] _1;
{
int[true is var x1, x1] _2;
}
int[true is var x1, x1] _3;
}
void Test2()
{
int[x2, true is var x2] _4;
}
void Test3(int x3)
{
int[true is var x3, x3] _5;
}
void Test4()
{
var x4 = 11;
int[x4] _6;
int[true is var x4, x4] _7;
}
void Test5()
{
int[true is var x5, x5] _8;
var x5 = 11;
int[x5] _9;
}
void Test6()
{
int[true is var x6, x6, false is var x6, x6] _10;
}
void Test7(bool y7)
{
if (y7)
int[true is var x7, x7] _11;
}
System.Action Test8(bool y8)
{
return () =>
{
if (y8)
int[true is var x8, x8] _12;
};
}
void Test9()
{
int[x9] _13;
int[true is var x9, x9] _13;
}
void Test10()
{
int[true is var x10, x10] _14;
int[x10] _15;
}
void Test11()
{
int[true is var x11, x11] x11;
int[x11] _16;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
int[] exclude = new int[] { (int)ErrorCode.ERR_NoImplicitConv, (int)ErrorCode.WRN_UnreferencedVar };
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (10,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x1, x1] _1;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x1, x1]").WithLocation(10, 12),
// (12,16): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x1, x1] _2;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x1, x1]").WithLocation(12, 16),
// (12,29): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int[true is var x1, x1] _2;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(12, 29),
// (14,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x1, x1] _3;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x1, x1]").WithLocation(14, 12),
// (14,25): error CS0128: A local variable or function named 'x1' is already defined in this scope
// int[true is var x1, x1] _3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 25),
// (19,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[x2, true is var x2] _4;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[x2, true is var x2]").WithLocation(19, 12),
// (19,13): error CS0841: Cannot use local variable 'x2' before it is declared
// int[x2, true is var x2] _4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(19, 13),
// (24,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x3, x3] _5;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x3, x3]").WithLocation(24, 12),
// (24,25): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int[true is var x3, x3] _5;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(24, 25),
// (29,13): warning CS0219: The variable 'x4' is assigned but its value is never used
// var x4 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x4").WithArguments("x4").WithLocation(29, 13),
// (30,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[x4] _6;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[x4]").WithLocation(30, 12),
// (31,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x4, x4] _7;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x4, x4]").WithLocation(31, 12),
// (31,25): error CS0128: A local variable or function named 'x4' is already defined in this scope
// int[true is var x4, x4] _7;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(31, 25),
// (36,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x5, x5] _8;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x5, x5]").WithLocation(36, 12),
// (37,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(37, 13),
// (37,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(37, 13),
// (38,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[x5] _9;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[x5]").WithLocation(38, 12),
// (43,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x6, x6, false is var x6, x6] _10;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x6, x6, false is var x6, x6]").WithLocation(43, 12),
// (43,46): error CS0128: A local variable or function named 'x6' is already defined in this scope
// int[true is var x6, x6, false is var x6, x6] _10;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(43, 46),
// (49,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// int[true is var x7, x7] _11;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "int[true is var x7, x7] _11;").WithLocation(49, 13),
// (49,16): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x7, x7] _11;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x7, x7]").WithLocation(49, 16),
// (57,25): error CS1023: Embedded statement cannot be a declaration or labeled statement
// int[true is var x8, x8] _12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "int[true is var x8, x8] _12;").WithLocation(57, 25),
// (57,28): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x8, x8] _12;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x8, x8]").WithLocation(57, 28),
// (63,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[x9] _13;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[x9]").WithLocation(63, 12),
// (63,13): error CS0841: Cannot use local variable 'x9' before it is declared
// int[x9] _13;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(63, 13),
// (64,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x9, x9] _13;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x9, x9]").WithLocation(64, 12),
// (64,33): error CS0128: A local variable or function named '_13' is already defined in this scope
// int[true is var x9, x9] _13;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "_13").WithArguments("_13").WithLocation(64, 33),
// (69,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x10, x10] _14;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x10, x10]").WithLocation(69, 12),
// (70,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[x10] _15;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[x10]").WithLocation(70, 12),
// (75,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x11, x11] x11;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x11, x11]").WithLocation(75, 12),
// (75,35): error CS0128: A local variable or function named 'x11' is already defined in this scope
// int[true is var x11, x11] x11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x11").WithArguments("x11").WithLocation(75, 35),
// (76,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[x11] _16;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[x11]").WithLocation(76, 12)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
for (int i = 0; i < x6Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
var x11Decl2 = GetVariableDeclarations(tree, "x11").Single();
Assert.Equal(2, x11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref[0], x11Ref[1]);
VerifyModelForDuplicateVariableDeclarationInSameScope(model, x11Decl2);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.Patterns)]
public class PatternMatchingTests_Scope : PatternMatchingTestBase
{
[Fact]
[WorkItem(13029, "https://github.com/dotnet/roslyn/issues/13029")]
public void ScopeOfLocalFunction()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test14(int val)
{
switch (val)
{
case 1 when TakeOutParam(true, out var x14):
void x14() {return;};
break;
case 2:
x14();
break;
}
switch (val)
{
case 1 when Dummy(1 is var x14):
void x14() {return;};
break;
case 2:
x14();
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,52): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when TakeOutParam(true, out var x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(14, 52),
// (24,40): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(1 is var x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(24, 40));
}
[Fact]
public void ScopeOfPatternVariables_ExpressionStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
Dummy(true is var x1, x1);
{
Dummy(true is var x1, x1);
}
Dummy(true is var x1, x1);
}
void Test2()
{
Dummy(x2, true is var x2);
}
void Test3(int x3)
{
Dummy(true is var x3, x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
Dummy(true is var x4, x4);
}
void Test5()
{
Dummy(true is var x5, x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
// Dummy(true is var x6, x6);
//}
//void Test7()
//{
// Dummy(true is var x7, x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
Dummy(true is var x8, x8, false is var x8, x8);
}
void Test9(bool y9)
{
if (y9)
Dummy(true is var x9, x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
Dummy(true is var x10, x10);
};
}
void Test11()
{
Dummy(x11);
Dummy(true is var x11, x11);
}
void Test12()
{
Dummy(true is var x12, x12);
Dummy(x12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (14,31): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 31),
// (16,27): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 27),
// (21,15): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2, true is var x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15),
// (26,27): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x3, x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 27),
// (33,27): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 27),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,48): error CS0128: A local variable or function named 'x8' is already defined in this scope
// Dummy(true is var x8, x8, false is var x8, x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 48),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref);
}
[Fact]
public void ScopeOfPatternVariables_ExpressionStatement_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(2 is var x1);
System.Console.WriteLine(x1);
}
static object Test1(bool x)
{
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_ExpressionStatement_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
bool test = true;
if (test)
Test2(1 is var x1, x1);
if (test)
{
Test2(2 is var x1, x1);
}
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "12").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_ExpressionStatement_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
if (true)
Dummy(true is var x1);
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_ExpressionStatement_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@"
Dummy(11 is var x1, x1);
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact, WorkItem(9258, "https://github.com/dotnet/roslyn/issues/9258")]
public void PatternVariableOrder()
{
var source =
@"
public class X
{
public static void Main()
{
}
static void Dummy(params object[] x) {}
void Test1(object o1, object o2)
{
Dummy(o1 is int i && i < 10,
o2 is int @i && @i > 10);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,25): error CS0128: A local variable named 'i' is already defined in this scope
// o2 is int @i && @i > 10);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "@i").WithArguments("i").WithLocation(13, 25),
// (13,31): error CS0165: Use of unassigned local variable 'i'
// o2 is int @i && @i > 10);
Diagnostic(ErrorCode.ERR_UseDefViolation, "@i").WithArguments("i").WithLocation(13, 31)
);
}
[Fact]
public void ScopeOfPatternVariables_ReturnStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null; }
object Test1()
{
return Dummy(true is var x1, x1);
{
return Dummy(true is var x1, x1);
}
return Dummy(true is var x1, x1);
}
object Test2()
{
return Dummy(x2, true is var x2);
}
object Test3(int x3)
{
return Dummy(true is var x3, x3);
}
object Test4()
{
var x4 = 11;
Dummy(x4);
return Dummy(true is var x4, x4);
}
object Test5()
{
return Dummy(true is var x5, x5);
var x5 = 11;
Dummy(x5);
}
//object Test6()
//{
// let x6 = 11;
// Dummy(x6);
// return Dummy(true is var x6, x6);
//}
//object Test7()
//{
// return Dummy(true is var x7, x7);
// let x7 = 11;
// Dummy(x7);
//}
object Test8()
{
return Dummy(true is var x8, x8, false is var x8, x8);
}
object Test9(bool y9)
{
if (y9)
return Dummy(true is var x9, x9);
return null;
}
System.Func<object> Test10(bool y10)
{
return () =>
{
if (y10)
return Dummy(true is var x10, x10);
return null;};
}
object Test11()
{
Dummy(x11);
return Dummy(true is var x11, x11);
}
object Test12()
{
return Dummy(true is var x12, x12);
Dummy(x12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (14,38): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// return Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 38),
// (16,34): error CS0128: A local variable or function named 'x1' is already defined in this scope
// return Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 34),
// (14,13): warning CS0162: Unreachable code detected
// return Dummy(true is var x1, x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(14, 13),
// (21,22): error CS0841: Cannot use local variable 'x2' before it is declared
// return Dummy(x2, true is var x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 22),
// (26,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// return Dummy(true is var x3, x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 34),
// (33,34): error CS0128: A local variable or function named 'x4' is already defined in this scope
// return Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 34),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,9): warning CS0162: Unreachable code detected
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,55): error CS0128: A local variable or function named 'x8' is already defined in this scope
// return Dummy(true is var x8, x8, false is var x8, x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 55),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (86,9): warning CS0162: Unreachable code detected
// Dummy(x12);
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref);
}
[Fact]
public void ScopeOfPatternVariables_ReturnStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
int Dummy(params object[] x) {return 0;}
int Test1(bool val)
{
if (val)
return Dummy(true is var x1);
x1++;
return 0;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_ReturnStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ReturnStatementSyntax)SyntaxFactory.ParseStatement(@"
return Dummy(11 is var x1, x1);
");
bool success = model.TryGetSpeculativeSemanticModel(
tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_ThrowStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Exception Dummy(params object[] x) { return null;}
void Test1()
{
throw Dummy(true is var x1, x1);
{
throw Dummy(true is var x1, x1);
}
throw Dummy(true is var x1, x1);
}
void Test2()
{
throw Dummy(x2, true is var x2);
}
void Test3(int x3)
{
throw Dummy(true is var x3, x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
throw Dummy(true is var x4, x4);
}
void Test5()
{
throw Dummy(true is var x5, x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
// throw Dummy(true is var x6, x6);
//}
//void Test7()
//{
// throw Dummy(true is var x7, x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
throw Dummy(true is var x8, x8, false is var x8, x8);
}
void Test9(bool y9)
{
if (y9)
throw Dummy(true is var x9, x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
throw Dummy(true is var x10, x10);
};
}
void Test11()
{
Dummy(x11);
throw Dummy(true is var x11, x11);
}
void Test12()
{
throw Dummy(true is var x12, x12);
Dummy(x12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (14,37): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// throw Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 37),
// (16,33): error CS0128: A local variable or function named 'x1' is already defined in this scope
// throw Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 33),
// (21,21): error CS0841: Cannot use local variable 'x2' before it is declared
// throw Dummy(x2, true is var x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 21),
// (26,33): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// throw Dummy(true is var x3, x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 33),
// (33,33): error CS0128: A local variable or function named 'x4' is already defined in this scope
// throw Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 33),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,9): warning CS0162: Unreachable code detected
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,54): error CS0128: A local variable or function named 'x8' is already defined in this scope
// throw Dummy(true is var x8, x8, false is var x8, x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 54),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (86,9): warning CS0162: Unreachable code detected
// Dummy(x12);
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref);
}
[Fact]
public void ScopeOfPatternVariables_ThrowStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Exception Dummy(params object[] x) { return null;}
void Test1(bool val)
{
if (val)
throw Dummy(true is var x1);
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_TrowStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ThrowStatementSyntax)SyntaxFactory.ParseStatement(@"
throw Dummy(11 is var x1, x1);
");
bool success = model.TryGetSpeculativeSemanticModel(
tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact, WorkItem(9121, "https://github.com/dotnet/roslyn/issues/9121")]
public void ScopeOfPatternVariables_If_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true is var x1)
{
Dummy(x1);
}
else
{
System.Console.WriteLine(x1);
}
}
void Test2()
{
if (true is var x2)
Dummy(x2);
else
System.Console.WriteLine(x2);
}
void Test3()
{
if (true is var x3)
Dummy(x3);
else
{
var x3 = 12;
System.Console.WriteLine(x3);
}
}
void Test4()
{
var x4 = 11;
Dummy(x4);
if (true is var x4)
Dummy(x4);
}
void Test5(int x5)
{
if (true is var x5)
Dummy(x5);
}
void Test6()
{
if (x6 && true is var x6)
Dummy(x6);
}
void Test7()
{
if (true is var x7 && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
if (true is var x8)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
if (true is var x9)
{
Dummy(x9);
if (true is var x9) // 2
Dummy(x9);
}
}
void Test10()
{
if (y10 is var x10)
{
var y10 = 12;
Dummy(y10);
}
}
void Test12()
{
if (y12 is var x12)
var y12 = 12;
}
//void Test13()
//{
// if (y13 is var x13)
// let y13 = 12;
//}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (110,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(110, 13),
// (36,17): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x3 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(36, 17),
// (46,25): error CS0128: A local variable named 'x4' is already defined in this scope
// if (true is var x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(46, 25),
// (52,25): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// if (true is var x5)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(52, 25),
// (58,13): error CS0841: Cannot use local variable 'x6' before it is declared
// if (x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(58, 13),
// (66,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(66, 17),
// (83,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(83, 19),
// (84,29): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// if (true is var x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(84, 29),
// (91,13): error CS0103: The name 'y10' does not exist in the current context
// if (y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(91, 13),
// (109,13): error CS0103: The name 'y12' does not exist in the current context
// if (y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(109, 13),
// (110,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(110, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref[0]);
VerifyNotAPatternLocal(model, x3Ref[1]);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
}
[Fact]
public void ScopeOfPatternVariables_If_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
if (true is var x1)
{
}
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (17,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_If_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (IfStatementSyntax)SyntaxFactory.ParseStatement(@"
if (Dummy(11 is var x1, x1));
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_Lambda_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
System.Action<object> Test1()
{
return (o) => let x1 = o;
}
System.Action<object> Test2()
{
return (o) => let var x2 = o;
}
void Test3()
{
Dummy((System.Func<object, bool>) (o => o is int x3 && x3 > 0));
}
void Test4()
{
Dummy((System.Func<object, bool>) (o => x4 && o is int x4));
}
void Test5()
{
Dummy((System.Func<object, object, bool>) ((o1, o2) => o1 is int x5 &&
o2 is int x5 &&
x5 > 0));
}
void Test6()
{
Dummy((System.Func<object, bool>) (o => o is int x6 && x6 > 0), (System.Func<object, bool>) (o => o is int x6 && x6 > 0));
}
void Test7()
{
Dummy(x7, 1);
Dummy(x7,
(System.Func<object, bool>) (o => o is int x7 && x7 > 0),
x7);
Dummy(x7, 2);
}
void Test8()
{
Dummy(true is var x8 && x8, (System.Func<object, bool>) (o => o is int y8 && x8));
}
void Test9()
{
Dummy(true is var x9,
(System.Func<object, bool>) (o => o is int x9 &&
x9 > 0), x9);
}
void Test10()
{
Dummy((System.Func<object, bool>) (o => o is int x10 &&
x10 > 0),
true is var x10, x10);
}
void Test11()
{
var x11 = 11;
Dummy(x11);
Dummy((System.Func<object, bool>) (o => o is int x11 &&
x11 > 0), x11);
}
void Test12()
{
Dummy((System.Func<object, bool>) (o => o is int x12 &&
x12 > 0),
x12);
var x12 = 11;
Dummy(x12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (12,27): error CS1002: ; expected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27),
// (17,27): error CS1002: ; expected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27),
// (12,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23),
// (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23),
// (12,27): error CS0103: The name 'x1' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27),
// (12,32): error CS0103: The name 'o' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32),
// (12,27): warning CS0162: Unreachable code detected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27),
// (17,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23),
// (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23),
// (17,36): error CS0103: The name 'o' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36),
// (17,27): warning CS0162: Unreachable code detected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27),
// (27,49): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && o is int x4));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49),
// (33,74): error CS0128: A local variable or function named 'x5' is already defined in this scope
// o2 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 74),
// (44,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15),
// (45,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15),
// (47,15): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15),
// (48,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15),
// (82,15): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15)
);
compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (12,27): error CS1002: ; expected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27),
// (17,27): error CS1002: ; expected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27),
// (12,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23),
// (12,23): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23),
// (12,27): error CS0103: The name 'x1' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27),
// (12,32): error CS0103: The name 'o' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32),
// (12,27): warning CS0162: Unreachable code detected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27),
// (17,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23),
// (17,23): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23),
// (17,36): error CS0103: The name 'o' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36),
// (17,27): warning CS0162: Unreachable code detected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27),
// (27,49): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && o is int x4));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49),
// (33,74): error CS0128: A local variable or function named 'x5' is already defined in this scope
// o2 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 74),
// (44,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15),
// (45,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15),
// (47,15): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15),
// (48,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15),
// (59,58): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// (System.Func<object, bool>) (o => o is int x9 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(59, 58),
// (65,58): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => o is int x10 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(65, 58),
// (74,58): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => o is int x11 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(74, 58),
// (80,58): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => o is int x12 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(80, 58),
// (82,15): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetPatternDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl[0], x10Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAPatternLocal(model, x11Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref[1]);
VerifyNotAPatternLocal(model, x11Ref[2]);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref[0]);
VerifyNotAPatternLocal(model, x12Ref[1]);
VerifyNotAPatternLocal(model, x12Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_Query_01()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x in new[] { 1 is var y1 ? y1 : 0, y1}
select x + y1;
Dummy(y1);
}
void Test2()
{
var res = from x1 in new[] { 1 is var y2 ? y2 : 0}
from x2 in new[] { x1 is var z2 ? z2 : 0, z2, y2}
select x1 + x2 + y2 +
z2;
Dummy(z2);
}
void Test3()
{
var res = from x1 in new[] { 1 is var y3 ? y3 : 0}
let x2 = x1 is var z3 && z3 > 0 && y3 < 0
select new { x1, x2, y3,
z3};
Dummy(z3);
}
void Test4()
{
var res = from x1 in new[] { 1 is var y4 ? y4 : 0}
join x2 in new[] { 2 is var z4 ? z4 : 0, z4, y4}
on x1 + y4 + z4 + 3 is var u4 ? u4 : 0 +
v4
equals x2 + y4 + z4 + 4 is var v4 ? v4 : 0 +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
}
void Test5()
{
var res = from x1 in new[] { 1 is var y5 ? y5 : 0}
join x2 in new[] { 2 is var z5 ? z5 : 0, z5, y5}
on x1 + y5 + z5 + 3 is var u5 ? u5 : 0 +
v5
equals x2 + y5 + z5 + 4 is var v5 ? v5 : 0 +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
}
void Test6()
{
var res = from x in new[] { 1 is var y6 ? y6 : 0}
where x > y6 && 1 is var z6 && z6 == 1
select x + y6 +
z6;
Dummy(z6);
}
void Test7()
{
var res = from x in new[] { 1 is var y7 ? y7 : 0}
orderby x > y7 && 1 is var z7 && z7 ==
u7,
x > y7 && 1 is var u7 && u7 ==
z7
select x + y7 +
z7 + u7;
Dummy(z7);
Dummy(u7);
}
void Test8()
{
var res = from x in new[] { 1 is var y8 ? y8 : 0}
select x > y8 && 1 is var z8 && z8 == 1;
Dummy(z8);
}
void Test9()
{
var res = from x in new[] { 1 is var y9 ? y9 : 0}
group x > y9 && 1 is var z9 && z9 ==
u9
by
x > y9 && 1 is var u9 && u9 ==
z9;
Dummy(z9);
Dummy(u9);
}
void Test10()
{
var res = from x1 in new[] { 1 is var y10 ? y10 : 0}
from y10 in new[] { 1 }
select x1 + y10;
}
void Test11()
{
var res = from x1 in new[] { 1 is var y11 ? y11 : 0}
let y11 = x1 + 1
select x1 + y11;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (25,26): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(25, 26),
// (27,15): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(27, 15),
// (35,32): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(35, 32),
// (37,15): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(37, 15),
// (45,35): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(45, 35),
// (47,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(47, 35),
// (49,32): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(49, 32),
// (49,36): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(49, 36),
// (52,15): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(52, 15),
// (53,15): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(53, 15),
// (61,35): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(61, 35),
// (63,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(63, 35),
// (66,32): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(66, 32),
// (66,36): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(66, 36),
// (69,15): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(69, 15),
// (70,15): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(70, 15),
// (78,26): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(78, 26),
// (80,15): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(80, 15),
// (87,27): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(87, 27),
// (89,27): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(89, 27),
// (91,26): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(91, 26),
// (91,31): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(91, 31),
// (93,15): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(93, 15),
// (94,15): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(94, 15),
// (102,15): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(102, 15),
// (112,25): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(112, 25),
// (109,25): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(109, 25),
// (114,15): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(114, 15),
// (115,15): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(115, 15),
// (121,24): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10'
// from y10 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(121, 24),
// (128,23): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11'
// let y11 = x1 + 1
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(128, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetPatternDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y1Decl, y1Ref);
var y2Decl = GetPatternDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y2Decl, y2Ref);
var z2Decl = GetPatternDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetPatternDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y3Decl, y3Ref);
var z3Decl = GetPatternDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetPatternDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y4Decl, y4Ref);
var z4Decl = GetPatternDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z4Decl, z4Ref);
var u4Decl = GetPatternDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetPatternDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetPatternDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y5Decl, y5Ref);
var z5Decl = GetPatternDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z5Decl, z5Ref);
var u5Decl = GetPatternDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetPatternDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetPatternDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y6Decl, y6Ref);
var z6Decl = GetPatternDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetPatternDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y7Decl, y7Ref);
var z7Decl = GetPatternDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetPatternDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetPatternDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y8Decl, y8Ref);
var z8Decl = GetPatternDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetPatternDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y9Decl, y9Ref);
var z9Decl = GetPatternDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetPatternDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetPatternDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y10Decl, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y11Decl = GetPatternDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y11Decl, y11Ref[0]);
VerifyNotAPatternLocal(model, y11Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_Query_03()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test4()
{
var res = from x1 in new[] { 1 is var y4 ? y4 : 0}
select x1 into x1
join x2 in new[] { 2 is var z4 ? z4 : 0, z4, y4}
on x1 + y4 + z4 + 3 is var u4 ? u4 : 0 +
v4
equals x2 + y4 + z4 + 4 is var v4 ? v4 : 0 +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
}
void Test5()
{
var res = from x1 in new[] { 1 is var y5 ? y5 : 0}
select x1 into x1
join x2 in new[] { 2 is var z5 ? z5 : 0, z5, y5}
on x1 + y5 + z5 + 3 is var u5 ? u5 : 0 +
v5
equals x2 + y5 + z5 + 4 is var v5 ? v5 : 0 +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (18,35): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(18, 35),
// (20,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(20, 35),
// (22,32): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(22, 32),
// (22,36): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(22, 36),
// (25,15): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(25, 15),
// (26,15): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(26, 15),
// (35,35): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(35, 35),
// (37,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(37, 35),
// (40,32): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(40, 32),
// (40,36): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(40, 36),
// (43,15): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(43, 15),
// (44,15): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(44, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y4Decl = GetPatternDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y4Decl, y4Ref);
var z4Decl = GetPatternDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z4Decl, z4Ref);
var u4Decl = GetPatternDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetPatternDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetPatternDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y5Decl, y5Ref);
var z5Decl = GetPatternDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, z5Decl, z5Ref);
var u5Decl = GetPatternDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetPatternDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void ScopeOfPatternVariables_Query_05()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
int y1 = 0, y2 = 0, y3 = 0, y4 = 0, y5 = 0, y6 = 0, y7 = 0, y8 = 0, y9 = 0, y10 = 0, y11 = 0, y12 = 0;
var res = from x1 in new[] { 1 is var y1 ? y1 : 0}
from x2 in new[] { 2 is var y2 ? y2 : 0}
join x3 in new[] { 3 is var y3 ? y3 : 0}
on 4 is var y4 ? y4 : 0
equals 5 is var y5 ? y5 : 0
where 6 is var y6 && y6 == 1
orderby 7 is var y7 && y7 > 0,
8 is var y8 && y8 > 0
group 9 is var y9 && y9 > 0
by 10 is var y10 && y10 > 0
into g
let x11 = 11 is var y11 && y11 > 0
select 12 is var y12 && y12 > 0
into s
select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12;
Dummy(y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (16,47): error CS0128: A local variable or function named 'y1' is already defined in this scope
// var res = from x1 in new[] { 1 is var y1 ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 47),
// (18,47): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { 3 is var y3 ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 47)
);
compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (16,47): error CS0128: A local variable or function named 'y1' is already defined in this scope
// var res = from x1 in new[] { 1 is var y1 ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 47),
// (17,47): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { 2 is var y2 ? y2 : 0}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(17, 47),
// (18,47): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { 3 is var y3 ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 47),
// (19,36): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on 4 is var y4 ? y4 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(19, 36),
// (20,43): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals 5 is var y5 ? y5 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(20, 43),
// (21,34): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where 6 is var y6 && y6 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(21, 34),
// (22,36): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby 7 is var y7 && y7 > 0,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(22, 36),
// (23,36): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// 8 is var y8 && y8 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(23, 36),
// (25,32): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by 10 is var y10 && y10 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(25, 32),
// (24,34): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group 9 is var y9 && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(24, 34),
// (27,39): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x11 = 11 is var y11 && y11 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(27, 39),
// (28,36): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select 12 is var y12 && y12 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(28, 36)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetPatternDeclarations(tree, id).Single();
var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).ToArray();
Assert.Equal(3, yRef.Length);
switch (i)
{
case 1:
case 3:
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, yDecl);
VerifyNotAPatternLocal(model, yRef[0]);
break;
default:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef[0]);
break;
}
VerifyNotAPatternLocal(model, yRef[2]);
switch (i)
{
case 1:
case 3:
case 12:
VerifyNotAPatternLocal(model, yRef[1]);
break;
default:
VerifyNotAPatternLocal(model, yRef[1]);
break;
}
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void ScopeOfPatternVariables_Query_06()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
Dummy(1 is int y1,
2 is int y2,
3 is int y3,
4 is int y4,
5 is int y5,
6 is int y6,
7 is int y7,
8 is int y8,
9 is int y9,
10 is int y10,
11 is int y11,
12 is int y12,
from x1 in new[] { 1 is var y1 ? y1 : 0}
from x2 in new[] { 2 is var y2 ? y2 : 0}
join x3 in new[] { 3 is var y3 ? y3 : 0}
on 4 is var y4 ? y4 : 0
equals 5 is var y5 ? y5 : 0
where 6 is var y6 && y6 == 1
orderby 7 is var y7 && y7 > 0,
8 is var y8 && y8 > 0
group 9 is var y9 && y9 > 0
by 10 is var y10 && y10 > 0
into g
let x11 = 11 is var y11 && y11 > 0
select 12 is var y12 && y12 > 0
into s
select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (26,47): error CS0128: A local variable or function named 'y1' is already defined in this scope
// from x1 in new[] { 1 is var y1 ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 47),
// (28,47): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { 3 is var y3 ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 47)
);
compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (26,47): error CS0128: A local variable or function named 'y1' is already defined in this scope
// from x1 in new[] { 1 is var y1 ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 47),
// (27,47): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { 2 is var y2 ? y2 : 0}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(27, 47),
// (28,47): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { 3 is var y3 ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 47),
// (29,36): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on 4 is var y4 ? y4 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(29, 36),
// (30,43): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals 5 is var y5 ? y5 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(30, 43),
// (31,34): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where 6 is var y6 && y6 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(31, 34),
// (32,36): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby 7 is var y7 && y7 > 0,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(32, 36),
// (33,36): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// 8 is var y8 && y8 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(33, 36),
// (35,32): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by 10 is var y10 && y10 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(35, 32),
// (34,34): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group 9 is var y9 && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(34, 34),
// (37,39): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x11 = 11 is var y11 && y11 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(37, 39),
// (38,36): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select 12 is var y12 && y12 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(38, 36)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetPatternDeclarations(tree, id).ToArray();
var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).ToArray();
Assert.Equal(2, yDecl.Length);
Assert.Equal(2, yRef.Length);
switch (i)
{
case 1:
case 3:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl[0], yRef);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, yDecl[1]);
break;
case 12:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl[0], yRef[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl[1], yRef[0]);
break;
default:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl[0], yRef[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl[1], yRef[0]);
break;
}
}
}
[Fact]
public void ScopeOfPatternVariables_Query_07()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
Dummy(7 is int y3,
from x1 in new[] { 0 }
select x1
into x1
join x3 in new[] { 3 is var y3 ? y3 : 0}
on x1 equals x3
select y3);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (18,47): error CS0128: A local variable named 'y3' is already defined in this scope
// join x3 in new[] { 3 is var y3 ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
const string id = "y3";
var yDecl = GetPatternDeclarations(tree, id).ToArray();
var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).ToArray();
Assert.Equal(2, yDecl.Length);
Assert.Equal(2, yRef.Length);
// Since the name is declared twice in the same scope,
// both references are to the same declaration.
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl[0], yRef);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, yDecl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Query_08()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x1 in new[] { Dummy(1 is var y1,
2 is var y2,
3 is var y3,
4 is var y4
) ? 1 : 0}
from y1 in new[] { 1 }
join y2 in new[] { 0 }
on y1 equals y2
let y3 = 0
group y3
by x1
into y4
select y4;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (19,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1'
// from y1 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(19, 24),
// (20,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2'
// join y2 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(20, 24),
// (22,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3'
// let y3 = 0
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(22, 23),
// (25,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4'
// into y4
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(25, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 5; i++)
{
var id = "y" + i;
var yDecl = GetPatternDeclarations(tree, id).Single();
var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).Single();
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl);
VerifyNotAPatternLocal(model, yRef);
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void ScopeOfPatternVariables_Query_09()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from y1 in new[] { 0 }
join y2 in new[] { 0 }
on y1 equals y2
let y3 = 0
group y3
by 1
into y4
select y4 == null ? 1 : 0
into x2
join y5 in new[] { Dummy(1 is var y1,
2 is var y2,
3 is var y3,
4 is var y4,
5 is var y5
) ? 1 : 0 }
on x2 equals y5
select x2;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (14,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1'
// var res = from y1 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(14, 24),
// (15,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2'
// join y2 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(15, 24),
// (17,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3'
// let y3 = 0
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(17, 23),
// (20,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4'
// into y4
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(20, 24),
// (23,24): error CS1931: The range variable 'y5' conflicts with a previous declaration of 'y5'
// join y5 in new[] { Dummy(1 is var y1,
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y5").WithArguments("y5").WithLocation(23, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 6; i++)
{
var id = "y" + i;
var yDecl = GetPatternDeclarations(tree, id).Single();
var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).Single();
switch (i)
{
case 4:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl);
VerifyNotAPatternLocal(model, yRef);
break;
case 5:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl);
VerifyNotAPatternLocal(model, yRef);
break;
default:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl);
VerifyNotAPatternLocal(model, yRef);
break;
}
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
[WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")]
public void ScopeOfPatternVariables_Query_10()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from y1 in new[] { 0 }
from x2 in new[] { 1 is var y1 ? y1 : 1 }
select y1;
}
void Test2()
{
var res = from y2 in new[] { 0 }
join x3 in new[] { 1 }
on 2 is var y2 ? y2 : 0
equals x3
select y2;
}
void Test3()
{
var res = from x3 in new[] { 0 }
join y3 in new[] { 1 }
on x3
equals 3 is var y3 ? y3 : 0
select y3;
}
void Test4()
{
var res = from y4 in new[] { 0 }
where 4 is var y4 && y4 == 1
select y4;
}
void Test5()
{
var res = from y5 in new[] { 0 }
orderby 5 is var y5 && y5 > 1,
1
select y5;
}
void Test6()
{
var res = from y6 in new[] { 0 }
orderby 1,
6 is var y6 && y6 > 1
select y6;
}
void Test7()
{
var res = from y7 in new[] { 0 }
group 7 is var y7 && y7 == 3
by y7;
}
void Test8()
{
var res = from y8 in new[] { 0 }
group y8
by 8 is var y8 && y8 == 3;
}
void Test9()
{
var res = from y9 in new[] { 0 }
let x4 = 9 is var y9 && y9 > 0
select y9;
}
void Test10()
{
var res = from y10 in new[] { 0 }
select 10 is var y10 && y10 > 0;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
// error CS0412 is misleading and reported due to preexisting bug https://github.com/dotnet/roslyn/issues/12052
compilation.VerifyDiagnostics(
// (15,47): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { 1 is var y1 ? y1 : 1 }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(15, 47),
// (23,36): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on 2 is var y2 ? y2 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(23, 36),
// (33,40): error CS0136: A local or parameter named 'y3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals 3 is var y3 ? y3 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y3").WithArguments("y3").WithLocation(33, 40),
// (40,34): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where 4 is var y4 && y4 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(40, 34),
// (47,36): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby 5 is var y5 && y5 > 1,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(47, 36),
// (56,36): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// 6 is var y6 && y6 > 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(56, 36),
// (63,34): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group 7 is var y7 && y7 == 3
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(63, 34),
// (71,31): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by 8 is var y8 && y8 == 3;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(71, 31),
// (77,37): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x4 = 9 is var y9 && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(77, 37),
// (84,36): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select 10 is var y10 && y10 > 0;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(84, 36)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 11; i++)
{
var id = "y" + i;
var yDecl = GetPatternDeclarations(tree, id).Single();
var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).ToArray();
Assert.Equal(i == 10 ? 1 : 2, yRef.Length);
switch (i)
{
case 4:
case 6:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef[0]);
VerifyNotAPatternLocal(model, yRef[1]);
break;
case 8:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef[1]);
VerifyNotAPatternLocal(model, yRef[0]);
break;
case 10:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef[0]);
break;
default:
VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef[0]);
VerifyNotAPatternLocal(model, yRef[1]);
break;
}
}
}
[Fact]
public void ScopeOfPatternVariables_Query_11()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x1 in new [] { 1 }
where Dummy(x1 is var y1,
from x2 in new [] { 1 }
where x1 is var y1
select x2)
select x1;
}
void Test2()
{
var res = from x1 in new [] { 1 }
where Dummy(x1 is var y2,
x1 + 1 is var y2)
select x1;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (26,45): error CS0128: A local variable or function named 'y2' is already defined in this scope
// x1 + 1 is var y2)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 45)
);
compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (17,47): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where x1 is var y1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(17, 47),
// (26,45): error CS0128: A local variable or function named 'y2' is already defined in this scope
// x1 + 1 is var y2)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 45)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetPatternDeclarations(tree, "y1").ToArray();
Assert.Equal(2, y1Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y1Decl[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, y1Decl[1]);
var y2Decl = GetPatternDeclarations(tree, "y2").ToArray();
Assert.Equal(2, y2Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, y2Decl[0]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, y2Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_ExpressionBodiedLocalFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
void f(object o) => let x1 = o;
f(null);
}
void Test2()
{
void f(object o) => let var x2 = o;
f(null);
}
void Test3()
{
bool f (object o) => o is int x3 && x3 > 0;
f(null);
}
void Test4()
{
bool f (object o) => x4 && o is int x4;
f(null);
}
void Test5()
{
bool f (object o1, object o2) => o1 is int x5 &&
o2 is int x5 &&
x5 > 0;
f(null, null);
}
void Test6()
{
bool f1 (object o) => o is int x6 && x6 > 0; bool f2 (object o) => o is int x6 && x6 > 0;
f1(null);
f2(null);
}
void Test7()
{
Dummy(x7, 1);
bool f (object o) => o is int x7 && x7 > 0;
Dummy(x7, 2);
f(null);
}
void Test11()
{
var x11 = 11;
Dummy(x11);
bool f (object o) => o is int x11 &&
x11 > 0;
f(null);
}
void Test12()
{
bool f (object o) => o is int x12 &&
x12 > 0;
var x12 = 11;
Dummy(x12);
f(null);
}
System.Action Test13()
{
return () =>
{
bool f (object o) => o is int x13 && x13 > 0;
f(null);
};
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (12,33): error CS1002: ; expected
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 33),
// (18,33): error CS1002: ; expected
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(18, 33),
// (12,29): error CS0103: The name 'let' does not exist in the current context
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 29),
// (12,29): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 29),
// (12,33): error CS0103: The name 'x1' does not exist in the current context
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 33),
// (12,38): error CS0103: The name 'o' does not exist in the current context
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 38),
// (18,29): error CS0103: The name 'let' does not exist in the current context
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(18, 29),
// (18,29): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(18, 29),
// (18,42): error CS0103: The name 'o' does not exist in the current context
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(18, 42),
// (30,30): error CS0841: Cannot use local variable 'x4' before it is declared
// bool f (object o) => x4 && o is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(30, 30),
// (37,52): error CS0128: A local variable or function named 'x5' is already defined in this scope
// o2 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(37, 52),
// (51,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(51, 15),
// (55,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(55, 15)
);
compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (12,29): error CS0103: The name 'let' does not exist in the current context
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 29),
// (12,29): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 29),
// (12,33): error CS1002: ; expected
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 33),
// (12,33): error CS0103: The name 'x1' does not exist in the current context
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 33),
// (12,38): error CS0103: The name 'o' does not exist in the current context
// void f(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 38),
// (18,29): error CS0103: The name 'let' does not exist in the current context
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(18, 29),
// (18,29): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(18, 29),
// (18,33): error CS1002: ; expected
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(18, 33),
// (18,42): error CS0103: The name 'o' does not exist in the current context
// void f(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(18, 42),
// (30,30): error CS0841: Cannot use local variable 'x4' before it is declared
// bool f (object o) => x4 && o is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(30, 30),
// (37,52): error CS0128: A local variable or function named 'x5' is already defined in this scope
// o2 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(37, 52),
// (51,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(51, 15),
// (55,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(55, 15),
// (63,39): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool f (object o) => o is int x11 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(63, 39),
// (70,39): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool f (object o) => o is int x12 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(70, 39)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyNotAPatternLocal(model, x11Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref[1]);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref[0]);
VerifyNotAPatternLocal(model, x12Ref[1]);
var x13Decl = GetPatternDeclarations(tree, "x13").Single();
var x13Ref = GetReferences(tree, "x13").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl, x13Ref);
}
[Fact]
public void ExpressionBodiedLocalFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
bool f() => 1 is int x1 && Dummy(x1);
return f();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void ScopeOfPatternVariables_ExpressionBodiedFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1(object o) => let x1 = o;
void Test2(object o) => let var x2 = o;
bool Test3(object o) => o is int x3 && x3 > 0;
bool Test4(object o) => x4 && o is int x4;
bool Test5(object o1, object o2) => o1 is int x5 &&
o2 is int x5 &&
x5 > 0;
bool Test61 (object o) => o is int x6 && x6 > 0; bool Test62 (object o) => o is int x6 && x6 > 0;
bool Test71(object o) => o is int x7 && x7 > 0;
void Test72() => Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Test11(object x11) => 1 is int x11 &&
x11 > 0;
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (9,33): error CS1002: ; expected
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(9, 33),
// (9,36): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 36),
// (9,36): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 36),
// (9,39): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(9, 39),
// (9,39): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(9, 39),
// (11,33): error CS1002: ; expected
// void Test2(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(11, 33),
// (11,33): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// void Test2(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(11, 33),
// (11,42): error CS0103: The name 'o' does not exist in the current context
// void Test2(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(11, 42),
// (9,29): error CS0103: The name 'let' does not exist in the current context
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(9, 29),
// (9,29): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
// void Test1(object o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(9, 29),
// (11,29): error CS0103: The name 'let' does not exist in the current context
// void Test2(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(11, 29),
// (11,29): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
// void Test2(object o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(11, 29),
// (15,29): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4(object o) => x4 && o is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(15, 29),
// (18,52): error CS0128: A local variable or function named 'x5' is already defined in this scope
// o2 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 52),
// (24,28): error CS0103: The name 'x7' does not exist in the current context
// void Test72() => Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(24, 28),
// (25,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(25, 27),
// (27,41): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool Test11(object x11) => 1 is int x11 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(27, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
}
[Fact]
public void ScopeOfPatternVariables_ExpressionBodiedProperties_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test1 => let x1 = 11;
bool this[int o] => let var x2 = o;
bool Test3 => 3 is int x3 && x3 > 0;
bool Test4 => x4 && 4 is int x4;
bool Test5 => 51 is int x5 &&
52 is int x5 &&
x5 > 0;
bool Test61 => 6 is int x6 && x6 > 0; bool Test62 => 6 is int x6 && x6 > 0;
bool Test71 => 7 is int x7 && x7 > 0;
bool Test72 => Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool this[object x11] => 1 is int x11 &&
x11 > 0;
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (9,23): error CS1002: ; expected
// bool Test1 => let x1 = 11;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(9, 23),
// (9,26): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration
// bool Test1 => let x1 = 11;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 26),
// (9,26): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration
// bool Test1 => let x1 = 11;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 26),
// (11,29): error CS1002: ; expected
// bool this[int o] => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(11, 29),
// (11,29): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// bool this[int o] => let var x2 = o;
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(11, 29),
// (11,38): error CS0103: The name 'o' does not exist in the current context
// bool this[int o] => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(11, 38),
// (9,19): error CS0103: The name 'let' does not exist in the current context
// bool Test1 => let x1 = 11;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(9, 19),
// (11,25): error CS0103: The name 'let' does not exist in the current context
// bool this[int o] => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(11, 25),
// (15,19): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 => x4 && 4 is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(15, 19),
// (18,29): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 29),
// (24,26): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 => Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(24, 26),
// (25,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(25, 27),
// (27,39): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool this[object x11] => 1 is int x11 &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(27, 39)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
}
[Fact]
public void ScopeOfPatternVariables_FieldInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 = 3 is int x3 && x3 > 0;
bool Test4 = x4 && 4 is int x4;
bool Test5 = 51 is int x5 &&
52 is int x5 &&
x5 > 0;
bool Test61 = 6 is int x6 && x6 > 0, Test62 = 6 is int x6 && x6 > 0;
bool Test71 = 7 is int x7 && x7 > 0;
bool Test72 = Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Test81 = 8 is int x8, Test82 = x8 > 0;
bool Test91 = x9 > 0, Test92 = 9 is int x9;
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (10,18): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 = x4 && 4 is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18),
// (13,28): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 28),
// (19,25): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 = Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,41): error CS0103: The name 'x8' does not exist in the current context
// bool Test81 = 8 is int x8, Test82 = x8 > 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(22, 41),
// (23,19): error CS0103: The name 'x9' does not exist in the current context
// bool Test91 = x9 > 0, Test92 = 9 is int x9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(23, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReference(tree, "x8");
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl);
VerifyNotInScope(model, x8Ref);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReference(tree, "x9");
VerifyNotInScope(model, x9Ref);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl);
}
[Fact]
public void ScopeOfPatternVariables_FieldInitializers_02()
{
var source =
@"
public enum X
{
Test3 = 3 is int x3 ? x3 : 0,
Test4 = x4 && 4 is int x4 ? 1 : 0,
Test5 = 51 is int x5 &&
52 is int x5 &&
x5 > 0 ? 1 : 0,
Test61 = 6 is int x6 && x6 > 0 ? 1 : 0, Test62 = 6 is int x6 && x6 > 0 ? 1 : 0,
Test71 = 7 is int x7 && x7 > 0 ? 1 : 0,
Test72 = x7,
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics(
// (6,13): error CS0841: Cannot use local variable 'x4' before it is declared
// Test4 = x4 && 4 is int x4 ? 1 : 0,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 13),
// (9,23): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 23),
// (12,14): error CS0133: The expression being assigned to 'X.Test61' must be constant
// Test61 = 6 is int x6 && x6 > 0 ? 1 : 0, Test62 = 6 is int x6 && x6 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "6 is int x6 && x6 > 0 ? 1 : 0").WithArguments("X.Test61").WithLocation(12, 14),
// (12,54): error CS0133: The expression being assigned to 'X.Test62' must be constant
// Test61 = 6 is int x6 && x6 > 0 ? 1 : 0, Test62 = 6 is int x6 && x6 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "6 is int x6 && x6 > 0 ? 1 : 0").WithArguments("X.Test62").WithLocation(12, 54),
// (14,14): error CS0133: The expression being assigned to 'X.Test71' must be constant
// Test71 = 7 is int x7 && x7 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "7 is int x7 && x7 > 0 ? 1 : 0").WithArguments("X.Test71").WithLocation(14, 14),
// (15,14): error CS0103: The name 'x7' does not exist in the current context
// Test72 = x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 14),
// (4,13): error CS0133: The expression being assigned to 'X.Test3' must be constant
// Test3 = 3 is int x3 ? x3 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "3 is int x3 ? x3 : 0").WithArguments("X.Test3").WithLocation(4, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_FieldInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
const bool Test3 = 3 is int x3 && x3 > 0;
const bool Test4 = x4 && 4 is int x4;
const bool Test5 = 51 is int x5 &&
52 is int x5 &&
x5 > 0;
const bool Test61 = 6 is int x6 && x6 > 0, Test62 = 6 is int x6 && x6 > 0;
const bool Test71 = 7 is int x7 && x7 > 0;
const bool Test72 = x7 > 2;
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (8,24): error CS0133: The expression being assigned to 'X.Test3' must be constant
// const bool Test3 = 3 is int x3 && x3 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "3 is int x3 && x3 > 0").WithArguments("X.Test3").WithLocation(8, 24),
// (10,24): error CS0841: Cannot use local variable 'x4' before it is declared
// const bool Test4 = x4 && 4 is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 24),
// (13,34): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 34),
// (16,25): error CS0133: The expression being assigned to 'X.Test61' must be constant
// const bool Test61 = 6 is int x6 && x6 > 0, Test62 = 6 is int x6 && x6 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "6 is int x6 && x6 > 0").WithArguments("X.Test61").WithLocation(16, 25),
// (16,57): error CS0133: The expression being assigned to 'X.Test62' must be constant
// const bool Test61 = 6 is int x6 && x6 > 0, Test62 = 6 is int x6 && x6 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "6 is int x6 && x6 > 0").WithArguments("X.Test62").WithLocation(16, 57),
// (18,25): error CS0133: The expression being assigned to 'X.Test71' must be constant
// const bool Test71 = 7 is int x7 && x7 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "7 is int x7 && x7 > 0").WithArguments("X.Test71").WithLocation(18, 25),
// (19,25): error CS0103: The name 'x7' does not exist in the current context
// const bool Test72 = x7 > 2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_PropertyInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 {get;} = 3 is int x3 && x3 > 0;
bool Test4 {get;} = x4 && 4 is int x4;
bool Test5 {get;} = 51 is int x5 &&
52 is int x5 &&
x5 > 0;
bool Test61 {get;} = 6 is int x6 && x6 > 0; bool Test62 {get;} = 6 is int x6 && x6 > 0;
bool Test71 {get;} = 7 is int x7 && x7 > 0;
bool Test72 {get;} = Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (10,25): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 {get;} = x4 && 4 is int x4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 25),
// (13,28): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 28),
// (19,32): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 {get;} = Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 32),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_ParameterDefault_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test3(bool p = 3 is int x3 && x3 > 0)
{}
void Test4(bool p = x4 && 4 is int x4)
{}
void Test5(bool p = 51 is int x5 &&
52 is int x5 &&
x5 > 0)
{}
void Test61(bool p1 = 6 is int x6 && x6 > 0, bool p2 = 6 is int x6 && x6 > 0)
{}
void Test71(bool p = 7 is int x7 && x7 > 0)
{
}
void Test72(bool p = x7 > 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test3(bool p = 3 is int x3 && x3 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "3 is int x3 && x3 > 0").WithArguments("p").WithLocation(8, 25),
// (11,25): error CS0841: Cannot use local variable 'x4' before it is declared
// void Test4(bool p = x4 && 4 is int x4)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25),
// (15,35): error CS0128: A local variable or function named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 35),
// (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant
// void Test61(bool p1 = 6 is int x6 && x6 > 0, bool p2 = 6 is int x6 && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "6 is int x6 && x6 > 0").WithArguments("p1").WithLocation(19, 27),
// (19,60): error CS1736: Default parameter value for 'p2' must be a compile-time constant
// void Test61(bool p1 = 6 is int x6 && x6 > 0, bool p2 = 6 is int x6 && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "6 is int x6 && x6 > 0").WithArguments("p2").WithLocation(19, 60),
// (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test71(bool p = 7 is int x7 && x7 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "7 is int x7 && x7 > 0").WithArguments("p").WithLocation(22, 26),
// (26,26): error CS0103: The name 'x7' does not exist in the current context
// void Test72(bool p = x7 > 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26),
// (29,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_Attribute_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(p = 3 is int x3 && x3 > 0)]
[Test(p = x4 && 4 is int x4)]
[Test(p = 51 is int x5 &&
52 is int x5 &&
x5 > 0)]
[Test(p1 = 6 is int x6 && x6 > 0, p2 = 6 is int x6 && x6 > 0)]
[Test(p = 7 is int x7 && x7 > 0)]
[Test(p = x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = 3 is int x3 && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "3 is int x3 && x3 > 0").WithLocation(8, 15),
// (9,15): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && 4 is int x4)]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15),
// (11,25): error CS0128: A local variable or function named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 25),
// (13,53): error CS0128: A local variable or function named 'x6' is already defined in this scope
// [Test(p1 = 6 is int x6 && x6 > 0, p2 = 6 is int x6 && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 53),
// (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p1 = 6 is int x6 && x6 > 0, p2 = 6 is int x6 && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "6 is int x6 && x6 > 0").WithLocation(13, 16),
// (14,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = 7 is int x7 && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "7 is int x7 && x7 > 0").WithLocation(14, 15),
// (15,15): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 15),
// (16,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_Attribute_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(3 is int x3 && x3 > 0)]
[Test(x4 && 4 is int x4)]
[Test(51 is int x5 &&
52 is int x5 &&
x5 > 0)]
[Test(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)]
[Test(7 is int x7 && x7 > 0)]
[Test(x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(3 is int x3 && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "3 is int x3 && x3 > 0").WithLocation(8, 11),
// (9,11): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && 4 is int x4)]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11),
// (11,21): error CS0128: A local variable or function named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 21),
// (13,43): error CS0128: A local variable or function named 'x6' is already defined in this scope
// [Test(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 43),
// (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "6 is int x6 && x6 > 0").WithLocation(13, 11),
// (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(7 is int x7 && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "7 is int x7 && x7 > 0").WithLocation(14, 11),
// (15,11): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 11),
// (16,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_ConstructorInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
X(byte x)
: this(3 is int x3 && x3 > 0)
{}
X(sbyte x)
: this(x4 && 4 is int x4)
{}
X(short x)
: this(51 is int x5 &&
52 is int x5 &&
x5 > 0)
{}
X(ushort x)
: this(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)
{}
X(int x)
: this(7 is int x7 && x7 > 0)
{}
X(uint x)
: this(x7, 2)
{}
void Test73() { Dummy(x7, 3); }
X(params object[] x) {}
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,16): error CS0841: Cannot use local variable 'x4' before it is declared
// : this(x4 && 4 is int x4)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16),
// (18,26): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 26),
// (23,48): error CS0128: A local variable named 'x6' is already defined in this scope
// : this(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(23, 48),
// (30,16): error CS0103: The name 'x7' does not exist in the current context
// : this(x7, 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16),
// (32,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_ConstructorInitializers_02()
{
var source =
@"
public class X : Y
{
public static void Main()
{
}
X(byte x)
: base(3 is int x3 && x3 > 0)
{}
X(sbyte x)
: base(x4 && 4 is int x4)
{}
X(short x)
: base(51 is int x5 &&
52 is int x5 &&
x5 > 0)
{}
X(ushort x)
: base(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)
{}
X(int x)
: base(7 is int x7 && x7 > 0)
{}
X(uint x)
: base(x7, 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
public class Y
{
public Y(params object[] x) {}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,16): error CS0841: Cannot use local variable 'x4' before it is declared
// : base(x4 && 4 is int x4)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16),
// (18,26): error CS0128: A local variable named 'x5' is already defined in this scope
// 52 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 26),
// (23,48): error CS0128: A local variable named 'x6' is already defined in this scope
// : base(6 is int x6 && x6 > 0, 6 is int x6 && x6 > 0)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(23, 48),
// (30,16): error CS0103: The name 'x7' does not exist in the current context
// : base(x7, 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16),
// (32,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0], x5Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_ConstructorInitializers_03()
{
var source =
@"using System;
public class X
{
public static void Main()
{
new D(1);
new D(10);
new D(1.2);
}
}
class D
{
public D(object o) : this(o is int x && x >= 5)
{
Console.WriteLine(x);
}
public D(bool b) { Console.WriteLine(b); }
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (15,27): error CS0165: Use of unassigned local variable 'x'
// Console.WriteLine(x);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(15, 27)
);
}
[Fact]
public void ScopeOfPatternVariables_ConstructorInitializers_04()
{
var source =
@"using System;
public class X
{
public static void Main()
{
new D(1);
new D(10);
new D(1.2);
}
}
class D : C
{
public D(object o) : base(o is int x && x >= 5)
{
Console.WriteLine(x);
}
}
class C
{
public C(bool b) { Console.WriteLine(b); }
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (15,27): error CS0165: Use of unassigned local variable 'x'
// Console.WriteLine(x);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(15, 27)
);
}
[Fact]
public void ScopeOfPatternVariables_ConstructorInitializers_07()
{
var source =
@"
public class X : Y
{
public static void Main()
{
}
X(byte x3)
: base(3 is int x3)
{}
X(sbyte x)
: base(4 is int x4)
{
int x4 = 1;
System.Console.WriteLine(x4);
}
X(ushort x)
: base(51 is int x5)
=> Dummy(52 is int x5, x5);
bool Dummy(params object[] x) {return true;}
}
public class Y
{
public Y(params object[] x) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (9,25): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// : base(3 is int x3)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(9, 25),
// (15,13): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x4 = 1;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 13),
// (21,24): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// => Dummy(52 is int x5, x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl);
VerifyNotAPatternLocal(model, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl[1], x5Ref);
}
[Fact]
public void ScopeOfPatternVariables_SwitchLabelGuard_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test1(int val)
{
switch (val)
{
case 0 when Dummy(true is var x1, x1):
Dummy(x1);
break;
case 1 when Dummy(true is var x1, x1):
Dummy(x1);
break;
case 2 when Dummy(true is var x1, x1):
Dummy(x1);
break;
}
}
void Test2(int val)
{
switch (val)
{
case 0 when Dummy(x2, true is var x2):
Dummy(x2);
break;
}
}
void Test3(int x3, int val)
{
switch (val)
{
case 0 when Dummy(true is var x3, x3):
Dummy(x3);
break;
}
}
void Test4(int val)
{
var x4 = 11;
switch (val)
{
case 0 when Dummy(true is var x4, x4):
Dummy(x4);
break;
case 1 when Dummy(x4): Dummy(x4); break;
}
}
void Test5(int val)
{
switch (val)
{
case 0 when Dummy(true is var x5, x5):
Dummy(x5);
break;
}
var x5 = 11;
Dummy(x5);
}
//void Test6(int val)
//{
// let x6 = 11;
// switch (val)
// {
// case 0 when Dummy(x6):
// Dummy(x6);
// break;
// case 1 when Dummy(true is var x6, x6):
// Dummy(x6);
// break;
// }
//}
//void Test7(int val)
//{
// switch (val)
// {
// case 0 when Dummy(true is var x7, x7):
// Dummy(x7);
// break;
// }
// let x7 = 11;
// Dummy(x7);
//}
void Test8(int val)
{
switch (val)
{
case 0 when Dummy(true is var x8, x8, false is var x8, x8):
Dummy(x8);
break;
}
}
void Test9(int val)
{
switch (val)
{
case 0 when Dummy(x9):
int x9 = 9;
Dummy(x9);
break;
case 2 when Dummy(x9 = 9):
Dummy(x9);
break;
case 1 when Dummy(true is var x9, x9):
Dummy(x9);
break;
}
}
//void Test10(int val)
//{
// switch (val)
// {
// case 1 when Dummy(true is var x10, x10):
// Dummy(x10);
// break;
// case 0 when Dummy(x10):
// let x10 = 10;
// Dummy(x10);
// break;
// case 2 when Dummy(x10 = 10, x10):
// Dummy(x10);
// break;
// }
//}
void Test11(int val)
{
switch (x11 ? val : 0)
{
case 0 when Dummy(x11):
Dummy(x11, 0);
break;
case 1 when Dummy(true is var x11, x11):
Dummy(x11, 1);
break;
}
}
void Test12(int val)
{
switch (x12 ? val : 0)
{
case 0 when Dummy(true is var x12, x12):
Dummy(x12, 0);
break;
case 1 when Dummy(x12):
Dummy(x12, 1);
break;
}
}
void Test13()
{
switch (1 is var x13 ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case 1 when Dummy(true is var x13, x13):
Dummy(x13);
break;
}
}
void Test14(int val)
{
switch (val)
{
case 1 when Dummy(true is var x14, x14):
Dummy(x14);
Dummy(true is var x14, x14);
Dummy(x14);
break;
}
}
void Test15(int val)
{
switch (val)
{
case 0 when Dummy(true is var x15, x15):
case 1 when Dummy(true is var x15, x15):
Dummy(x15);
break;
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (30,31): error CS0841: Cannot use local variable 'x2' before it is declared
// case 0 when Dummy(x2, true is var x2):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(30, 31),
// (40,43): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(true is var x3, x3):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(40, 43),
// (51,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(true is var x4, x4):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(51, 43),
// (62,43): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(true is var x5, x5):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(62, 43),
// (102,64): error CS0128: A local variable named 'x8' is already defined in this scope
// case 0 when Dummy(true is var x8, x8, false is var x8, x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(102, 64),
// (112,31): error CS0841: Cannot use local variable 'x9' before it is declared
// case 0 when Dummy(x9):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(112, 31),
// (119,43): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(true is var x9, x9):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(119, 43),
// (144,17): error CS0103: The name 'x11' does not exist in the current context
// switch (x11 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(144, 17),
// (146,31): error CS0103: The name 'x11' does not exist in the current context
// case 0 when Dummy(x11):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(146, 31),
// (147,23): error CS0103: The name 'x11' does not exist in the current context
// Dummy(x11, 0);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(147, 23),
// (157,17): error CS0103: The name 'x12' does not exist in the current context
// switch (x12 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(157, 17),
// (162,31): error CS0103: The name 'x12' does not exist in the current context
// case 1 when Dummy(x12):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(162, 31),
// (163,23): error CS0103: The name 'x12' does not exist in the current context
// Dummy(x12, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(163, 23),
// (175,43): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(true is var x13, x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(175, 43),
// (185,43): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(true is var x14, x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(185, 43),
// (198,43): error CS0128: A local variable named 'x15' is already defined in this scope
// case 1 when Dummy(true is var x15, x15):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(198, 43),
// (198,48): error CS0165: Use of unassigned local variable 'x15'
// case 1 when Dummy(true is var x15, x15):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(198, 48)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(6, x1Ref.Length);
for (int i = 0; i < x1Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]);
}
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(4, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[0], x4Ref[1]);
VerifyNotAPatternLocal(model, x4Ref[2]);
VerifyNotAPatternLocal(model, x4Ref[3]);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(3, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref[0], x5Ref[1]);
VerifyNotAPatternLocal(model, x5Ref[2]);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(6, x9Ref.Length);
VerifyNotAPatternLocal(model, x9Ref[0]);
VerifyNotAPatternLocal(model, x9Ref[1]);
VerifyNotAPatternLocal(model, x9Ref[2]);
VerifyNotAPatternLocal(model, x9Ref[3]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref[4], x9Ref[5]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(5, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyNotInScope(model, x11Ref[1]);
VerifyNotInScope(model, x11Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref[3], x11Ref[4]);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(5, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref[1], x12Ref[2]);
VerifyNotInScope(model, x12Ref[3]);
VerifyNotInScope(model, x12Ref[4]);
var x13Decl = GetPatternDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(5, x13Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[1], x13Ref[3], x13Ref[4]);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[1], true);
var x15Decl = GetPatternDeclarations(tree, "x15").ToArray();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Decl.Length);
Assert.Equal(3, x15Ref.Length);
for (int i = 0; i < x15Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x15Decl[0], x15Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x15Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_SwitchLabelPattern_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test1(object val)
{
switch (val)
{
case byte x1 when Dummy(x1):
Dummy(x1);
break;
case int x1 when Dummy(x1):
Dummy(x1);
break;
case long x1 when Dummy(x1):
Dummy(x1);
break;
}
}
void Test2(object val)
{
switch (val)
{
case 0 when Dummy(x2):
case int x2:
Dummy(x2);
break;
}
}
void Test3(int x3, object val)
{
switch (val)
{
case int x3 when Dummy(x3):
Dummy(x3);
break;
}
}
void Test4(object val)
{
var x4 = 11;
switch (val)
{
case int x4 when Dummy(x4):
Dummy(x4);
break;
case 1 when Dummy(x4):
Dummy(x4);
break;
}
}
void Test5(object val)
{
switch (val)
{
case int x5 when Dummy(x5):
Dummy(x5);
break;
}
var x5 = 11;
Dummy(x5);
}
//void Test6(object val)
//{
// let x6 = 11;
// switch (val)
// {
// case 0 when Dummy(x6):
// Dummy(x6);
// break;
// case int x6 when Dummy(x6):
// Dummy(x6);
// break;
// }
//}
//void Test7(object val)
//{
// switch (val)
// {
// case int x7 when Dummy(x7):
// Dummy(x7);
// break;
// }
// let x7 = 11;
// Dummy(x7);
//}
void Test8(object val)
{
switch (val)
{
case int x8
when Dummy(x8, false is var x8, x8):
Dummy(x8);
break;
}
}
void Test9(object val)
{
switch (val)
{
case 0 when Dummy(x9):
int x9 = 9;
Dummy(x9);
break;
case 2 when Dummy(x9 = 9):
Dummy(x9);
break;
case int x9 when Dummy(x9):
Dummy(x9);
break;
}
}
//void Test10(object val)
//{
// switch (val)
// {
// case int x10 when Dummy(x10):
// Dummy(x10);
// break;
// case 0 when Dummy(x10):
// let x10 = 10;
// Dummy(x10);
// break;
// case 2 when Dummy(x10 = 10, x10):
// Dummy(x10);
// break;
// }
//}
void Test11(object val)
{
switch (x11 ? val : 0)
{
case 0 when Dummy(x11):
Dummy(x11, 0);
break;
case int x11 when Dummy(x11):
Dummy(x11, 1);
break;
}
}
void Test12(object val)
{
switch (x12 ? val : 0)
{
case int x12 when Dummy(x12):
Dummy(x12, 0);
break;
case 1 when Dummy(x12):
Dummy(x12, 1);
break;
}
}
void Test13()
{
switch (1 is var x13 ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case int x13 when Dummy(x13):
Dummy(x13);
break;
}
}
void Test14(object val)
{
switch (val)
{
case int x14 when Dummy(x14):
Dummy(x14);
Dummy(true is var x14, x14);
Dummy(x14);
break;
}
}
void Test15(object val)
{
switch (val)
{
case int x15 when Dummy(x15):
case long x15 when Dummy(x15):
Dummy(x15);
break;
}
}
void Test16(object val)
{
switch (val)
{
case int x16 when Dummy(x16):
case 1 when Dummy(true is var x16, x16):
Dummy(x16);
break;
}
}
void Test17(object val)
{
switch (val)
{
case 0 when Dummy(true is var x17, x17):
case int x17 when Dummy(x17):
Dummy(x17);
break;
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (30,31): error CS0841: Cannot use local variable 'x2' before it is declared
// case 0 when Dummy(x2):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(30, 31),
// (32,23): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(32, 23),
// (41,22): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x3 when Dummy(x3):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(41, 22),
// (52,22): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x4 when Dummy(x4):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(52, 22),
// (65,22): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x5 when Dummy(x5):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(65, 22),
// (106,49): error CS0128: A local variable named 'x8' is already defined in this scope
// when Dummy(x8, false is var x8, x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(106, 49),
// (116,31): error CS0841: Cannot use local variable 'x9' before it is declared
// case 0 when Dummy(x9):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(116, 31),
// (123,22): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x9 when Dummy(x9):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(123, 22),
// (148,17): error CS0103: The name 'x11' does not exist in the current context
// switch (x11 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(148, 17),
// (150,31): error CS0103: The name 'x11' does not exist in the current context
// case 0 when Dummy(x11):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(150, 31),
// (151,23): error CS0103: The name 'x11' does not exist in the current context
// Dummy(x11, 0);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(151, 23),
// (161,17): error CS0103: The name 'x12' does not exist in the current context
// switch (x12 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(161, 17),
// (166,31): error CS0103: The name 'x12' does not exist in the current context
// case 1 when Dummy(x12):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(166, 31),
// (167,23): error CS0103: The name 'x12' does not exist in the current context
// Dummy(x12, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(167, 23),
// (179,22): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x13 when Dummy(x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(179, 22),
// (189,22): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x14 when Dummy(x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(189, 22),
// (202,23): error CS0128: A local variable named 'x15' is already defined in this scope
// case long x15 when Dummy(x15):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(202, 23),
// (202,38): error CS0165: Use of unassigned local variable 'x15'
// case long x15 when Dummy(x15):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(202, 38),
// (213,43): error CS0128: A local variable named 'x16' is already defined in this scope
// case 1 when Dummy(true is var x16, x16):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x16").WithArguments("x16").WithLocation(213, 43),
// (213,48): error CS0165: Use of unassigned local variable 'x16'
// case 1 when Dummy(true is var x16, x16):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x16").WithArguments("x16").WithLocation(213, 48),
// (224,22): error CS0128: A local variable named 'x17' is already defined in this scope
// case int x17 when Dummy(x17):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x17").WithArguments("x17").WithLocation(224, 22),
// (224,37): error CS0165: Use of unassigned local variable 'x17'
// case int x17 when Dummy(x17):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x17").WithArguments("x17").WithLocation(224, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(6, x1Ref.Length);
for (int i = 0; i < x1Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]);
}
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(4, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[0], x4Ref[1]);
VerifyNotAPatternLocal(model, x4Ref[2]);
VerifyNotAPatternLocal(model, x4Ref[3]);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(3, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref[0], x5Ref[1]);
VerifyNotAPatternLocal(model, x5Ref[2]);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(6, x9Ref.Length);
VerifyNotAPatternLocal(model, x9Ref[0]);
VerifyNotAPatternLocal(model, x9Ref[1]);
VerifyNotAPatternLocal(model, x9Ref[2]);
VerifyNotAPatternLocal(model, x9Ref[3]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref[4], x9Ref[5]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(5, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyNotInScope(model, x11Ref[1]);
VerifyNotInScope(model, x11Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref[3], x11Ref[4]);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(5, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref[1], x12Ref[2]);
VerifyNotInScope(model, x12Ref[3]);
VerifyNotInScope(model, x12Ref[4]);
var x13Decl = GetPatternDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(5, x13Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[1], x13Ref[3], x13Ref[4]);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[1], true);
var x15Decl = GetPatternDeclarations(tree, "x15").ToArray();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Decl.Length);
Assert.Equal(3, x15Ref.Length);
for (int i = 0; i < x15Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x15Decl[0], x15Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x15Decl[1]);
var x16Decl = GetPatternDeclarations(tree, "x16").ToArray();
var x16Ref = GetReferences(tree, "x16").ToArray();
Assert.Equal(2, x16Decl.Length);
Assert.Equal(3, x16Ref.Length);
for (int i = 0; i < x16Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x16Decl[0], x16Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x16Decl[1]);
var x17Decl = GetPatternDeclarations(tree, "x17").ToArray();
var x17Ref = GetReferences(tree, "x17").ToArray();
Assert.Equal(2, x17Decl.Length);
Assert.Equal(3, x17Ref.Length);
for (int i = 0; i < x17Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x17Decl[0], x17Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x17Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Switch_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
switch (1 is var x1 ? x1 : 0)
{
case 0:
Dummy(x1, 0);
break;
}
Dummy(x1, 1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
switch (4 is var x4 ? x4 : 0)
{
case 4:
Dummy(x4);
break;
}
}
void Test5(int x5)
{
switch (5 is var x5 ? x5 : 0)
{
case 5:
Dummy(x5);
break;
}
}
void Test6()
{
switch (x6 + 6 is var x6 ? x6 : 0)
{
case 6:
Dummy(x6);
break;
}
}
void Test7()
{
switch (7 is var x7 ? x7 : 0)
{
case 7:
var x7 = 12;
Dummy(x7);
break;
}
}
void Test9()
{
switch (9 is var x9 ? x9 : 0)
{
case 9:
Dummy(x9, 0);
switch (9 is var x9 ? x9 : 0)
{
case 9:
Dummy(x9, 1);
break;
}
break;
}
}
void Test10()
{
switch (y10 + 10 is var x10 ? x10 : 0)
{
case 0 when y10:
break;
case y10:
var y10 = 12;
Dummy(y10);
break;
}
}
//void Test11()
//{
// switch (y11 + 11 is var x11 ? x11 : 0)
// {
// case 0 when y11 > 0:
// break;
// case y11:
// let y11 = 12;
// Dummy(y11);
// break;
// }
//}
void Test14()
{
switch (Dummy(1 is var x14,
2 is var x14,
x14) ? 1 : 0)
{
case 0:
Dummy(x14);
break;
}
}
void Test15(int val)
{
switch (val)
{
case 0 when y15 > 0:
break;
case y15:
var y15 = 15;
Dummy(y15);
break;
}
}
//void Test16(int val)
//{
// switch (val)
// {
// case 0 when y16 > 0:
// break;
// case y16:
// let y16 = 16;
// Dummy(y16);
// break;
// }
//}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (27,26): error CS0128: A local variable or function named 'x4' is already defined in this scope
// switch (4 is var x4 ? x4 : 0)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(27, 26),
// (37,26): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// switch (5 is var x5 ? x5 : 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(37, 26),
// (47,17): error CS0841: Cannot use local variable 'x6' before it is declared
// switch (x6 + 6 is var x6 ? x6 : 0)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(47, 17),
// (60,21): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(60, 21),
// (71,23): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9, 0);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(71, 23),
// (72,34): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// switch (9 is var x9 ? x9 : 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(72, 34),
// (85,17): error CS0103: The name 'y10' does not exist in the current context
// switch (y10 + 10 is var x10 ? x10 : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 17),
// (87,25): error CS0841: Cannot use local variable 'y10' before it is declared
// case 0 when y10:
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y10").WithArguments("y10").WithLocation(87, 25),
// (89,18): error CS0841: Cannot use local variable 'y10' before it is declared
// case y10:
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y10").WithArguments("y10").WithLocation(89, 18),
// (89,18): error CS0150: A constant value is expected
// case y10:
Diagnostic(ErrorCode.ERR_ConstantExpected, "y10").WithLocation(89, 18),
// (112,28): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(112, 28),
// (125,25): error CS0841: Cannot use local variable 'y15' before it is declared
// case 0 when y15 > 0:
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y15").WithArguments("y15").WithLocation(125, 25),
// (127,18): error CS0841: Cannot use local variable 'y15' before it is declared
// case y15:
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y15").WithArguments("y15").WithLocation(127, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyNotAPatternLocal(model, x4Ref[2]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(3, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(4, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
VerifyNotAPatternLocal(model, y10Ref[2]);
VerifyNotAPatternLocal(model, y10Ref[3]);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
var y15Ref = GetReferences(tree, "y15").ToArray();
Assert.Equal(3, y15Ref.Length);
VerifyNotAPatternLocal(model, y15Ref[0]);
VerifyNotAPatternLocal(model, y15Ref[1]);
VerifyNotAPatternLocal(model, y15Ref[2]);
}
[Fact]
public void ScopeOfPatternVariables_Switch_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
switch (1 is var x1 ? 1 : 0)
{
case 0:
break;
}
Dummy(x1, 1);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (19,15): error CS0103: The name 'x1' does not exist in the current context
// Dummy(x1, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(19, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_Switch_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (SwitchStatementSyntax)SyntaxFactory.ParseStatement(@"
switch (Dummy(11 is var x1, x1)) {}
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_Using_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (Dummy(true is var x1, x1))
{
Dummy(x1);
}
}
void Test2()
{
using (Dummy(true is var x2, x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (Dummy(true is var x4, x4))
Dummy(x4);
}
void Test6()
{
using (Dummy(x6 && true is var x6))
Dummy(x6);
}
void Test7()
{
using (Dummy(true is var x7 && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (Dummy(true is var x8, x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (Dummy(true is var x9, x9))
{
Dummy(x9);
using (Dummy(true is var x9, x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (Dummy(y10 is var x10, x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (Dummy(y11 is var x11, x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (Dummy(y12 is var x12, x12))
var y12 = 12;
}
//void Test13()
//{
// using (Dummy(y13 is var x13, x13))
// let y13 = 12;
//}
void Test14()
{
using (Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,34): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(true is var x4, x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 34),
// (35,22): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && true is var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 22),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(true is var x9, x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 38),
// (68,22): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(y10 is var x10, x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 22),
// (86,22): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(y12 is var x12, x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 22),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,31): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 31)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Using_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d = Dummy(true is var x1, x1))
{
Dummy(x1);
}
}
void Test2()
{
using (var d = Dummy(true is var x2, x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (var d = Dummy(true is var x4, x4))
Dummy(x4);
}
void Test6()
{
using (var d = Dummy(x6 && true is var x6))
Dummy(x6);
}
void Test7()
{
using (var d = Dummy(true is var x7 && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (var d = Dummy(true is var x8, x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (var d = Dummy(true is var x9, x9))
{
Dummy(x9);
using (var e = Dummy(true is var x9, x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (var d = Dummy(y10 is var x10, x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (var d = Dummy(y11 is var x11, x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (var d = Dummy(y12 is var x12, x12))
var y12 = 12;
}
//void Test13()
//{
// using (var d = Dummy(y13 is var x13, x13))
// let y13 = 12;
//}
void Test14()
{
using (var d = Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var d = Dummy(true is var x4, x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 42),
// (35,30): error CS0841: Cannot use local variable 'x6' before it is declared
// using (var d = Dummy(x6 && true is var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var e = Dummy(true is var x9, x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 46),
// (68,30): error CS0103: The name 'y10' does not exist in the current context
// using (var d = Dummy(y10 is var x10, x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 30),
// (86,30): error CS0103: The name 'y12' does not exist in the current context
// using (var d = Dummy(y12 is var x12, x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 30),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,39): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 39)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Using_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d = Dummy(true is var x1, x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d = Dummy(true is var x2, x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (System.IDisposable d = Dummy(true is var x4, x4))
Dummy(x4);
}
void Test6()
{
using (System.IDisposable d = Dummy(x6 && true is var x6))
Dummy(x6);
}
void Test7()
{
using (System.IDisposable d = Dummy(true is var x7 && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (System.IDisposable d = Dummy(true is var x8, x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (System.IDisposable d = Dummy(true is var x9, x9))
{
Dummy(x9);
using (System.IDisposable c = Dummy(true is var x9, x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (System.IDisposable d = Dummy(y10 is var x10, x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (System.IDisposable d = Dummy(y11 is var x11, x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (System.IDisposable d = Dummy(y12 is var x12, x12))
var y12 = 12;
}
//void Test13()
//{
// using (System.IDisposable d = Dummy(y13 is var x13, x13))
// let y13 = 12;
//}
void Test14()
{
using (System.IDisposable d = Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (System.IDisposable d = Dummy(true is var x4, x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57),
// (35,45): error CS0841: Cannot use local variable 'x6' before it is declared
// using (System.IDisposable d = Dummy(x6 && true is var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 45),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (System.IDisposable c = Dummy(true is var x9, x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61),
// (68,45): error CS0103: The name 'y10' does not exist in the current context
// using (System.IDisposable d = Dummy(y10 is var x10, x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 45),
// (86,45): error CS0103: The name 'y12' does not exist in the current context
// using (System.IDisposable d = Dummy(y12 is var x12, x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 45),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,54): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Using_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var x1 = Dummy(true is var x1, x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable x2 = Dummy(true is var x2, x2))
{
Dummy(x2);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (12,43): error CS0128: A local variable named 'x1' is already defined in this scope
// using (var x1 = Dummy(true is var x1, x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 43),
// (12,47): error CS0841: Cannot use local variable 'x1' before it is declared
// using (var x1 = Dummy(true is var x1, x1))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(12, 47),
// (20,58): error CS0128: A local variable named 'x2' is already defined in this scope
// using (System.IDisposable x2 = Dummy(true is var x2, x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 58),
// (20,62): error CS0165: Use of unassigned local variable 'x2'
// using (System.IDisposable x2 = Dummy(true is var x2, x2))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 62)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl);
VerifyNotAPatternLocal(model, x2Ref[0]);
VerifyNotAPatternLocal(model, x2Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_Using_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d = Dummy(true is var x1, x1),
x1 = Dummy(x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d1 = Dummy(true is var x2, x2),
d2 = Dummy(true is var x2, x2))
{
Dummy(x2);
}
}
void Test3()
{
using (System.IDisposable d1 = Dummy(true is var x3, x3),
d2 = Dummy(x3))
{
Dummy(x3);
}
}
void Test4()
{
using (System.IDisposable d1 = Dummy(x4),
d2 = Dummy(true is var x4, x4))
{
Dummy(x4);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,35): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35),
// (22,58): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(true is var x2, x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 58),
// (39,46): error CS0841: Cannot use local variable 'x4' before it is declared
// using (System.IDisposable d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(3, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
}
[Fact]
public void ScopeOfPatternVariables_LocalDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var d = Dummy(true is var x1, x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
var d = Dummy(true is var x4, x4);
}
void Test6()
{
var d = Dummy(x6 && true is var x6);
}
void Test8()
{
var d = Dummy(true is var x8, x8);
System.Console.WriteLine(x8);
}
void Test14()
{
var d = Dummy(1 is var x14,
2 is var x14,
x14);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (19,35): error CS0128: A local variable named 'x4' is already defined in this scope
// var d = Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 35),
// (24,23): error CS0841: Cannot use local variable 'x6' before it is declared
// var d = Dummy(x6 && true is var x6);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23),
// (36,32): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 32)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_LocalDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d = Dummy(true is var x1, x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
object d = Dummy(true is var x4, x4);
}
void Test6()
{
object d = Dummy(x6 && true is var x6);
}
void Test8()
{
object d = Dummy(true is var x8, x8);
System.Console.WriteLine(x8);
}
void Test14()
{
object d = Dummy(1 is var x14,
2 is var x14,
x14);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (19,38): error CS0128: A local variable named 'x4' is already defined in this scope
// object d = Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 38),
// (24,26): error CS0841: Cannot use local variable 'x6' before it is declared
// object d = Dummy(x6 && true is var x6);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 26),
// (36,35): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 35)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_LocalDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var x1 =
Dummy(true is var x1, x1);
Dummy(x1);
}
void Test2()
{
object x2 =
Dummy(true is var x2, x2);
Dummy(x2);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,36): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 36),
// (13,40): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 40),
// (20,39): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(true is var x2, x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 39),
// (20,43): error CS0165: Use of unassigned local variable 'x2'
// Dummy(true is var x2, x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 43)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyNotAPatternLocal(model, x2Ref[0]);
VerifyNotAPatternLocal(model, x2Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl);
}
[Fact]
public void ScopeOfPatternVariables_LocalDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d = Dummy(true is var x1, x1),
x1 = Dummy(x1);
Dummy(x1);
}
void Test2()
{
object d1 = Dummy(true is var x2, x2),
d2 = Dummy(true is var x2, x2);
}
void Test3()
{
object d1 = Dummy(true is var x3, x3),
d2 = Dummy(x3);
}
void Test4()
{
object d1 = Dummy(x4),
d2 = Dummy(true is var x4, x4);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (20,39): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(true is var x2, x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 39),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
}
[Fact]
public void ScopeOfPatternVariables_LocalDeclarationStmt_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
long Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"
var y1 = Dummy(11 is var x1, x1);
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
Assert.Equal("System.Int64 y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_LocalDeclarationStmt_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var d = true is var x1;
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var d = true is var x1;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d = true is var x1;").WithLocation(11, 13),
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
var d = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "d").Single();
Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void ScopeOfPatternVariables_DeconstructionDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var (d, dd) = ((true is var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
var (d, dd) = ((true is var x4), x4);
}
void Test6()
{
var (d, dd) = (x6 && (true is var x6), 1);
}
void Test8()
{
var (d, dd) = ((true is var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
var (d, dd, ddd) = ((1 is var x14),
(2 is var x14),
x14);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,37): error CS0128: A local variable named 'x4' is already defined in this scope
// var (d, dd) = ((true is var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 37),
// (24,24): error CS0841: Cannot use local variable 'x6' before it is declared
// var (d, dd) = (x6 && (true is var x6), 1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 24),
// (36,33): error CS0128: A local variable named 'x14' is already defined in this scope
// (2 is var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x4Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x4").Single();
var x4Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x6Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x6").Single();
var x6Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x6").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x8Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x8").Single();
var x8Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x14Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x14").ToArray();
var x14Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void ScopeOfPatternVariables_DeconstructionDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
(object d, object dd) = ((true is var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
(object d, object dd) = ((true is var x4), x4);
}
void Test6()
{
(object d, object dd) = (x6 && (true is var x6), 1);
}
void Test8()
{
(object d, object dd) = ((true is var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
(object d, object dd, object ddd) = ((1 is var x14),
(2 is var x14),
x14);
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,47): error CS0128: A local variable named 'x4' is already defined in this scope
// (object d, object dd) = ((true is var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 47),
// (24,34): error CS0841: Cannot use local variable 'x6' before it is declared
// (object d, object dd) = (x6 && (true is var x6), 1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 34),
// (36,33): error CS0128: A local variable named 'x14' is already defined in this scope
// (2 is var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x4Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x4").Single();
var x4Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x6Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x6").Single();
var x6Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x6").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x8Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x8").Single();
var x8Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x14Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x14").ToArray();
var x14Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void ScopeOfPatternVariables_DeconstructionDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var (x1, dd) =
((true is var x1), x1);
Dummy(x1);
}
void Test2()
{
(object x2, object dd) =
((true is var x2), x2);
Dummy(x2);
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,37): error CS0128: A local variable named 'x1' is already defined in this scope
// ((true is var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 37),
// (13,42): error CS0841: Cannot use local variable 'x1' before it is declared
// ((true is var x1), x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 42),
// (20,40): error CS0128: A local variable named 'x2' is already defined in this scope
// ((true is var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 40),
// (20,45): error CS0165: Use of unassigned local variable 'x2'
// ((true is var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 45)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
var x2Decl = GetPatternDeclaration(tree, "x2");
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyNotAPatternLocal(model, x2Ref[0]);
VerifyNotAPatternLocal(model, x2Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void ScopeOfPatternVariables_DeconstructionDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
(object d, object x1) = (Dummy((true is var x1), x1),
Dummy(x1));
Dummy(x1);
}
void Test2()
{
(object d1, object d2) = (Dummy((true is var x2), x2),
Dummy((true is var x2), x2));
}
void Test3()
{
(object d1, object d2) = (Dummy((true is var x3), x3),
Dummy(x3));
}
void Test4()
{
(object d1, object d2) = (Dummy(x4),
Dummy((true is var x4), x4));
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,53): error CS0128: A local variable named 'x1' is already defined in this scope
// (object d, object x1) = (Dummy((true is var x1), x1),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 53),
// (12,58): error CS0165: Use of unassigned local variable 'x1'
// (object d, object x1) = (Dummy((true is var x1), x1),
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(12, 58),
// (20,40): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy((true is var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 40),
// (31,41): error CS0841: Cannot use local variable 'x4' before it is declared
// (object d1, object d2) = (Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
VerifyNotAPatternLocal(model, x1Ref[2]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
var x2Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x2").ToArray();
var x2Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x3").Single();
var x3Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x4").Single();
var x4Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void ScopeOfPatternVariables_DeconstructionDeclarationStmt_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@"
var (y1, dd) = ((123 is var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
Assert.Equal("System.Boolean y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void ScopeOfPatternVariables_DeconstructionDeclarationStmt_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var (d, dd) = ((true is var x1), x1);
x1++;
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var d = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(id => id.Identifier.ValueText == "d").Single();
Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_While_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
while (true is var x1 && x1)
{
Dummy(x1);
}
}
void Test2()
{
while (true is var x2 && x2)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
while (true is var x4 && x4)
Dummy(x4);
}
void Test6()
{
while (x6 && true is var x6)
Dummy(x6);
}
void Test7()
{
while (true is var x7 && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
while (true is var x8 && x8)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
while (true is var x9 && x9)
{
Dummy(x9);
while (true is var x9 && x9) // 2
Dummy(x9);
}
}
void Test10()
{
while (y10 is var x10)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// while (y11 is var x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
while (y12 is var x12)
var y12 = 12;
}
//void Test13()
//{
// while (y13 is var x13)
// let y13 = 12;
//}
void Test14()
{
while (Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,28): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 28),
// (35,16): error CS0841: Cannot use local variable 'x6' before it is declared
// while (x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 16),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,32): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 32),
// (68,16): error CS0103: The name 'y10' does not exist in the current context
// while (y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 16),
// (86,16): error CS0103: The name 'y12' does not exist in the current context
// while (y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 16),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,31): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 31)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_While_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
while (true is var x1)
{
}
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (17,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_While_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (WhileStatementSyntax)SyntaxFactory.ParseStatement(@"
while (Dummy(11 is var x1, x1)) ;
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_Do_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
do
{
Dummy(x1);
}
while (true is var x1 && x1);
}
void Test2()
{
do
Dummy(x2);
while (true is var x2 && x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
do
Dummy(x4);
while (true is var x4 && x4);
}
void Test6()
{
do
Dummy(x6);
while (x6 && true is var x6);
}
void Test7()
{
do
{
var x7 = 12;
Dummy(x7);
}
while (true is var x7 && x7);
}
void Test8()
{
do
Dummy(x8);
while (true is var x8 && x8);
System.Console.WriteLine(x8);
}
void Test9()
{
do
{
Dummy(x9);
do
Dummy(x9);
while (true is var x9 && x9); // 2
}
while (true is var x9 && x9);
}
void Test10()
{
do
{
var y10 = 12;
Dummy(y10);
}
while (y10 is var x10);
}
//void Test11()
//{
// do
// {
// let y11 = 12;
// Dummy(y11);
// }
// while (y11 is var x11);
//}
void Test12()
{
do
var y12 = 12;
while (y12 is var x12);
}
//void Test13()
//{
// do
// let y13 = 12;
// while (y13 is var x13);
//}
void Test14()
{
do
{
Dummy(x14);
}
while (Dummy(1 is var x14,
2 is var x14,
x14));
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (97,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(97, 13),
// (14,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(14, 19),
// (22,19): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(22, 19),
// (33,28): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (true is var x4 && x4);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(33, 28),
// (32,19): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy(x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(32, 19),
// (40,16): error CS0841: Cannot use local variable 'x6' before it is declared
// while (x6 && true is var x6);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(40, 16),
// (39,19): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(39, 19),
// (47,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(47, 17),
// (56,19): error CS0841: Cannot use local variable 'x8' before it is declared
// Dummy(x8);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x8").WithArguments("x8").WithLocation(56, 19),
// (59,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(59, 34),
// (66,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(66, 19),
// (69,32): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (true is var x9 && x9); // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(69, 32),
// (68,23): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(68, 23),
// (81,16): error CS0103: The name 'y10' does not exist in the current context
// while (y10 is var x10);
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(81, 16),
// (98,16): error CS0103: The name 'y12' does not exist in the current context
// while (y12 is var x12);
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(98, 16),
// (97,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(97, 17),
// (115,31): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(115, 31),
// (112,19): error CS0841: Cannot use local variable 'x14' before it is declared
// Dummy(x14);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x14").WithArguments("x14").WithLocation(112, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[1]);
VerifyNotAPatternLocal(model, x7Ref[0]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[1], x9Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[0], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[1]);
VerifyNotAPatternLocal(model, y10Ref[0]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Do_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
do
{
}
while (true is var x1);
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (18,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_Do_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (DoStatementSyntax)SyntaxFactory.ParseStatement(@"
do {} while (Dummy(11 is var x1, x1));
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_For_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (
Dummy(true is var x1 && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (
Dummy(true is var x2 && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (
Dummy(true is var x4 && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (
Dummy(x6 && true is var x6)
;;)
Dummy(x6);
}
void Test7()
{
for (
Dummy(true is var x7 && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (
Dummy(true is var x8 && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (
Dummy(true is var x9 && x9)
;;)
{
Dummy(x9);
for (
Dummy(true is var x9 && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (
Dummy(y10 is var x10)
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (
// Dummy(y11 is var x11)
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (
Dummy(y12 is var x12)
;;)
var y12 = 12;
}
//void Test13()
//{
// for (
// Dummy(y13 is var x13)
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (
Dummy(1 is var x14,
2 is var x14,
x14)
;;)
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,32): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 32),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,36): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 36),
// (85,20): error CS0103: The name 'y10' does not exist in the current context
// Dummy(y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 20),
// (107,20): error CS0103: The name 'y12' does not exist in the current context
// Dummy(y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 20),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,29): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_For_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;
Dummy(true is var x1 && x1)
;)
{
Dummy(x1);
}
}
void Test2()
{
for (;
Dummy(true is var x2 && x2)
;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (;
Dummy(true is var x4 && x4)
;)
Dummy(x4);
}
void Test6()
{
for (;
Dummy(x6 && true is var x6)
;)
Dummy(x6);
}
void Test7()
{
for (;
Dummy(true is var x7 && x7)
;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (;
Dummy(true is var x8 && x8)
;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (;
Dummy(true is var x9 && x9)
;)
{
Dummy(x9);
for (;
Dummy(true is var x9 && x9) // 2
;)
Dummy(x9);
}
}
void Test10()
{
for (;
Dummy(y10 is var x10)
;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (;
// Dummy(y11 is var x11)
// ;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (;
Dummy(y12 is var x12)
;)
var y12 = 12;
}
//void Test13()
//{
// for (;
// Dummy(y13 is var x13)
// ;)
// let y13 = 12;
//}
void Test14()
{
for (;
Dummy(1 is var x14,
2 is var x14,
x14)
;)
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,32): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 32),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (76,36): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 36),
// (85,20): error CS0103: The name 'y10' does not exist in the current context
// Dummy(y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 20),
// (107,20): error CS0103: The name 'y12' does not exist in the current context
// Dummy(y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 20),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,29): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_For_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;;
Dummy(true is var x1 && x1)
)
{
Dummy(x1);
}
}
void Test2()
{
for (;;
Dummy(true is var x2 && x2)
)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (;;
Dummy(true is var x4 && x4)
)
Dummy(x4);
}
void Test6()
{
for (;;
Dummy(x6 && true is var x6)
)
Dummy(x6);
}
void Test7()
{
for (;;
Dummy(true is var x7 && x7)
)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (;;
Dummy(true is var x8 && x8)
)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (;;
Dummy(true is var x9 && x9)
)
{
Dummy(x9);
for (;;
Dummy(true is var x9 && x9) // 2
)
Dummy(x9);
}
}
void Test10()
{
for (;;
Dummy(y10 is var x10)
)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (;;
// Dummy(y11 is var x11)
// )
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (;;
Dummy(y12 is var x12)
)
var y12 = 12;
}
//void Test13()
//{
// for (;;
// Dummy(y13 is var x13)
// )
// let y13 = 12;
//}
void Test14()
{
for (;;
Dummy(1 is var x14,
2 is var x14,
x14)
)
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (16,19): error CS0103: The name 'x1' does not exist in the current context
// Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(16, 19),
// (25,19): error CS0103: The name 'x2' does not exist in the current context
// Dummy(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(25, 19),
// (34,32): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 32),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (44,19): error CS0103: The name 'x6' does not exist in the current context
// Dummy(x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(44, 19),
// (63,19): error CS0103: The name 'x8' does not exist in the current context
// Dummy(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(63, 19),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (74,19): error CS0103: The name 'x9' does not exist in the current context
// Dummy(x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(74, 19),
// (78,23): error CS0103: The name 'x9' does not exist in the current context
// Dummy(x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(78, 23),
// (71,14): warning CS0162: Unreachable code detected
// Dummy(true is var x9 && x9)
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(71, 14),
// (85,20): error CS0103: The name 'y10' does not exist in the current context
// Dummy(y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 20),
// (107,20): error CS0103: The name 'y12' does not exist in the current context
// Dummy(y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 20),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,29): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 29),
// (128,19): error CS0103: The name 'x14' does not exist in the current context
// Dummy(x14);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(128, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref[0]);
VerifyNotInScope(model, x2Ref[1]);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1]);
VerifyNotAPatternLocal(model, x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref[0]);
VerifyNotInScope(model, x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0]);
VerifyNotInScope(model, x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0]);
VerifyNotInScope(model, x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2]);
VerifyNotInScope(model, x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref[0]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
VerifyNotInScope(model, x14Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_For_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (var b =
Dummy(true is var x1 && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (var b =
Dummy(true is var x2 && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (var b =
Dummy(true is var x4 && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (var b =
Dummy(x6 && true is var x6)
;;)
Dummy(x6);
}
void Test7()
{
for (var b =
Dummy(true is var x7 && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (var b =
Dummy(true is var x8 && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (var b1 =
Dummy(true is var x9 && x9)
;;)
{
Dummy(x9);
for (var b2 =
Dummy(true is var x9 && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (var b =
Dummy(y10 is var x10)
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (var b =
// Dummy(y11 is var x11)
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (var b =
Dummy(y12 is var x12)
;;)
var y12 = 12;
}
//void Test13()
//{
// for (var b =
// Dummy(y13 is var x13)
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (var b =
Dummy(1 is var x14,
2 is var x14,
x14)
;;)
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,32): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 32),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,36): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 36),
// (85,20): error CS0103: The name 'y10' does not exist in the current context
// Dummy(y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 20),
// (107,20): error CS0103: The name 'y12' does not exist in the current context
// Dummy(y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 20),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,29): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_For_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (bool b =
Dummy(true is var x1 && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (bool b =
Dummy(true is var x2 && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (bool b =
Dummy(true is var x4 && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (bool b =
Dummy(x6 && true is var x6)
;;)
Dummy(x6);
}
void Test7()
{
for (bool b =
Dummy(true is var x7 && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (bool b =
Dummy(true is var x8 && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (bool b1 =
Dummy(true is var x9 && x9)
;;)
{
Dummy(x9);
for (bool b2 =
Dummy(true is var x9 && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (bool b =
Dummy(y10 is var x10)
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (bool b =
// Dummy(y11 is var x11)
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (bool b =
Dummy(y12 is var x12)
;;)
var y12 = 12;
}
//void Test13()
//{
// for (bool b =
// Dummy(y13 is var x13)
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (bool b =
Dummy(1 is var x14,
2 is var x14,
x14)
;;)
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,32): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 32),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,36): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 36),
// (85,20): error CS0103: The name 'y10' does not exist in the current context
// Dummy(y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 20),
// (107,20): error CS0103: The name 'y12' does not exist in the current context
// Dummy(y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 20),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,29): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_For_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (var x1 =
Dummy(true is var x1 && x1)
;;)
{}
}
void Test2()
{
for (var x2 = true;
Dummy(true is var x2 && x2)
;)
{}
}
void Test3()
{
for (var x3 = true;;
Dummy(true is var x3 && x3)
)
{}
}
void Test4()
{
for (bool x4 =
Dummy(true is var x4 && x4)
;;)
{}
}
void Test5()
{
for (bool x5 = true;
Dummy(true is var x5 && x5)
;)
{}
}
void Test6()
{
for (bool x6 = true;;
Dummy(true is var x6 && x6)
)
{}
}
void Test7()
{
for (bool x7 = true, b =
Dummy(true is var x7 && x7)
;;)
{}
}
void Test8()
{
for (bool b1 = Dummy(true is var x8 && x8),
b2 = Dummy(true is var x8 && x8);
Dummy(true is var x8 && x8);
Dummy(true is var x8 && x8))
{}
}
void Test9()
{
for (bool b = x9,
b2 = Dummy(true is var x9 && x9);
Dummy(true is var x9 && x9);
Dummy(true is var x9 && x9))
{}
}
void Test10()
{
for (var b = x10;
Dummy(true is var x10 && x10) &&
Dummy(true is var x10 && x10);
Dummy(true is var x10 && x10))
{}
}
void Test11()
{
for (bool b = x11;
Dummy(true is var x11 && x11) &&
Dummy(true is var x11 && x11);
Dummy(true is var x11 && x11))
{}
}
void Test12()
{
for (Dummy(x12);
Dummy(x12) &&
Dummy(true is var x12 && x12);
Dummy(true is var x12 && x12))
{}
}
void Test13()
{
for (var b = x13;
Dummy(x13);
Dummy(true is var x13 && x13),
Dummy(true is var x13 && x13))
{}
}
void Test14()
{
for (bool b = x14;
Dummy(x14);
Dummy(true is var x14 && x14),
Dummy(true is var x14 && x14))
{}
}
void Test15()
{
for (Dummy(x15);
Dummy(x15);
Dummy(x15),
Dummy(true is var x15 && x15))
{}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,32): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(true is var x1 && x1)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 32),
// (13,38): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(true is var x1 && x1)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 38),
// (21,32): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x2 && x2)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 32),
// (20,18): warning CS0219: The variable 'x2' is assigned but its value is never used
// for (var x2 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(20, 18),
// (29,32): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x3 && x3)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 32),
// (28,18): warning CS0219: The variable 'x3' is assigned but its value is never used
// for (var x3 = true;;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(28, 18),
// (37,32): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(37, 32),
// (37,38): error CS0165: Use of unassigned local variable 'x4'
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(37, 38),
// (45,32): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x5 && x5)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(45, 32),
// (44,19): warning CS0219: The variable 'x5' is assigned but its value is never used
// for (bool x5 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(44, 19),
// (53,32): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x6 && x6)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(53, 32),
// (52,19): warning CS0219: The variable 'x6' is assigned but its value is never used
// for (bool x6 = true;;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(52, 19),
// (61,32): error CS0128: A local variable or function named 'x7' is already defined in this scope
// Dummy(true is var x7 && x7)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(61, 32),
// (69,37): error CS0128: A local variable or function named 'x8' is already defined in this scope
// b2 = Dummy(true is var x8 && x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(69, 37),
// (70,32): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x8 && x8);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(70, 32),
// (71,32): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x8 && x8))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(71, 32),
// (77,23): error CS0841: Cannot use local variable 'x9' before it is declared
// for (bool b = x9,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(77, 23),
// (79,32): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(79, 32),
// (80,32): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(80, 32),
// (86,22): error CS0103: The name 'x10' does not exist in the current context
// for (var b = x10;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x10").WithArguments("x10").WithLocation(86, 22),
// (88,32): error CS0128: A local variable or function named 'x10' is already defined in this scope
// Dummy(true is var x10 && x10);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x10").WithArguments("x10").WithLocation(88, 32),
// (89,32): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x10 && x10))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(89, 32),
// (95,23): error CS0103: The name 'x11' does not exist in the current context
// for (bool b = x11;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(95, 23),
// (97,32): error CS0128: A local variable or function named 'x11' is already defined in this scope
// Dummy(true is var x11 && x11);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x11").WithArguments("x11").WithLocation(97, 32),
// (98,32): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x11 && x11))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(98, 32),
// (104,20): error CS0103: The name 'x12' does not exist in the current context
// for (Dummy(x12);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(104, 20),
// (105,20): error CS0841: Cannot use local variable 'x12' before it is declared
// Dummy(x12) &&
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(105, 20),
// (107,32): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x12 && x12))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(107, 32),
// (113,22): error CS0103: The name 'x13' does not exist in the current context
// for (var b = x13;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(113, 22),
// (114,20): error CS0103: The name 'x13' does not exist in the current context
// Dummy(x13);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(114, 20),
// (116,32): error CS0128: A local variable or function named 'x13' is already defined in this scope
// Dummy(true is var x13 && x13))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x13").WithArguments("x13").WithLocation(116, 32),
// (122,23): error CS0103: The name 'x14' does not exist in the current context
// for (bool b = x14;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(122, 23),
// (123,20): error CS0103: The name 'x14' does not exist in the current context
// Dummy(x14);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(123, 20),
// (125,32): error CS0128: A local variable or function named 'x14' is already defined in this scope
// Dummy(true is var x14 && x14))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(125, 32),
// (131,20): error CS0103: The name 'x15' does not exist in the current context
// for (Dummy(x15);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(131, 20),
// (132,20): error CS0103: The name 'x15' does not exist in the current context
// Dummy(x15);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(132, 20),
// (133,20): error CS0841: Cannot use local variable 'x15' before it is declared
// Dummy(x15),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x15").WithArguments("x15").WithLocation(133, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
VerifyNotAPatternLocal(model, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
VerifyNotAPatternLocal(model, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x7Decl);
VerifyNotAPatternLocal(model, x7Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(4, x8Decl.Length);
Assert.Equal(4, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[0], x8Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[2], x8Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[3], x8Ref[3]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(3, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[2], x9Ref[3]);
var x10Decl = GetPatternDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(3, x10Decl.Length);
Assert.Equal(4, x10Ref.Length);
VerifyNotInScope(model, x10Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl[0], x10Ref[1], x10Ref[2]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x10Decl[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl[2], x10Ref[3]);
var x11Decl = GetPatternDeclarations(tree, "x11").ToArray();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Decl.Length);
Assert.Equal(4, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl[0], x11Ref[1], x11Ref[2]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x11Decl[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl[2], x11Ref[3]);
var x12Decl = GetPatternDeclarations(tree, "x12").ToArray();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Decl.Length);
Assert.Equal(4, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl[0], x12Ref[1], x12Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl[1], x12Ref[3]);
var x13Decl = GetPatternDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(4, x13Ref.Length);
VerifyNotInScope(model, x13Ref[0]);
VerifyNotInScope(model, x13Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[0], x13Ref[2], x13Ref[3]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x13Decl[1]);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyNotInScope(model, x14Ref[0]);
VerifyNotInScope(model, x14Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref[2], x14Ref[3]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetPatternDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(4, x15Ref.Length);
VerifyNotInScope(model, x15Ref[0]);
VerifyNotInScope(model, x15Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x15Decl, x15Ref[2], x15Ref[3]);
}
[Fact]
public void ScopeOfPatternVariables_For_07()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;;
Dummy(x1),
Dummy(true is var x1 && x1))
{}
}
void Test2()
{
for (;;
Dummy(true is var x2 && x2),
Dummy(true is var x2 && x2))
{}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,20): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(x1),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 20),
// (22,32): error CS0128: A local variable or function named 'x2' is already defined in this scope
// Dummy(true is var x2 && x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 32)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Foreach_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Collections.IEnumerable Dummy(params object[] x) {return null;}
void Test1()
{
foreach (var i in Dummy(true is var x1 && x1))
{
Dummy(x1);
}
}
void Test2()
{
foreach (var i in Dummy(true is var x2 && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
foreach (var i in Dummy(true is var x4 && x4))
Dummy(x4);
}
void Test6()
{
foreach (var i in Dummy(x6 && true is var x6))
Dummy(x6);
}
void Test7()
{
foreach (var i in Dummy(true is var x7 && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
foreach (var i in Dummy(true is var x8 && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
foreach (var i1 in Dummy(true is var x9 && x9))
{
Dummy(x9);
foreach (var i2 in Dummy(true is var x9 && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
foreach (var i in Dummy(y10 is var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// foreach (var i in Dummy(y11 is var x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
foreach (var i in Dummy(y12 is var x12))
var y12 = 12;
}
//void Test13()
//{
// foreach (var i in Dummy(y13 is var x13))
// let y13 = 12;
//}
void Test14()
{
foreach (var i in Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
void Test15()
{
foreach (var x15 in
Dummy(1 is var x15, x15))
{
Dummy(x15);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,45): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i in Dummy(true is var x4 && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 45),
// (35,33): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && true is var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 33),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,50): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(true is var x9 && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 50),
// (68,33): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(y10 is var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 33),
// (86,33): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(y12 is var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 33),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,42): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 42),
// (108,22): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(108, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetPatternDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x15Decl, x15Ref[0]);
VerifyNotAPatternLocal(model, x15Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_Lock_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
lock (Dummy(true is var x1 && x1))
{
Dummy(x1);
}
}
void Test2()
{
lock (Dummy(true is var x2 && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
lock (Dummy(true is var x4 && x4))
Dummy(x4);
}
void Test6()
{
lock (Dummy(x6 && true is var x6))
Dummy(x6);
}
void Test7()
{
lock (Dummy(true is var x7 && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
lock (Dummy(true is var x8 && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
lock (Dummy(true is var x9 && x9))
{
Dummy(x9);
lock (Dummy(true is var x9 && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
lock (Dummy(y10 is var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// lock (Dummy(y11 is var x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
lock (Dummy(y12 is var x12))
var y12 = 12;
}
//void Test13()
//{
// lock (Dummy(y13 is var x13))
// let y13 = 12;
//}
void Test14()
{
lock (Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,33): error CS0128: A local variable named 'x4' is already defined in this scope
// lock (Dummy(true is var x4 && x4))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(29, 33),
// (35,21): error CS0841: Cannot use local variable 'x6' before it is declared
// lock (Dummy(x6 && true is var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 21),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (60,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(60, 19),
// (61,37): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// lock (Dummy(true is var x9 && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 37),
// (68,21): error CS0103: The name 'y10' does not exist in the current context
// lock (Dummy(y10 is var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 21),
// (86,21): error CS0103: The name 'y12' does not exist in the current context
// lock (Dummy(y12 is var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 21),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,30): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 30)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyNotAPatternLocal(model, x4Ref[2]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Lock_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
if (true)
lock (Dummy(true is var x1))
{
}
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (17,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_Lock_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LockStatementSyntax)SyntaxFactory.ParseStatement(@"
lock (Dummy(11 is var x1, x1));
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_Fixed_01()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
void Test1()
{
fixed (int* p = Dummy(true is var x1 && x1))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p = Dummy(true is var x2 && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
fixed (int* p = Dummy(true is var x4 && x4))
Dummy(x4);
}
void Test6()
{
fixed (int* p = Dummy(x6 && true is var x6))
Dummy(x6);
}
void Test7()
{
fixed (int* p = Dummy(true is var x7 && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
fixed (int* p = Dummy(true is var x8 && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
fixed (int* p1 = Dummy(true is var x9 && x9))
{
Dummy(x9);
fixed (int* p2 = Dummy(true is var x9 && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
fixed (int* p = Dummy(y10 is var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// fixed (int* p = Dummy(y11 is var x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
fixed (int* p = Dummy(y12 is var x12))
var y12 = 12;
}
//void Test13()
//{
// fixed (int* p = Dummy(y13 is var x13))
// let y13 = 12;
//}
void Test14()
{
fixed (int* p = Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p = Dummy(true is var x4 && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 43),
// (35,31): error CS0841: Cannot use local variable 'x6' before it is declared
// fixed (int* p = Dummy(x6 && true is var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,48): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p2 = Dummy(true is var x9 && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 48),
// (68,31): error CS0103: The name 'y10' does not exist in the current context
// fixed (int* p = Dummy(y10 is var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 31),
// (86,31): error CS0103: The name 'y12' does not exist in the current context
// fixed (int* p = Dummy(y12 is var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 31),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,40): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Fixed_02()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
int[] Dummy(int* x) {return null;}
void Test1()
{
fixed (int* x1 =
Dummy(true is var x1 && x1))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p = Dummy(true is var x2 && x2),
x2 = Dummy())
{
Dummy(x2);
}
}
void Test3()
{
fixed (int* x3 = Dummy(),
p = Dummy(true is var x3 && x3))
{
Dummy(x3);
}
}
void Test4()
{
fixed (int* p1 = Dummy(true is var x4 && x4),
p2 = Dummy(true is var x4 && x4))
{
Dummy(x4);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
// (14,44): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(true is var x1 && x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 44),
// (14,50): error CS0165: Use of unassigned local variable 'x1'
// Dummy(true is var x1 && x1))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 50),
// (23,21): error CS0128: A local variable named 'x2' is already defined in this scope
// x2 = Dummy())
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21),
// (32,43): error CS0128: A local variable named 'x3' is already defined in this scope
// p = Dummy(true is var x3 && x3))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 43),
// (41,44): error CS0128: A local variable named 'x4' is already defined in this scope
// p2 = Dummy(true is var x4 && x4))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x3Decl);
VerifyNotAPatternLocal(model, x3Ref[0]);
VerifyNotAPatternLocal(model, x3Ref[1]);
var x4Decl = GetPatternDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Decl.Length);
Assert.Equal(3, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl[0], x4Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl[1]);
}
[Fact]
public void ScopeOfPatternVariables_Yield_01()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null;}
IEnumerable Test1()
{
yield return Dummy(true is var x1, x1);
{
yield return Dummy(true is var x1, x1);
}
yield return Dummy(true is var x1, x1);
}
IEnumerable Test2()
{
yield return Dummy(x2, true is var x2);
}
IEnumerable Test3(int x3)
{
yield return Dummy(true is var x3, x3);
}
IEnumerable Test4()
{
var x4 = 11;
Dummy(x4);
yield return Dummy(true is var x4, x4);
}
IEnumerable Test5()
{
yield return Dummy(true is var x5, x5);
var x5 = 11;
Dummy(x5);
}
//IEnumerable Test6()
//{
// let x6 = 11;
// Dummy(x6);
// yield return Dummy(true is var x6, x6);
//}
//IEnumerable Test7()
//{
// yield return Dummy(true is var x7, x7);
// let x7 = 11;
// Dummy(x7);
//}
IEnumerable Test8()
{
yield return Dummy(true is var x8, x8, false is var x8, x8);
}
IEnumerable Test9(bool y9)
{
if (y9)
yield return Dummy(true is var x9, x9);
}
IEnumerable Test11()
{
Dummy(x11);
yield return Dummy(true is var x11, x11);
}
IEnumerable Test12()
{
yield return Dummy(true is var x12, x12);
Dummy(x12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (16,44): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// yield return Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(16, 44),
// (18,40): error CS0128: A local variable or function named 'x1' is already defined in this scope
// yield return Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(18, 40),
// (23,28): error CS0841: Cannot use local variable 'x2' before it is declared
// yield return Dummy(x2, true is var x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(23, 28),
// (28,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// yield return Dummy(true is var x3, x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(28, 40),
// (35,40): error CS0128: A local variable or function named 'x4' is already defined in this scope
// yield return Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(35, 40),
// (41,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(41, 13),
// (41,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(41, 13),
// (61,61): error CS0128: A local variable or function named 'x8' is already defined in this scope
// yield return Dummy(true is var x8, x8, false is var x8, x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(61, 61),
// (72,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(72, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref);
}
[Fact]
public void ScopeOfPatternVariables_Yield_02()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null;}
IEnumerable Test1()
{
if (true)
yield return Dummy(true is var x1);
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (17,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_Yield_03()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null;}
IEnumerable Test1()
{
SpeculateHere();
yield 0;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (YieldStatementSyntax)SyntaxFactory.ParseStatement(@"
yield return (Dummy(11 is var x1, x1));
");
bool success = model.TryGetSpeculativeSemanticModel(
GetReferences(tree, "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_Catch_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
try {}
catch when (true is var x1 && x1)
{
Dummy(x1);
}
}
void Test4()
{
var x4 = 11;
Dummy(x4);
try {}
catch when (true is var x4 && x4)
{
Dummy(x4);
}
}
void Test6()
{
try {}
catch when (x6 && true is var x6)
{
Dummy(x6);
}
}
void Test7()
{
try {}
catch when (true is var x7 && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
try {}
catch when (true is var x8 && x8)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
}
void Test9()
{
try {}
catch when (true is var x9 && x9)
{
Dummy(x9);
try {}
catch when (true is var x9 && x9) // 2
{
Dummy(x9);
}
}
}
void Test10()
{
try {}
catch when (y10 is var x10)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// try {}
// catch when (y11 is var x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test14()
{
try {}
catch when (Dummy(1 is var x14,
2 is var x14,
x14))
{
Dummy(x14);
}
}
void Test15()
{
try {}
catch (System.Exception x15)
when (Dummy(1 is var x15, x15))
{
Dummy(x15);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (25,33): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 33),
// (34,21): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21),
// (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17),
// (58,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34),
// (68,37): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 37),
// (78,21): error CS0103: The name 'y10' does not exist in the current context
// catch when (y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 21),
// (99,36): error CS0128: A local variable named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 36),
// (110,36): error CS0128: A local variable named 'x15' is already defined in this scope
// when (Dummy(1 is var x15, x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 36)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetPatternDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x15Decl);
VerifyNotAPatternLocal(model, x15Ref[0]);
VerifyNotAPatternLocal(model, x15Ref[1]);
}
[Fact]
public void ScopeOfPatternVariables_LabeledStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
a: Dummy(true is var x1, x1);
{
b: Dummy(true is var x1, x1);
}
c: Dummy(true is var x1, x1);
}
void Test2()
{
Dummy(x2, true is var x2);
}
void Test3(int x3)
{
a: Dummy(true is var x3, x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
a: Dummy(true is var x4, x4);
}
void Test5()
{
a: Dummy(true is var x5, x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
//a: Dummy(true is var x6, x6);
//}
//void Test7()
//{
//a: Dummy(true is var x7, x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
a: Dummy(true is var x8, x8, false is var x8, x8);
}
void Test9(bool y9)
{
if (y9)
a: Dummy(true is var x9, x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
a: Dummy(true is var x10, x10);
};
}
void Test11()
{
Dummy(x11);
a: Dummy(true is var x11, x11);
}
void Test12()
{
a: Dummy(true is var x12, x12);
Dummy(x12);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// b: Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 31),
// (16,27): error CS0128: A local variable or function named 'x1' is already defined in this scope
// c: Dummy(true is var x1, x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 27),
// (12,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x1, x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(12, 1),
// (14,1): warning CS0164: This label has not been referenced
// b: Dummy(true is var x1, x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(14, 1),
// (16,1): warning CS0164: This label has not been referenced
// c: Dummy(true is var x1, x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(16, 1),
// (21,15): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2, true is var x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15),
// (26,27): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// a: Dummy(true is var x3, x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 27),
// (26,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x3, x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(26, 1),
// (33,27): error CS0128: A local variable or function named 'x4' is already defined in this scope
// a: Dummy(true is var x4, x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 27),
// (33,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x4, x4);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(33, 1),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (38,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x5, x5);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(38, 1),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,48): error CS0128: A local variable or function named 'x8' is already defined in this scope
// a: Dummy(true is var x8, x8, false is var x8, x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 48),
// (59,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x8, x8, false is var x8, x8);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(59, 1),
// (65,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(true is var x9, x9);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(true is var x9, x9);").WithLocation(65, 1),
// (65,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x9, x9);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(65, 1),
// (73,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(true is var x10, x10);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(true is var x10, x10);").WithLocation(73, 1),
// (73,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x10, x10);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(73, 1),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (80,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x11, x11);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(80, 1),
// (85,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x12, x12);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(85, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x2").Single();
var x2Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x3").Single();
var x3Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x4").Single();
var x4Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x5").Single();
var x5Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x8Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x8").ToArray();
var x8Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x9").Single();
var x9Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x9").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref);
var x10Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x10").Single();
var x10Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x10").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var x11Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x11").Single();
var x11Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref);
var x12Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x12").Single();
var x12Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref);
}
[Fact]
public void ScopeOfPatternVariables_LabeledStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
if (true)
a: Dummy(true is var x1);
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (13,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(true is var x1);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(true is var x1);").WithLocation(13, 1),
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9),
// (13,1): warning CS0164: This label has not been referenced
// a: Dummy(true is var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void ScopeOfPatternVariables_LabeledStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LabeledStatementSyntax)SyntaxFactory.ParseStatement(@"
a: b: c:Dummy(11 is var x1, x1);
");
bool success = model.TryGetSpeculativeSemanticModel(
tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "SpeculateHere").Single().SpanStart,
statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").Single();
var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
public static int Data = 2;
void Test1(int val)
{
switch (val)
{
case 0 when Dummy(Dummy(Data is var x1), x1):
Dummy(x1);
break;
case 1 when Dummy(Dummy(Data is var x1), x1):
Dummy(x1);
break;
case 2 when Dummy(Dummy(Data is var x1), x1):
Dummy(x1);
break;
}
}
void Test2(int val)
{
switch (val)
{
case 0 when Dummy(x2, Dummy(Data is var x2)):
Dummy(x2);
break;
}
}
void Test3(int x3, int val)
{
switch (val)
{
case 0 when Dummy(Dummy(Data is var x3), x3):
Dummy(x3);
break;
}
}
void Test4(int val)
{
var x4 = 11;
switch (val)
{
case 0 when Dummy(Dummy(Data is var x4), x4):
Dummy(x4);
break;
case 1 when Dummy(x4): Dummy(x4); break;
}
}
void Test5(int val)
{
switch (val)
{
case 0 when Dummy(Dummy(Data is var x5), x5):
Dummy(x5);
break;
}
var x5 = 11;
Dummy(x5);
}
//void Test6(int val)
//{
// let x6 = 11;
// switch (val)
// {
// case 0 when Dummy(x6):
// Dummy(x6);
// break;
// case 1 when Dummy(Dummy(Data is var x6), x6):
// Dummy(x6);
// break;
// }
//}
//void Test7(int val)
//{
// switch (val)
// {
// case 0 when Dummy(Dummy(Data is var x7), x7):
// Dummy(x7);
// break;
// }
// let x7 = 11;
// Dummy(x7);
//}
void Test8(int val)
{
switch (val)
{
case 0 when Dummy(Dummy(Data is var x8), x8, Dummy(Data is var x8), x8):
Dummy(x8);
break;
}
}
void Test9(int val)
{
switch (val)
{
case 0 when Dummy(x9):
int x9 = 9;
Dummy(x9);
break;
case 2 when Dummy(x9 = 9):
Dummy(x9);
break;
case 1 when Dummy(Dummy(Data is var x9), x9):
Dummy(x9);
break;
}
}
//void Test10(int val)
//{
// switch (val)
// {
// case 1 when Dummy(Dummy(Data is var x10), x10):
// Dummy(x10);
// break;
// case 0 when Dummy(x10):
// let x10 = 10;
// Dummy(x10);
// break;
// case 2 when Dummy(x10 = 10, x10):
// Dummy(x10);
// break;
// }
//}
void Test11(int val)
{
switch (x11 ? val : 0)
{
case 0 when Dummy(x11):
Dummy(x11, 0);
break;
case 1 when Dummy(Dummy(Data is var x11), x11):
Dummy(x11, 1);
break;
}
}
void Test12(int val)
{
switch (x12 ? val : 0)
{
case 0 when Dummy(Dummy(Data is var x12), x12):
Dummy(x12, 0);
break;
case 1 when Dummy(x12):
Dummy(x12, 1);
break;
}
}
void Test13()
{
switch (Dummy(1, Data is var x13) ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case 1 when Dummy(Dummy(Data is var x13), x13):
Dummy(x13);
break;
}
}
void Test14(int val)
{
switch (val)
{
case 1 when Dummy(Dummy(Data is var x14), x14):
Dummy(x14);
Dummy(Dummy(Data is var x14), x14);
Dummy(x14);
break;
}
}
void Test15(int val)
{
switch (val)
{
case 0 when Dummy(Dummy(Data is var x15), x15):
case 1 when Dummy(Dummy(Data is var x15), x15):
Dummy(x15);
break;
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (32,31): error CS0841: Cannot use local variable 'x2' before it is declared
// case 0 when Dummy(x2, Dummy(Data is var x2)):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(32, 31),
// (42,49): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(Dummy(Data is var x3), x3):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(42, 49),
// (53,49): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(Dummy(Data is var x4), x4):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(53, 49),
// (64,49): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(Dummy(Data is var x5), x5):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(64, 49),
// (104,76): error CS0128: A local variable named 'x8' is already defined in this scope
// case 0 when Dummy(Dummy(Data is var x8), x8, Dummy(Data is var x8), x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(104, 76),
// (114,31): error CS0841: Cannot use local variable 'x9' before it is declared
// case 0 when Dummy(x9):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(114, 31),
// (121,49): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(Dummy(Data is var x9), x9):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(121, 49),
// (146,17): error CS0103: The name 'x11' does not exist in the current context
// switch (x11 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(146, 17),
// (148,31): error CS0103: The name 'x11' does not exist in the current context
// case 0 when Dummy(x11):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(148, 31),
// (149,23): error CS0103: The name 'x11' does not exist in the current context
// Dummy(x11, 0);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(149, 23),
// (159,17): error CS0103: The name 'x12' does not exist in the current context
// switch (x12 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(159, 17),
// (164,31): error CS0103: The name 'x12' does not exist in the current context
// case 1 when Dummy(x12):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(164, 31),
// (165,23): error CS0103: The name 'x12' does not exist in the current context
// Dummy(x12, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(165, 23),
// (177,49): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(Dummy(Data is var x13), x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(177, 49),
// (187,49): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(Dummy(Data is var x14), x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(187, 49),
// (200,49): error CS0128: A local variable named 'x15' is already defined in this scope
// case 1 when Dummy(Dummy(Data is var x15), x15):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(200, 49),
// (200,55): error CS0165: Use of unassigned local variable 'x15'
// case 1 when Dummy(Dummy(Data is var x15), x15):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(200, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(6, x1Ref.Length);
for (int i = 0; i < x1Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]);
}
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(4, x4Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x4Decl, x4Ref[0], x4Ref[1]);
VerifyNotAPatternLocal(model, x4Ref[2]);
VerifyNotAPatternLocal(model, x4Ref[3]);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(3, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref[0], x5Ref[1]);
VerifyNotAPatternLocal(model, x5Ref[2]);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(6, x9Ref.Length);
VerifyNotAPatternLocal(model, x9Ref[0]);
VerifyNotAPatternLocal(model, x9Ref[1]);
VerifyNotAPatternLocal(model, x9Ref[2]);
VerifyNotAPatternLocal(model, x9Ref[3]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref[4], x9Ref[5]);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(5, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyNotInScope(model, x11Ref[1]);
VerifyNotInScope(model, x11Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref[3], x11Ref[4]);
var x12Decl = GetPatternDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(5, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForDeclarationOrVarSimplePattern(model, x12Decl, x12Ref[1], x12Ref[2]);
VerifyNotInScope(model, x12Ref[3]);
VerifyNotInScope(model, x12Ref[4]);
var x13Decl = GetPatternDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(5, x13Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x13Decl[1], x13Ref[3], x13Ref[4]);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarSimplePattern(model, x14Decl[1], true);
var x15Decl = GetPatternDeclarations(tree, "x15").ToArray();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Decl.Length);
Assert.Equal(3, x15Ref.Length);
for (int i = 0; i < x15Ref.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x15Decl[0], x15Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x15Decl[1]);
}
[Fact]
public void Scope_SwitchLabelGuard_02()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
Dummy(x1 is var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool Dummy(params object[] trash)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_03()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
while (Dummy(x1 is var y1) && Print(y1)) break;
break;
}
}
static bool Print(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_04()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
do
val = 0;
while (Dummy(x1 is var y1) && Print(y1));
break;
}
}
static bool Print(int x)
{
System.Console.WriteLine(x);
return false;
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_05()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
lock ((object)Dummy(x1 is var y1)) {}
System.Console.WriteLine(y1);
break;
}
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_06()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
if (Dummy(x1 is var y1)) {}
System.Console.WriteLine(y1);
break;
}
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_07()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
switch (Dummy(x1 is var y1))
{
default: break;
}
System.Console.WriteLine(y1);
break;
}
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_08()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
foreach (var x in Test(1)) {}
}
static System.Collections.IEnumerable Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
yield return Dummy(x1 is var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_09()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
var z1 = x1 > 0 & Dummy(x1 is var y1);
System.Console.WriteLine(y1);
System.Console.WriteLine(z1);
break;
}
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
True").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(yRef).Type.ToTestDisplayString());
var zRef = GetReferences(tree, "z1").Single();
Assert.Equal("System.Boolean", compilation.GetSemanticModel(tree).GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_10()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
var z1 = Dummy(123, x1 is var y1);
System.Console.WriteLine(y1);
System.Console.WriteLine(z1);
break;
}
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
True").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var xRef = GetReferences(tree, "x1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef).Type.ToTestDisplayString());
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(yRef).Type.ToTestDisplayString());
var zRef = GetReferences(tree, "z1").Single();
Assert.Equal("System.Boolean", compilation.GetSemanticModel(tree).GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_11()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
System.Console.WriteLine(Test(1));
}
static bool Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
return Dummy(123, x1 is var y1) && Dummy(y1);
System.Console.WriteLine(y1);
break;
}
return false;
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "True").VerifyDiagnostics(
// (17,17): warning CS0162: Unreachable code detected
// System.Console.WriteLine(y1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(17, 17));
var tree = compilation.SyntaxTrees.Single();
var xRef = GetReferences(tree, "x1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef).Type.ToTestDisplayString());
var yRefs = GetReferences(tree, "y1");
Assert.Equal(2, yRefs.Count());
foreach (var yRef in yRefs)
{
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(yRef).Type.ToTestDisplayString());
}
}
[Fact]
public void Scope_SwitchLabelGuard_12()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
Test(1);
}
static bool Test(int val)
{
try
{
switch (val)
{
case 1 when Data is var x1:
throw Dummy(123, x1 is var y1);
System.Console.WriteLine(y1);
break;
}
}
catch { }
return false;
}
static System.Exception Dummy(params object[] data)
{
foreach(var obj in data)
{
System.Console.WriteLine(obj);
}
return new System.Exception();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123
True").VerifyDiagnostics(
// (19,21): warning CS0162: Unreachable code detected
// System.Console.WriteLine(y1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(19, 21));
var tree = compilation.SyntaxTrees.Single();
var xRef = GetReferences(tree, "x1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef).Type.ToTestDisplayString());
var yRef = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_SwitchLabelGuard_13()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
System.Console.WriteLine(Test(1));
}
static bool Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
var (z0, z1) = (x1, Dummy(x1, x1 is var y1));
System.Console.WriteLine(y1);
System.Console.WriteLine(z0);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
return false;
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(
source: source,
options: TestOptions.DebugExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
2
1
False").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var y1Ref = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(y1Ref).Type.ToTestDisplayString());
var z0Ref = GetReferences(tree, "z0").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(z0Ref).Type.ToTestDisplayString());
var z1Ref = GetReferences(tree, "z1").Single();
Assert.Equal("System.Boolean", compilation.GetSemanticModel(tree).GetTypeInfo(z1Ref).Type.ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_SwitchLabelGuard_14()
{
var source =
@"
public class X
{
public static int Data = 2;
public static void Main()
{
System.Console.WriteLine(Test(1));
}
static bool Test(int val)
{
switch (val)
{
case 1 when Dummy(123, Data is var x1):
var (z0, (z1, z2)) = (x1, (Data, Dummy(x1, x1 is var y1)));
System.Console.WriteLine(y1);
System.Console.WriteLine(z0);
System.Console.WriteLine(z1);
System.Console.WriteLine(z2);
break;
}
return false;
}
static bool Dummy(params object[] data)
{
return true;
}
}
";
var compilation = CreateCompilation(
source: source,
options: TestOptions.DebugExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
2
2
True
False").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var y1Ref = GetReferences(tree, "y1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(y1Ref).Type.ToTestDisplayString());
var z0Ref = GetReferences(tree, "z0").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(z0Ref).Type.ToTestDisplayString());
var z1Ref = GetReferences(tree, "z1").Single();
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(z1Ref).Type.ToTestDisplayString());
var z2Ref = GetReferences(tree, "z2").Single();
Assert.Equal("System.Boolean", compilation.GetSemanticModel(tree).GetTypeInfo(z2Ref).Type.ToTestDisplayString());
}
[Fact]
public void Scope_DeclaratorArguments_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
int d,e(Dummy(true is var x1, x1));
}
void Test4()
{
var x4 = 11;
Dummy(x4);
int d,e(Dummy(true is var x4, x4));
}
void Test6()
{
int d,e(Dummy(x6 && true is var x6));
}
void Test8()
{
int d,e(Dummy(true is var x8, x8));
System.Console.WriteLine(x8);
}
void Test14()
{
int d,e(Dummy(1 is var x14,
2 is var x14,
x14));
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (19,35): error CS0128: A local variable or function named 'x4' is already defined in this scope
// int d,e(Dummy(true is var x4, x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 35),
// (24,23): error CS0841: Cannot use local variable 'x6' before it is declared
// int d,e(Dummy(x6 && true is var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23),
// (30,34): error CS0165: Use of unassigned local variable 'x8'
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(30, 34),
// (36,32): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 32)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x6Decl, x6Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x8Decl, x8Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var d, x1(
Dummy(true is var x1, x1));
Dummy(x1);
}
void Test2()
{
object d, x2(
Dummy(true is var x2, x2));
Dummy(x2);
}
void Test3()
{
object x3, d(
Dummy(true is var x3, x3));
Dummy(x3);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (12,13): error CS0818: Implicitly-typed variables must be initialized
// var d, x1(
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(12, 13),
// (13,36): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(true is var x1, x1));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 36),
// (20,39): error CS0128: A local variable or function named 'x2' is already defined in this scope
// Dummy(true is var x2, x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 39),
// (21,15): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 15),
// (27,39): error CS0128: A local variable or function named 'x3' is already defined in this scope
// Dummy(true is var x3, x3));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(27, 39),
// (28,15): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(28, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyNotAPatternLocal(model, x2Ref[0]);
VerifyNotAPatternLocal(model, x2Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyNotAPatternLocal(model, x3Ref[0]);
VerifyNotAPatternLocal(model, x3Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x3Decl);
}
[Fact]
public void Scope_DeclaratorArguments_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d,e(Dummy(true is var x1, x1)],
x1( Dummy(x1));
Dummy(x1);
}
void Test2()
{
object d1,e(Dummy(true is var x2, x2)],
d2(Dummy(true is var x2, x2));
}
void Test3()
{
object d1,e(Dummy(true is var x3, x3)],
d2(Dummy(x3));
}
void Test4()
{
object d1,e(Dummy(x4)],
d2(Dummy(true is var x4, x4));
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,16): error CS0128: A local variable or function named 'x1' is already defined in this scope
// x1( Dummy(x1));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (14,15): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 15),
// (20,39): error CS0128: A local variable or function named 'x2' is already defined in this scope
// d2(Dummy(true is var x2, x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 39),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1,e(Dummy(x4)],
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d,e(Dummy(true is var x1, x1)],
x1 = Dummy(x1);
Dummy(x1);
}
void Test2()
{
object d1,e(Dummy(true is var x2, x2)],
d2 = Dummy(true is var x2, x2);
}
void Test3()
{
object d1,e(Dummy(true is var x3, x3)],
d2 = Dummy(x3);
}
void Test4()
{
object d1 = Dummy(x4),
d2 (Dummy(true is var x4, x4));
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,16): error CS0128: A local variable or function named 'x1' is already defined in this scope
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (13,27): error CS0165: Use of unassigned local variable 'x1'
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 27),
// (20,39): error CS0128: A local variable or function named 'x2' is already defined in this scope
// d2 = Dummy(true is var x2, x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 39),
// (20,43): error CS0165: Use of unassigned local variable 'x2'
// d2 = Dummy(true is var x2, x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 43),
// (26,27): error CS0165: Use of unassigned local variable 'x3'
// d2 = Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(26, 27),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl[0]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
long Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"
var y, y1(Dummy(3 is var x1, x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
var y1 = model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single();
Assert.Equal("var y1", y1.ToTestDisplayString());
Assert.True(((ILocalSymbol)y1).Type.IsErrorType());
}
[Fact]
public void Scope_DeclaratorArguments_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var d,e(string.Empty is var x1 && x1 != null);
x1++;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var d,e(string.Empty is var x1 && x1 != null);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d,e(string.Empty is var x1 && x1 != null);").WithLocation(11, 13),
// (11,17): error CS0818: Implicitly-typed variables must be initialized
// var d,e(string.Empty is var x1 && x1 != null);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(11, 17),
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var e = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "e").Single();
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(e);
Assert.Equal("var e", symbol.ToTestDisplayString());
Assert.True(symbol.Type.IsErrorType());
}
[Fact]
[WorkItem(13460, "https://github.com/dotnet/roslyn/issues/13460")]
public void Scope_DeclaratorArguments_07()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when 123 is var x1:
var z, z1(x1, out var u1, x1 > 0 & x1 is var y1];
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetPatternDeclarations(tree, "y1").Single();
AssertContainedInDeclaratorArguments(y1Decl);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.True(model.GetTypeInfo(zRef).Type.IsErrorType());
}
[Fact]
[WorkItem(13459, "https://github.com/dotnet/roslyn/issues/13459")]
public void Scope_DeclaratorArguments_08()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (bool a, b(
Dummy(true is var x1 && x1)
);;)
{
Dummy(x1);
}
}
void Test2()
{
for (bool a, b(
Dummy(true is var x2 && x2)
);;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (bool a, b(
Dummy(true is var x4 && x4)
);;)
Dummy(x4);
}
void Test6()
{
for (bool a, b(
Dummy(x6 && true is var x6)
);;)
Dummy(x6);
}
void Test7()
{
for (bool a, b(
Dummy(true is var x7 && x7)
);;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (bool a, b(
Dummy(true is var x8 && x8)
);;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (bool a1, b1(
Dummy(true is var x9 && x9)
);;)
{
Dummy(x9);
for (bool a2, b2(
Dummy(true is var x9 && x9) // 2
);;)
Dummy(x9);
}
}
void Test10()
{
for (bool a, b(
Dummy(y10 is var x10)
);;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (bool a, b(
// Dummy(y11 is var x11)
// );;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (bool a, b(
Dummy(y12 is var x12)
);;)
var y12 = 12;
}
//void Test13()
//{
// for (bool a, b(
// Dummy(y13 is var x13)
// );;)
// let y13 = 12;
//}
void Test14()
{
for (bool a, b(
Dummy(1 is var x14,
2 is var x14,
x14)
);;)
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,32): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 32),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && true is var x6)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,36): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 36),
// (85,20): error CS0103: The name 'y10' does not exist in the current context
// Dummy(y10 is var x10)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 20),
// (107,20): error CS0103: The name 'y12' does not exist in the current context
// Dummy(y12 is var x12)
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 20),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,29): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_09()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test4()
{
for (bool d, x4(
Dummy(true is var x4 && x4)
);;)
{}
}
void Test7()
{
for (bool x7 = true, b(
Dummy(true is var x7 && x7)
);;)
{}
}
void Test8()
{
for (bool d,b1(Dummy(true is var x8 && x8)],
b2(Dummy(true is var x8 && x8));
Dummy(true is var x8 && x8);
Dummy(true is var x8 && x8))
{}
}
void Test9()
{
for (bool b = x9,
b2(Dummy(true is var x9 && x9));
Dummy(true is var x9 && x9);
Dummy(true is var x9 && x9))
{}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,32): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(true is var x4 && x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 32),
// (21,32): error CS0128: A local variable or function named 'x7' is already defined in this scope
// Dummy(true is var x7 && x7)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(21, 32),
// (20,19): warning CS0219: The variable 'x7' is assigned but its value is never used
// for (bool x7 = true, b(
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x7").WithArguments("x7").WithLocation(20, 19),
// (29,37): error CS0128: A local variable or function named 'x8' is already defined in this scope
// b2(Dummy(true is var x8 && x8));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(29, 37),
// (30,32): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x8 && x8);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(30, 32),
// (31,32): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x8 && x8))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(31, 32),
// (37,23): error CS0841: Cannot use local variable 'x9' before it is declared
// for (bool b = x9,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(37, 23),
// (39,32): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(39, 32),
// (40,32): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(true is var x9 && x9))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(40, 32)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
VerifyNotAPatternLocal(model, x4Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x7Decl);
VerifyNotAPatternLocal(model, x7Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(4, x8Decl.Length);
Assert.Equal(4, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl[0]);
AssertContainedInDeclaratorArguments(x8Decl[1]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x8Decl[0], x8Ref[0], x8Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x8Decl[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[2], x8Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl[3], x8Ref[3]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(3, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl[0]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[1], x9Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl[2], x9Ref[3]);
}
[Fact]
public void Scope_DeclaratorArguments_10()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d,e(Dummy(true is var x1, x1)))
{
Dummy(x1);
}
}
void Test2()
{
using (var d,e(Dummy(true is var x2, x2)))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (var d,e(Dummy(true is var x4, x4)))
Dummy(x4);
}
void Test6()
{
using (var d,e(Dummy(x6 && true is var x6)))
Dummy(x6);
}
void Test7()
{
using (var d,e(Dummy(true is var x7 && x7)))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (var d,e(Dummy(true is var x8, x8)))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (var d,a(Dummy(true is var x9, x9)))
{
Dummy(x9);
using (var e,b(Dummy(true is var x9, x9))) // 2
Dummy(x9);
}
}
void Test10()
{
using (var d,e(Dummy(y10 is var x10, x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (var d,e(Dummy(y11 is var x11, x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (var d,e(Dummy(y12 is var x12, x12)))
var y12 = 12;
}
//void Test13()
//{
// using (var d,e(Dummy(y13 is var x13, x13)))
// let y13 = 12;
//}
void Test14()
{
using (var d,e(Dummy(1 is var x14,
2 is var x14,
x14)))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var d,e(Dummy(true is var x4, x4)))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 42),
// (35,30): error CS0841: Cannot use local variable 'x6' before it is declared
// using (var d,e(Dummy(x6 && true is var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var e,b(Dummy(true is var x9, x9))) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 46),
// (68,30): error CS0103: The name 'y10' does not exist in the current context
// using (var d,e(Dummy(y10 is var x10, x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 30),
// (86,30): error CS0103: The name 'y12' does not exist in the current context
// using (var d,e(Dummy(y12 is var x12, x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 30),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,39): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 39)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
AssertContainedInDeclaratorArguments(x10Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_11()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d,x1(Dummy(true is var x1, x1)))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d,x2(Dummy(true is var x2, x2)))
{
Dummy(x2);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (12,43): error CS0128: A local variable or function named 'x1' is already defined in this scope
// using (var d,x1(Dummy(true is var x1, x1)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 43),
// (20,58): error CS0128: A local variable or function named 'x2' is already defined in this scope
// using (System.IDisposable d,x2(Dummy(true is var x2, x2)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 58)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
AssertContainedInDeclaratorArguments(x2Decl);
Assert.Equal(2, x2Ref.Length);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl);
VerifyNotAPatternLocal(model, x2Ref[0]);
VerifyNotAPatternLocal(model, x2Ref[1]);
}
[Fact]
public void Scope_DeclaratorArguments_12()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d,e(Dummy(true is var x1, x1)],
x1 = Dummy(x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d1,e(Dummy(true is var x2, x2)],
d2(Dummy(true is var x2, x2)))
{
Dummy(x2);
}
}
void Test3()
{
using (System.IDisposable d1,e(Dummy(true is var x3, x3)],
d2 = Dummy(x3))
{
Dummy(x3);
}
}
void Test4()
{
using (System.IDisposable d1 = Dummy(x4),
d2(Dummy(true is var x4, x4)))
{
Dummy(x4);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,35): error CS0128: A local variable or function named 'x1' is already defined in this scope
// x1 = Dummy(x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35),
// (22,58): error CS0128: A local variable or function named 'x2' is already defined in this scope
// d2(Dummy(true is var x2, x2)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 58),
// (39,46): error CS0841: Cannot use local variable 'x4' before it is declared
// using (System.IDisposable d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(3, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_13()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
void Test1()
{
fixed (int* p,e(Dummy(true is var x1 && x1)))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p,e(Dummy(true is var x2 && x2)))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
fixed (int* p,e(Dummy(true is var x4 && x4)))
Dummy(x4);
}
void Test6()
{
fixed (int* p,e(Dummy(x6 && true is var x6)))
Dummy(x6);
}
void Test7()
{
fixed (int* p,e(Dummy(true is var x7 && x7)))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
fixed (int* p,e(Dummy(true is var x8 && x8)))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
fixed (int* p1,a(Dummy(true is var x9 && x9)))
{
Dummy(x9);
fixed (int* p2,b(Dummy(true is var x9 && x9))) // 2
Dummy(x9);
}
}
void Test10()
{
fixed (int* p,e(Dummy(y10 is var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// fixed (int* p,e(Dummy(y11 is var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
fixed (int* p,e(Dummy(y12 is var x12)))
var y12 = 12;
}
//void Test13()
//{
// fixed (int* p,e(Dummy(y13 is var x13)))
// let y13 = 12;
//}
void Test14()
{
fixed (int* p,e(Dummy(1 is var x14,
2 is var x14,
x14)))
{
Dummy(x14);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p,e(Dummy(true is var x4 && x4)))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 43),
// (35,31): error CS0841: Cannot use local variable 'x6' before it is declared
// fixed (int* p,e(Dummy(x6 && true is var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,48): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p2,b(Dummy(true is var x9 && x9))) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 48),
// (68,31): error CS0103: The name 'y10' does not exist in the current context
// fixed (int* p,e(Dummy(y10 is var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 31),
// (86,31): error CS0103: The name 'y12' does not exist in the current context
// fixed (int* p,e(Dummy(y12 is var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 31),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,40): error CS0128: A local variable or function named 'x14' is already defined in this scope
// 2 is var x14,
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetPatternDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAPatternLocal(model, x7Ref[1]);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetPatternDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAPatternLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetPatternDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_14()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
int[] Dummy(int* x) {return null;}
void Test1()
{
fixed (int* d,x1(
Dummy(true is var x1 && x1)))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* d,p(Dummy(true is var x2 && x2)],
x2 = Dummy())
{
Dummy(x2);
}
}
void Test3()
{
fixed (int* x3 = Dummy(),
p(Dummy(true is var x3 && x3)))
{
Dummy(x3);
}
}
void Test4()
{
fixed (int* d,p1(Dummy(true is var x4 && x4)],
p2(Dummy(true is var x4 && x4)))
{
Dummy(x4);
}
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (14,44): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(true is var x1 && x1)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 44),
// (23,21): error CS0128: A local variable or function named 'x2' is already defined in this scope
// x2 = Dummy())
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21),
// (32,43): error CS0128: A local variable or function named 'x3' is already defined in this scope
// p(Dummy(true is var x3 && x3)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 43),
// (41,44): error CS0128: A local variable or function named 'x4' is already defined in this scope
// p2(Dummy(true is var x4 && x4)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl);
VerifyNotAPatternLocal(model, x1Ref[0]);
VerifyNotAPatternLocal(model, x1Ref[1]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x3Decl);
VerifyNotAPatternLocal(model, x3Ref[0]);
VerifyNotAPatternLocal(model, x3Ref[1]);
var x4Decl = GetPatternDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Decl.Length);
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForDeclarationOrVarSimplePatternWithoutDataFlow(model, x4Decl[0], x4Ref);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_15()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 [3 is var x3 && x3 > 0];
bool Test4 [x4 && 4 is var x4];
bool Test5 [51 is var x5 &&
52 is var x5 &&
x5 > 0];
bool Test61 [6 is var x6 && x6 > 0], Test62 [6 is var x6 && x6 > 0];
bool Test71 [7 is var x7 && x7 > 0];
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.WRN_UnreferencedField
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_16()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed
bool Test3 [3 is var x3 && x3 > 0];
fixed
bool Test4 [x4 && 4 is var x4];
fixed
bool Test5 [51 is var x5 &&
52 is var x5 &&
x5 > 0];
fixed
bool Test61 [6 is var x6 && x6 > 0], Test62 [6 is var x6 && x6 > 0];
fixed
bool Test71 [7 is var x7 && x7 > 0];
fixed
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.WRN_UnreferencedField,
(int)ErrorCode.ERR_NoImplicitConv
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (10,18): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 [x4 && 4 is var x4];
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18),
// (13,28): error CS0128: A local variable or function named 'x5' is already defined in this scope
// 52 is var x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 28),
// (20,25): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 [Dummy(x7, 2)];
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 25),
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_17()
{
var source =
@"
public class X
{
public static void Main()
{
}
const
bool Test3 [3 is var x3 && x3 > 0];
const
bool Test4 [x4 && 4 is var x4];
const
bool Test5 [51 is var x5 &&
52 is var x5 &&
x5 > 0];
const
bool Test61 [6 is var x6 && x6 > 0], Test62 [6 is var x6 && x6 > 0];
const
bool Test71 [7 is var x7 && x7 > 0];
const
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_18()
{
var source =
@"
public class X
{
public static void Main()
{
}
event
bool Test3 [3 is var x3 && x3 > 0];
event
bool Test4 [x4 && 4 is var x4];
event
bool Test5 [51 is var x5 &&
52 is var x5 &&
x5 > 0];
event
bool Test61 [6 is var x6 && x6 > 0], Test62 [6 is var x6 && x6 > 0];
event
bool Test71 [7 is var x7 && x7 > 0];
event
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.ERR_EventNotDelegate,
(int)ErrorCode.WRN_UnreferencedEvent
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetPatternDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_19()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed bool d[2], Test3 (string.Empty is var x3);
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (8,28): error CS1003: Syntax error, '[' expected
// fixed bool d[2], Test3 (string.Empty is var x3);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(8, 28),
// (8,51): error CS1003: Syntax error, ']' expected
// fixed bool d[2], Test3 (string.Empty is var x3);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(8, 51),
// (8,29): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed bool d[2], Test3 (string.Empty is var x3);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty is var x3").WithArguments("bool", "int").WithLocation(8, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl);
}
[Fact]
public void Scope_DeclaratorArguments_20()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed bool Test3[string.Empty is var x3];
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,22): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed bool Test3[string.Empty is var x3];
Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty is var x3").WithArguments("bool", "int").WithLocation(8, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl);
}
[Fact]
public void DeclarationInsideNameof()
{
string source = @"
class Program
{
static void Main(int i)
{
string s = nameof(M(i is var x1, x1)).ToString();
string s1 = x1;
}
static void M(bool b, int i) {}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,27): error CS8081: Expression does not have a name.
// string s = nameof(M(i is var x1, x1)).ToString();
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(i is var x1, x1)").WithLocation(6, 27),
// (7,21): error CS0029: Cannot implicitly convert type 'int' to 'string'
// string s1 = x1;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("int", "string").WithLocation(7, 21),
// (7,21): error CS0165: Use of unassigned local variable 'x1'
// string s1 = x1;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 21)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designation = GetPatternDeclarations(tree).Single();
var refs = GetReferences(tree, "x1").ToArray();
VerifyModelForDeclarationOrVarSimplePattern(model, designation, refs);
var x1 = (ILocalSymbol)model.GetDeclaredSymbol(designation);
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
}
[Fact]
public void ScopeOfPatternVariables_ArrayDeclarationInvalidDimensions()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
int[true is var x1, x1] _1;
{
int[true is var x1, x1] _2;
}
int[true is var x1, x1] _3;
}
void Test2()
{
int[x2, true is var x2] _4;
}
void Test3(int x3)
{
int[true is var x3, x3] _5;
}
void Test4()
{
var x4 = 11;
int[x4] _6;
int[true is var x4, x4] _7;
}
void Test5()
{
int[true is var x5, x5] _8;
var x5 = 11;
int[x5] _9;
}
void Test6()
{
int[true is var x6, x6, false is var x6, x6] _10;
}
void Test7(bool y7)
{
if (y7)
int[true is var x7, x7] _11;
}
System.Action Test8(bool y8)
{
return () =>
{
if (y8)
int[true is var x8, x8] _12;
};
}
void Test9()
{
int[x9] _13;
int[true is var x9, x9] _13;
}
void Test10()
{
int[true is var x10, x10] _14;
int[x10] _15;
}
void Test11()
{
int[true is var x11, x11] x11;
int[x11] _16;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
int[] exclude = new int[] { (int)ErrorCode.ERR_NoImplicitConv, (int)ErrorCode.WRN_UnreferencedVar };
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (10,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x1, x1] _1;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x1, x1]").WithLocation(10, 12),
// (12,16): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x1, x1] _2;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x1, x1]").WithLocation(12, 16),
// (12,29): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int[true is var x1, x1] _2;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(12, 29),
// (14,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x1, x1] _3;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x1, x1]").WithLocation(14, 12),
// (14,25): error CS0128: A local variable or function named 'x1' is already defined in this scope
// int[true is var x1, x1] _3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 25),
// (19,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[x2, true is var x2] _4;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[x2, true is var x2]").WithLocation(19, 12),
// (19,13): error CS0841: Cannot use local variable 'x2' before it is declared
// int[x2, true is var x2] _4;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(19, 13),
// (24,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x3, x3] _5;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x3, x3]").WithLocation(24, 12),
// (24,25): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int[true is var x3, x3] _5;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(24, 25),
// (29,13): warning CS0219: The variable 'x4' is assigned but its value is never used
// var x4 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x4").WithArguments("x4").WithLocation(29, 13),
// (30,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[x4] _6;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[x4]").WithLocation(30, 12),
// (31,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x4, x4] _7;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x4, x4]").WithLocation(31, 12),
// (31,25): error CS0128: A local variable or function named 'x4' is already defined in this scope
// int[true is var x4, x4] _7;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(31, 25),
// (36,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x5, x5] _8;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x5, x5]").WithLocation(36, 12),
// (37,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(37, 13),
// (37,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(37, 13),
// (38,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[x5] _9;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[x5]").WithLocation(38, 12),
// (43,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x6, x6, false is var x6, x6] _10;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x6, x6, false is var x6, x6]").WithLocation(43, 12),
// (43,46): error CS0128: A local variable or function named 'x6' is already defined in this scope
// int[true is var x6, x6, false is var x6, x6] _10;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(43, 46),
// (49,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// int[true is var x7, x7] _11;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "int[true is var x7, x7] _11;").WithLocation(49, 13),
// (49,16): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x7, x7] _11;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x7, x7]").WithLocation(49, 16),
// (57,25): error CS1023: Embedded statement cannot be a declaration or labeled statement
// int[true is var x8, x8] _12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "int[true is var x8, x8] _12;").WithLocation(57, 25),
// (57,28): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x8, x8] _12;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x8, x8]").WithLocation(57, 28),
// (63,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[x9] _13;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[x9]").WithLocation(63, 12),
// (63,13): error CS0841: Cannot use local variable 'x9' before it is declared
// int[x9] _13;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(63, 13),
// (64,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x9, x9] _13;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x9, x9]").WithLocation(64, 12),
// (64,33): error CS0128: A local variable or function named '_13' is already defined in this scope
// int[true is var x9, x9] _13;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "_13").WithArguments("_13").WithLocation(64, 33),
// (69,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x10, x10] _14;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x10, x10]").WithLocation(69, 12),
// (70,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[x10] _15;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[x10]").WithLocation(70, 12),
// (75,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[true is var x11, x11] x11;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[true is var x11, x11]").WithLocation(75, 12),
// (75,35): error CS0128: A local variable or function named 'x11' is already defined in this scope
// int[true is var x11, x11] x11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x11").WithArguments("x11").WithLocation(75, 35),
// (76,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[x11] _16;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[x11]").WithLocation(76, 12)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetPatternDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetPatternDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref);
var x3Decl = GetPatternDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl, x3Ref);
var x4Decl = GetPatternDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAPatternLocal(model, x4Ref[0]);
VerifyNotAPatternLocal(model, x4Ref[1]);
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x4Decl);
var x5Decl = GetPatternDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x5Decl, x5Ref);
var x6Decl = GetPatternDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
for (int i = 0; i < x6Decl.Length; i++)
{
VerifyModelForDeclarationOrVarSimplePattern(model, x6Decl[0], x6Ref[i]);
}
VerifyModelForDeclarationOrVarPatternDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetPatternDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x7Decl, x7Ref);
var x8Decl = GetPatternDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").Single();
VerifyModelForDeclarationOrVarSimplePattern(model, x8Decl, x8Ref);
var x9Decl = GetPatternDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x9Decl, x9Ref);
var x10Decl = GetPatternDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x10Decl, x10Ref);
var x11Decl = GetPatternDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
var x11Decl2 = GetVariableDeclarations(tree, "x11").Single();
Assert.Equal(2, x11Ref.Length);
VerifyModelForDeclarationOrVarSimplePattern(model, x11Decl, x11Ref[0], x11Ref[1]);
VerifyModelForDuplicateVariableDeclarationInSameScope(model, x11Decl2);
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Analyzers/Core/Analyzers/RemoveRedundantEquality/AbstractRemoveRedundantEqualityDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.RemoveRedundantEquality
{
internal abstract class AbstractRemoveRedundantEqualityDiagnosticAnalyzer
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
private readonly ISyntaxFacts _syntaxFacts;
protected AbstractRemoveRedundantEqualityDiagnosticAnalyzer(ISyntaxFacts syntaxFacts)
: base(IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId,
EnforceOnBuildValues.RemoveRedundantEquality,
option: null,
new LocalizableResourceString(nameof(AnalyzersResources.Remove_redundant_equality), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
_syntaxFacts = syntaxFacts;
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterOperationAction(AnalyzeBinaryOperator, OperationKind.BinaryOperator);
private void AnalyzeBinaryOperator(OperationAnalysisContext context)
{
var operation = (IBinaryOperation)context.Operation;
if (operation.OperatorMethod is not null)
{
// We shouldn't report diagnostic on overloaded operator as the behavior can change.
return;
}
if (operation.OperatorKind is not (BinaryOperatorKind.Equals or BinaryOperatorKind.NotEquals))
{
return;
}
if (!_syntaxFacts.IsBinaryExpression(operation.Syntax))
{
return;
}
var rightOperand = operation.RightOperand;
var leftOperand = operation.LeftOperand;
if (rightOperand.Type is null || leftOperand.Type is null)
{
return;
}
if (rightOperand.Type.SpecialType != SpecialType.System_Boolean ||
leftOperand.Type.SpecialType != SpecialType.System_Boolean)
{
return;
}
var isOperatorEquals = operation.OperatorKind == BinaryOperatorKind.Equals;
_syntaxFacts.GetPartsOfBinaryExpression(operation.Syntax, out _, out var operatorToken, out _);
var properties = ImmutableDictionary.CreateBuilder<string, string?>();
if (TryGetLiteralValue(rightOperand) == isOperatorEquals)
{
properties.Add(RedundantEqualityConstants.RedundantSide, RedundantEqualityConstants.Right);
}
else if (TryGetLiteralValue(leftOperand) == isOperatorEquals)
{
properties.Add(RedundantEqualityConstants.RedundantSide, RedundantEqualityConstants.Left);
}
if (properties.Count == 1)
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor,
operatorToken.GetLocation(),
additionalLocations: new[] { operation.Syntax.GetLocation() },
properties: properties.ToImmutable()));
}
return;
static bool? TryGetLiteralValue(IOperation operand)
{
// Make sure we only simplify literals to avoid changing
// something like the following example:
// const bool Activated = true; ... if (state == Activated)
if (operand.ConstantValue.HasValue && operand.Kind == OperationKind.Literal &&
operand.ConstantValue.Value is bool constValue)
{
return constValue;
}
return null;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.RemoveRedundantEquality
{
internal abstract class AbstractRemoveRedundantEqualityDiagnosticAnalyzer
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
private readonly ISyntaxFacts _syntaxFacts;
protected AbstractRemoveRedundantEqualityDiagnosticAnalyzer(ISyntaxFacts syntaxFacts)
: base(IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId,
EnforceOnBuildValues.RemoveRedundantEquality,
option: null,
new LocalizableResourceString(nameof(AnalyzersResources.Remove_redundant_equality), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
_syntaxFacts = syntaxFacts;
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterOperationAction(AnalyzeBinaryOperator, OperationKind.BinaryOperator);
private void AnalyzeBinaryOperator(OperationAnalysisContext context)
{
var operation = (IBinaryOperation)context.Operation;
if (operation.OperatorMethod is not null)
{
// We shouldn't report diagnostic on overloaded operator as the behavior can change.
return;
}
if (operation.OperatorKind is not (BinaryOperatorKind.Equals or BinaryOperatorKind.NotEquals))
{
return;
}
if (!_syntaxFacts.IsBinaryExpression(operation.Syntax))
{
return;
}
var rightOperand = operation.RightOperand;
var leftOperand = operation.LeftOperand;
if (rightOperand.Type is null || leftOperand.Type is null)
{
return;
}
if (rightOperand.Type.SpecialType != SpecialType.System_Boolean ||
leftOperand.Type.SpecialType != SpecialType.System_Boolean)
{
return;
}
var isOperatorEquals = operation.OperatorKind == BinaryOperatorKind.Equals;
_syntaxFacts.GetPartsOfBinaryExpression(operation.Syntax, out _, out var operatorToken, out _);
var properties = ImmutableDictionary.CreateBuilder<string, string?>();
if (TryGetLiteralValue(rightOperand) == isOperatorEquals)
{
properties.Add(RedundantEqualityConstants.RedundantSide, RedundantEqualityConstants.Right);
}
else if (TryGetLiteralValue(leftOperand) == isOperatorEquals)
{
properties.Add(RedundantEqualityConstants.RedundantSide, RedundantEqualityConstants.Left);
}
if (properties.Count == 1)
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor,
operatorToken.GetLocation(),
additionalLocations: new[] { operation.Syntax.GetLocation() },
properties: properties.ToImmutable()));
}
return;
static bool? TryGetLiteralValue(IOperation operand)
{
// Make sure we only simplify literals to avoid changing
// something like the following example:
// const bool Activated = true; ... if (state == Activated)
if (operand.ConstantValue.HasValue && operand.Kind == OperationKind.Literal &&
operand.ConstantValue.Value is bool constValue)
{
return constValue;
}
return null;
}
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/VisualStudio/Core/Impl/Options/Style/NamingPreferences/NamingStyles/NamingStyleViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences
{
internal class NamingStyleViewModel : AbstractNotifyPropertyChanged, INamingStylesInfoDialogViewModel
{
private readonly MutableNamingStyle _style;
private readonly INotificationService _notificationService;
public NamingStyleViewModel(MutableNamingStyle style, bool canBeDeleted, INotificationService notificationService)
{
_notificationService = notificationService;
_style = style;
ID = style.ID;
RequiredPrefix = style.Prefix;
RequiredSuffix = style.Suffix;
WordSeparator = style.WordSeparator;
ItemName = style.Name;
CanBeDeleted = canBeDeleted;
CapitalizationSchemes = new List<CapitalizationDisplay>
{
new CapitalizationDisplay(Capitalization.PascalCase, ServicesVSResources.Pascal_Case_Name),
new CapitalizationDisplay(Capitalization.CamelCase, ServicesVSResources.camel_Case_Name),
new CapitalizationDisplay(Capitalization.FirstUpper, ServicesVSResources.First_word_upper),
new CapitalizationDisplay(Capitalization.AllUpper, ServicesVSResources.ALL_UPPER),
new CapitalizationDisplay(Capitalization.AllLower, ServicesVSResources.all_lower)
};
CapitalizationSchemeIndex = CapitalizationSchemes.IndexOf(CapitalizationSchemes.Single(s => s.Capitalization == style.CapitalizationScheme));
}
public IList<CapitalizationDisplay> CapitalizationSchemes { get; set; }
private int _capitalizationSchemeIndex;
public int CapitalizationSchemeIndex
{
get
{
return _capitalizationSchemeIndex;
}
set
{
_style.CapitalizationScheme = CapitalizationSchemes[value].Capitalization;
if (SetProperty(ref _capitalizationSchemeIndex, value))
{
NotifyPropertyChanged(nameof(CurrentConfiguration));
}
}
}
public Guid ID { get; }
private string _itemName;
public string ItemName
{
get { return _itemName; }
set { SetProperty(ref _itemName, value); }
}
public string CurrentConfiguration
{
get
{
return _style.NamingStyle.CreateName(ImmutableArray.Create(ServicesVSResources.example, ServicesVSResources.identifier));
}
set
{
}
}
private string _requiredPrefix;
public string RequiredPrefix
{
get
{
return _requiredPrefix;
}
set
{
_style.Prefix = value;
if (SetProperty(ref _requiredPrefix, value))
{
NotifyPropertyChanged(nameof(CurrentConfiguration));
}
}
}
private string _requiredSuffix;
public string RequiredSuffix
{
get
{
return _requiredSuffix;
}
set
{
_style.Suffix = value;
if (SetProperty(ref _requiredSuffix, value))
{
NotifyPropertyChanged(nameof(CurrentConfiguration));
}
}
}
private string _wordSeparator;
public string WordSeparator
{
get
{
return _wordSeparator;
}
set
{
_style.WordSeparator = value;
if (SetProperty(ref _wordSeparator, value))
{
NotifyPropertyChanged(nameof(CurrentConfiguration));
}
}
}
public bool CanBeDeleted { get; set; }
internal bool TrySubmit()
{
if (string.IsNullOrWhiteSpace(ItemName))
{
_notificationService.SendNotification(ServicesVSResources.Enter_a_title_for_this_Naming_Style);
return false;
}
return true;
}
internal MutableNamingStyle GetNamingStyle()
{
_style.Name = ItemName;
return _style;
}
// For screen readers
public override string ToString() => ItemName;
public class CapitalizationDisplay
{
public Capitalization Capitalization { get; set; }
public string Name { get; set; }
public CapitalizationDisplay(Capitalization capitalization, string name)
{
Capitalization = capitalization;
Name = name;
}
// For screen readers
public override string ToString()
=> Name;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences
{
internal class NamingStyleViewModel : AbstractNotifyPropertyChanged, INamingStylesInfoDialogViewModel
{
private readonly MutableNamingStyle _style;
private readonly INotificationService _notificationService;
public NamingStyleViewModel(MutableNamingStyle style, bool canBeDeleted, INotificationService notificationService)
{
_notificationService = notificationService;
_style = style;
ID = style.ID;
RequiredPrefix = style.Prefix;
RequiredSuffix = style.Suffix;
WordSeparator = style.WordSeparator;
ItemName = style.Name;
CanBeDeleted = canBeDeleted;
CapitalizationSchemes = new List<CapitalizationDisplay>
{
new CapitalizationDisplay(Capitalization.PascalCase, ServicesVSResources.Pascal_Case_Name),
new CapitalizationDisplay(Capitalization.CamelCase, ServicesVSResources.camel_Case_Name),
new CapitalizationDisplay(Capitalization.FirstUpper, ServicesVSResources.First_word_upper),
new CapitalizationDisplay(Capitalization.AllUpper, ServicesVSResources.ALL_UPPER),
new CapitalizationDisplay(Capitalization.AllLower, ServicesVSResources.all_lower)
};
CapitalizationSchemeIndex = CapitalizationSchemes.IndexOf(CapitalizationSchemes.Single(s => s.Capitalization == style.CapitalizationScheme));
}
public IList<CapitalizationDisplay> CapitalizationSchemes { get; set; }
private int _capitalizationSchemeIndex;
public int CapitalizationSchemeIndex
{
get
{
return _capitalizationSchemeIndex;
}
set
{
_style.CapitalizationScheme = CapitalizationSchemes[value].Capitalization;
if (SetProperty(ref _capitalizationSchemeIndex, value))
{
NotifyPropertyChanged(nameof(CurrentConfiguration));
}
}
}
public Guid ID { get; }
private string _itemName;
public string ItemName
{
get { return _itemName; }
set { SetProperty(ref _itemName, value); }
}
public string CurrentConfiguration
{
get
{
return _style.NamingStyle.CreateName(ImmutableArray.Create(ServicesVSResources.example, ServicesVSResources.identifier));
}
set
{
}
}
private string _requiredPrefix;
public string RequiredPrefix
{
get
{
return _requiredPrefix;
}
set
{
_style.Prefix = value;
if (SetProperty(ref _requiredPrefix, value))
{
NotifyPropertyChanged(nameof(CurrentConfiguration));
}
}
}
private string _requiredSuffix;
public string RequiredSuffix
{
get
{
return _requiredSuffix;
}
set
{
_style.Suffix = value;
if (SetProperty(ref _requiredSuffix, value))
{
NotifyPropertyChanged(nameof(CurrentConfiguration));
}
}
}
private string _wordSeparator;
public string WordSeparator
{
get
{
return _wordSeparator;
}
set
{
_style.WordSeparator = value;
if (SetProperty(ref _wordSeparator, value))
{
NotifyPropertyChanged(nameof(CurrentConfiguration));
}
}
}
public bool CanBeDeleted { get; set; }
internal bool TrySubmit()
{
if (string.IsNullOrWhiteSpace(ItemName))
{
_notificationService.SendNotification(ServicesVSResources.Enter_a_title_for_this_Naming_Style);
return false;
}
return true;
}
internal MutableNamingStyle GetNamingStyle()
{
_style.Name = ItemName;
return _style;
}
// For screen readers
public override string ToString() => ItemName;
public class CapitalizationDisplay
{
public Capitalization Capitalization { get; set; }
public string Name { get; set; }
public CapitalizationDisplay(Capitalization capitalization, string name)
{
Capitalization = capitalization;
Name = name;
}
// For screen readers
public override string ToString()
=> Name;
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenNullable.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.PooledObjects
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports System.Collections.Immutable
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenNullable
Inherits BasicTestBase
<Fact(), WorkItem(544947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544947")>
Public Sub LiftedIntrinsicNegationLocal()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As New Integer?(1)
Dim y = -x
Console.Write("y1={0} ", y)
x = Nothing
y = -x
Console.Write("y2={0} ", y)
y = -New Long?()
Console.Write("y3={0} ", y)
End Sub
End Module
</file>
</compilation>, expectedOutput:="y1=-1 y2= y3=").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 127 (0x7f)
.maxstack 2
.locals init (Integer? V_0, //x
Integer? V_1) //y
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Integer?.get_HasValue() As Boolean"
IL_000f: brtrue.s IL_0014
IL_0011: ldloc.0
IL_0012: br.s IL_0022
IL_0014: ldc.i4.0
IL_0015: ldloca.s V_0
IL_0017: call "Function Integer?.GetValueOrDefault() As Integer"
IL_001c: sub.ovf
IL_001d: newobj "Sub Integer?..ctor(Integer)"
IL_0022: stloc.1
IL_0023: ldstr "y1={0} "
IL_0028: ldloc.1
IL_0029: box "Integer?"
IL_002e: call "Sub System.Console.Write(String, Object)"
IL_0033: ldloca.s V_0
IL_0035: initobj "Integer?"
IL_003b: ldloca.s V_0
IL_003d: call "Function Integer?.get_HasValue() As Boolean"
IL_0042: brtrue.s IL_0047
IL_0044: ldloc.0
IL_0045: br.s IL_0055
IL_0047: ldc.i4.0
IL_0048: ldloca.s V_0
IL_004a: call "Function Integer?.GetValueOrDefault() As Integer"
IL_004f: sub.ovf
IL_0050: newobj "Sub Integer?..ctor(Integer)"
IL_0055: stloc.1
IL_0056: ldstr "y2={0} "
IL_005b: ldloc.1
IL_005c: box "Integer?"
IL_0061: call "Sub System.Console.Write(String, Object)"
IL_0066: ldloca.s V_1
IL_0068: initobj "Integer?"
IL_006e: ldstr "y3={0} "
IL_0073: ldloc.1
IL_0074: box "Integer?"
IL_0079: call "Sub System.Console.Write(String, Object)"
IL_007e: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedIntrinsicNegationField()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Dim x As New Integer?(1)
Sub Main(args As String())
Dim y = -x
Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>, expectedOutput:="-1").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 43 (0x2b)
.maxstack 2
.locals init (Integer? V_0)
IL_0000: ldsfld "MyClass1.x As Integer?"
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call "Function Integer?.get_HasValue() As Boolean"
IL_000d: brtrue.s IL_0012
IL_000f: ldloc.0
IL_0010: br.s IL_0020
IL_0012: ldc.i4.0
IL_0013: ldloca.s V_0
IL_0015: call "Function Integer?.GetValueOrDefault() As Integer"
IL_001a: sub.ovf
IL_001b: newobj "Sub Integer?..ctor(Integer)"
IL_0020: box "Integer?"
IL_0025: call "Sub System.Console.WriteLine(Object)"
IL_002a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedIntrinsicNegationNull()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim y = ---CType(Nothing, Int32?)
Console.WriteLine(y.HasValue)
End Sub
End Module
</file>
</compilation>, expectedOutput:="False").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 21 (0x15)
.maxstack 1
.locals init (Integer? V_0) //y
IL_0000: ldloca.s V_0
IL_0002: initobj "Integer?"
IL_0008: ldloca.s V_0
IL_000a: call "Function Integer?.get_HasValue() As Boolean"
IL_000f: call "Sub System.Console.WriteLine(Boolean)"
IL_0014: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedIntrinsicNegationNotNull()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim y = ---CType(42, Int32?)
Console.WriteLine(y.HasValue)
End Sub
End Module
</file>
</compilation>, expectedOutput:="True").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 28 (0x1c)
.maxstack 5
.locals init (Integer? V_0) //y
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldc.i4.s 42
IL_0007: sub.ovf
IL_0008: sub.ovf
IL_0009: sub.ovf
IL_000a: call "Sub Integer?..ctor(Integer)"
IL_000f: ldloca.s V_0
IL_0011: call "Function Integer?.get_HasValue() As Boolean"
IL_0016: call "Sub System.Console.WriteLine(Boolean)"
IL_001b: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedIsTrueLiteral()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
If Not Not Not (CType(False, Boolean?)) Then
Console.Write("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr "hi"
IL_0005: call "Sub System.Console.Write(String)"
IL_000a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedIsTrueLocal()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x as boolean? = false
If Not Not Not x Then
Console.Write("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 112 (0x70)
.maxstack 2
.locals init (Boolean? V_0, //x
Boolean? V_1,
Boolean? V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: call "Sub Boolean?..ctor(Boolean)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Boolean?.get_HasValue() As Boolean"
IL_000f: brtrue.s IL_0014
IL_0011: ldloc.0
IL_0012: br.s IL_0023
IL_0014: ldloca.s V_0
IL_0016: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001b: ldc.i4.0
IL_001c: ceq
IL_001e: newobj "Sub Boolean?..ctor(Boolean)"
IL_0023: stloc.2
IL_0024: ldloca.s V_2
IL_0026: call "Function Boolean?.get_HasValue() As Boolean"
IL_002b: brtrue.s IL_0030
IL_002d: ldloc.2
IL_002e: br.s IL_003f
IL_0030: ldloca.s V_2
IL_0032: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0037: ldc.i4.0
IL_0038: ceq
IL_003a: newobj "Sub Boolean?..ctor(Boolean)"
IL_003f: stloc.1
IL_0040: ldloca.s V_1
IL_0042: call "Function Boolean?.get_HasValue() As Boolean"
IL_0047: brtrue.s IL_004c
IL_0049: ldloc.1
IL_004a: br.s IL_005b
IL_004c: ldloca.s V_1
IL_004e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0053: ldc.i4.0
IL_0054: ceq
IL_0056: newobj "Sub Boolean?..ctor(Boolean)"
IL_005b: stloc.1
IL_005c: ldloca.s V_1
IL_005e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0063: brfalse.s IL_006f
IL_0065: ldstr "hi"
IL_006a: call "Sub System.Console.Write(String)"
IL_006f: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryPlus()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Integer? = 2
Dim y As Integer? = 4
If x + x = y Then
Console.Write("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 137 (0x89)
.maxstack 2
.locals init (Integer? V_0, //x
Integer? V_1, //y
Integer? V_2,
Integer? V_3,
Boolean? V_4)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.2
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.4
IL_000b: call "Sub Integer?..ctor(Integer)"
IL_0010: ldloca.s V_0
IL_0012: call "Function Integer?.get_HasValue() As Boolean"
IL_0017: ldloca.s V_0
IL_0019: call "Function Integer?.get_HasValue() As Boolean"
IL_001e: and
IL_001f: brtrue.s IL_002c
IL_0021: ldloca.s V_3
IL_0023: initobj "Integer?"
IL_0029: ldloc.3
IL_002a: br.s IL_0040
IL_002c: ldloca.s V_0
IL_002e: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0033: ldloca.s V_0
IL_0035: call "Function Integer?.GetValueOrDefault() As Integer"
IL_003a: add.ovf
IL_003b: newobj "Sub Integer?..ctor(Integer)"
IL_0040: stloc.2
IL_0041: ldloca.s V_2
IL_0043: call "Function Integer?.get_HasValue() As Boolean"
IL_0048: ldloca.s V_1
IL_004a: call "Function Integer?.get_HasValue() As Boolean"
IL_004f: and
IL_0050: brtrue.s IL_005e
IL_0052: ldloca.s V_4
IL_0054: initobj "Boolean?"
IL_005a: ldloc.s V_4
IL_005c: br.s IL_0073
IL_005e: ldloca.s V_2
IL_0060: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0065: ldloca.s V_1
IL_0067: call "Function Integer?.GetValueOrDefault() As Integer"
IL_006c: ceq
IL_006e: newobj "Sub Boolean?..ctor(Boolean)"
IL_0073: stloc.s V_4
IL_0075: ldloca.s V_4
IL_0077: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_007c: brfalse.s IL_0088
IL_007e: ldstr "hi"
IL_0083: call "Sub System.Console.Write(String)"
IL_0088: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryPlus1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Integer? = 0
Console.WriteLine(x + goo(x))
End Sub
Function goo(ByRef v As Integer?) As Integer
v = 0
Return 42
End Function
End Module
</file>
</compilation>, expectedOutput:="42").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 63 (0x3f)
.maxstack 2
.locals init (Integer? V_0, //x
Integer? V_1,
Integer V_2,
Integer? V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldloc.0
IL_0009: stloc.1
IL_000a: ldloca.s V_0
IL_000c: call "Function MyClass1.goo(ByRef Integer?) As Integer"
IL_0011: stloc.2
IL_0012: ldloca.s V_1
IL_0014: call "Function Integer?.get_HasValue() As Boolean"
IL_0019: brtrue.s IL_0026
IL_001b: ldloca.s V_3
IL_001d: initobj "Integer?"
IL_0023: ldloc.3
IL_0024: br.s IL_0034
IL_0026: ldloca.s V_1
IL_0028: call "Function Integer?.GetValueOrDefault() As Integer"
IL_002d: ldloc.2
IL_002e: add.ovf
IL_002f: newobj "Sub Integer?..ctor(Integer)"
IL_0034: box "Integer?"
IL_0039: call "Sub System.Console.WriteLine(Object)"
IL_003e: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryPlusHasValue1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Integer? = 2
If x + x = 4 Then
Console.Write("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 113 (0x71)
.maxstack 2
.locals init (Integer? V_0, //x
Integer? V_1,
Integer? V_2,
Boolean? V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.2
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Integer?.get_HasValue() As Boolean"
IL_000f: ldloca.s V_0
IL_0011: call "Function Integer?.get_HasValue() As Boolean"
IL_0016: and
IL_0017: brtrue.s IL_0024
IL_0019: ldloca.s V_2
IL_001b: initobj "Integer?"
IL_0021: ldloc.2
IL_0022: br.s IL_0038
IL_0024: ldloca.s V_0
IL_0026: call "Function Integer?.GetValueOrDefault() As Integer"
IL_002b: ldloca.s V_0
IL_002d: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0032: add.ovf
IL_0033: newobj "Sub Integer?..ctor(Integer)"
IL_0038: stloc.1
IL_0039: ldloca.s V_1
IL_003b: call "Function Integer?.get_HasValue() As Boolean"
IL_0040: brtrue.s IL_004d
IL_0042: ldloca.s V_3
IL_0044: initobj "Boolean?"
IL_004a: ldloc.3
IL_004b: br.s IL_005c
IL_004d: ldloca.s V_1
IL_004f: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0054: ldc.i4.4
IL_0055: ceq
IL_0057: newobj "Sub Boolean?..ctor(Boolean)"
IL_005c: stloc.3
IL_005d: ldloca.s V_3
IL_005f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0064: brfalse.s IL_0070
IL_0066: ldstr "hi"
IL_006b: call "Sub System.Console.Write(String)"
IL_0070: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryPlusHasValue2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Integer? = 2
If 4 = x + x Then
Console.Write("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 113 (0x71)
.maxstack 2
.locals init (Integer? V_0, //x
Integer? V_1,
Integer? V_2,
Boolean? V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.2
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Integer?.get_HasValue() As Boolean"
IL_000f: ldloca.s V_0
IL_0011: call "Function Integer?.get_HasValue() As Boolean"
IL_0016: and
IL_0017: brtrue.s IL_0024
IL_0019: ldloca.s V_2
IL_001b: initobj "Integer?"
IL_0021: ldloc.2
IL_0022: br.s IL_0038
IL_0024: ldloca.s V_0
IL_0026: call "Function Integer?.GetValueOrDefault() As Integer"
IL_002b: ldloca.s V_0
IL_002d: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0032: add.ovf
IL_0033: newobj "Sub Integer?..ctor(Integer)"
IL_0038: stloc.1
IL_0039: ldloca.s V_1
IL_003b: call "Function Integer?.get_HasValue() As Boolean"
IL_0040: brtrue.s IL_004d
IL_0042: ldloca.s V_3
IL_0044: initobj "Boolean?"
IL_004a: ldloc.3
IL_004b: br.s IL_005c
IL_004d: ldc.i4.4
IL_004e: ldloca.s V_1
IL_0050: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0055: ceq
IL_0057: newobj "Sub Boolean?..ctor(Boolean)"
IL_005c: stloc.3
IL_005d: ldloca.s V_3
IL_005f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0064: brfalse.s IL_0070
IL_0066: ldstr "hi"
IL_006b: call "Sub System.Console.Write(String)"
IL_0070: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryBooleanXor()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Boolean? = True
If (x Xor Nothing) Then
Else
Console.WriteLine("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: newobj "Sub Boolean?..ctor(Boolean)"
IL_0006: pop
IL_0007: ldstr "hi"
IL_000c: call "Sub System.Console.WriteLine(String)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryBooleanXor1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Boolean? = True
Dim y As Boolean? = False
If (x Xor y) Then
Console.WriteLine("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 85 (0x55)
.maxstack 2
.locals init (Boolean? V_0, //x
Boolean? V_1, //y
Boolean? V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Boolean?..ctor(Boolean)"
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.0
IL_000b: call "Sub Boolean?..ctor(Boolean)"
IL_0010: ldloca.s V_0
IL_0012: call "Function Boolean?.get_HasValue() As Boolean"
IL_0017: ldloca.s V_1
IL_0019: call "Function Boolean?.get_HasValue() As Boolean"
IL_001e: and
IL_001f: brtrue.s IL_002c
IL_0021: ldloca.s V_2
IL_0023: initobj "Boolean?"
IL_0029: ldloc.2
IL_002a: br.s IL_0040
IL_002c: ldloca.s V_0
IL_002e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0033: ldloca.s V_1
IL_0035: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_003a: xor
IL_003b: newobj "Sub Boolean?..ctor(Boolean)"
IL_0040: stloc.2
IL_0041: ldloca.s V_2
IL_0043: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0048: brfalse.s IL_0054
IL_004a: ldstr "hi"
IL_004f: call "Sub System.Console.WriteLine(String)"
IL_0054: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryBooleanOrNothing()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Boolean? = True
If (x or Nothing) Then
Console.WriteLine("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 50 (0x32)
.maxstack 2
.locals init (Boolean? V_0, //x
Boolean? V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Boolean?..ctor(Boolean)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000f: brtrue.s IL_001c
IL_0011: ldloca.s V_1
IL_0013: initobj "Boolean?"
IL_0019: ldloc.1
IL_001a: br.s IL_001d
IL_001c: ldloc.0
IL_001d: stloc.1
IL_001e: ldloca.s V_1
IL_0020: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0025: brfalse.s IL_0031
IL_0027: ldstr "hi"
IL_002c: call "Sub System.Console.WriteLine(String)"
IL_0031: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryBooleanAndNothing()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Boolean? = True
If (Nothing And x) Then
Else
Console.WriteLine("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 61 (0x3d)
.maxstack 3
.locals init (Boolean? V_0, //x
Boolean? V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Boolean?..ctor(Boolean)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Boolean?.get_HasValue() As Boolean"
IL_000f: ldloca.s V_0
IL_0011: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0016: ldc.i4.0
IL_0017: ceq
IL_0019: and
IL_001a: brtrue.s IL_0027
IL_001c: ldloca.s V_1
IL_001e: initobj "Boolean?"
IL_0024: ldloc.1
IL_0025: br.s IL_0028
IL_0027: ldloc.0
IL_0028: stloc.1
IL_0029: ldloca.s V_1
IL_002b: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0030: brtrue.s IL_003c
IL_0032: ldstr "hi"
IL_0037: call "Sub System.Console.WriteLine(String)"
IL_003c: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryBooleanAnd()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
If (T() And T()) Then
Console.Write("hi")
End If
End Sub
Function T() As Boolean?
Return True
End Function
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 97 (0x61)
.maxstack 1
.locals init (Boolean? V_0,
Boolean? V_1,
Boolean? V_2)
IL_0000: call "Function MyClass1.T() As Boolean?"
IL_0005: stloc.0
IL_0006: call "Function MyClass1.T() As Boolean?"
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call "Function Boolean?.get_HasValue() As Boolean"
IL_0013: brfalse.s IL_001e
IL_0015: ldloca.s V_0
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brfalse.s IL_0046
IL_001e: ldloca.s V_1
IL_0020: call "Function Boolean?.get_HasValue() As Boolean"
IL_0025: brtrue.s IL_0032
IL_0027: ldloca.s V_2
IL_0029: initobj "Boolean?"
IL_002f: ldloc.2
IL_0030: br.s IL_004c
IL_0032: ldloca.s V_1
IL_0034: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0039: brtrue.s IL_0043
IL_003b: ldc.i4.0
IL_003c: newobj "Sub Boolean?..ctor(Boolean)"
IL_0041: br.s IL_004c
IL_0043: ldloc.0
IL_0044: br.s IL_004c
IL_0046: ldc.i4.0
IL_0047: newobj "Sub Boolean?..ctor(Boolean)"
IL_004c: stloc.1
IL_004d: ldloca.s V_1
IL_004f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0054: brfalse.s IL_0060
IL_0056: ldstr "hi"
IL_005b: call "Sub System.Console.Write(String)"
IL_0060: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryBooleanOr()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Boolean? = True
Dim y As Boolean? = True
If (x Or y) Then
Console.Write("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 101 (0x65)
.maxstack 2
.locals init (Boolean? V_0, //x
Boolean? V_1, //y
Boolean? V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Boolean?..ctor(Boolean)"
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.1
IL_000b: call "Sub Boolean?..ctor(Boolean)"
IL_0010: ldloca.s V_0
IL_0012: call "Function Boolean?.get_HasValue() As Boolean"
IL_0017: brfalse.s IL_0022
IL_0019: ldloca.s V_0
IL_001b: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0020: brtrue.s IL_004a
IL_0022: ldloca.s V_1
IL_0024: call "Function Boolean?.get_HasValue() As Boolean"
IL_0029: brtrue.s IL_0036
IL_002b: ldloca.s V_2
IL_002d: initobj "Boolean?"
IL_0033: ldloc.2
IL_0034: br.s IL_0050
IL_0036: ldloca.s V_1
IL_0038: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_003d: brtrue.s IL_0042
IL_003f: ldloc.0
IL_0040: br.s IL_0050
IL_0042: ldc.i4.1
IL_0043: newobj "Sub Boolean?..ctor(Boolean)"
IL_0048: br.s IL_0050
IL_004a: ldc.i4.1
IL_004b: newobj "Sub Boolean?..ctor(Boolean)"
IL_0050: stloc.2
IL_0051: ldloca.s V_2
IL_0053: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0058: brfalse.s IL_0064
IL_005a: ldstr "hi"
IL_005f: call "Sub System.Console.Write(String)"
IL_0064: ret
}
]]>)
End Sub
<Fact()>
Public Sub BinaryBool()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Module MyClass1
Sub Main(args As String())
Print("== And ==")
Print(T() And T())
Print(T() And F())
Print(T() And N())
Print(F() And T())
Print(F() And F())
Print(F() And N())
Print(N() And T())
Print(N() And F())
Print(N() And N())
Print("== Or ==")
Print(T() Or T())
Print(T() Or F())
Print(T() Or N())
Print(F() Or T())
Print(F() Or F())
Print(F() Or N())
Print(N() Or T())
Print(N() Or F())
Print(N() Or N())
Print("== AndAlso ==")
Print(T() AndAlso T())
Print(T() AndAlso F())
Print(T() AndAlso N())
Print(F() AndAlso T())
Print(F() AndAlso F())
Print(F() AndAlso N())
Print(N() AndAlso T())
Print(N() AndAlso F())
Print(N() AndAlso N())
Print("== OrElse ==")
Print(T() OrElse T())
Print(T() OrElse F())
Print(T() OrElse N())
Print(F() OrElse T())
Print(F() OrElse F())
Print(F() OrElse N())
Print(N() OrElse T())
Print(N() OrElse F())
Print(N() OrElse N())
End Sub
Private Sub Print(s As String)
Console.WriteLine(s)
End Sub
Private Sub Print(r As Boolean?)
Console.Write(": HasValue = ")
Console.Write(r.HasValue)
Console.Write(": Value =")
If r.HasValue Then
Console.Write(" ")
Console.Write(r)
End If
Console.WriteLine()
End Sub
Private Function T() As Boolean?
Console.Write("T")
Return True
End Function
Private Function F() As Boolean?
Console.Write("F")
Return False
End Function
Private Function N() As Boolean?
Console.Write("N")
Return Nothing
End Function
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
== And ==
TT: HasValue = True: Value = True
TF: HasValue = True: Value = False
TN: HasValue = False: Value =
FT: HasValue = True: Value = False
FF: HasValue = True: Value = False
FN: HasValue = True: Value = False
NT: HasValue = False: Value =
NF: HasValue = True: Value = False
NN: HasValue = False: Value =
== Or ==
TT: HasValue = True: Value = True
TF: HasValue = True: Value = True
TN: HasValue = True: Value = True
FT: HasValue = True: Value = True
FF: HasValue = True: Value = False
FN: HasValue = False: Value =
NT: HasValue = True: Value = True
NF: HasValue = False: Value =
NN: HasValue = False: Value =
== AndAlso ==
TT: HasValue = True: Value = True
TF: HasValue = True: Value = False
TN: HasValue = False: Value =
F: HasValue = True: Value = False
F: HasValue = True: Value = False
F: HasValue = True: Value = False
NT: HasValue = False: Value =
NF: HasValue = True: Value = False
NN: HasValue = False: Value =
== OrElse ==
T: HasValue = True: Value = True
T: HasValue = True: Value = True
T: HasValue = True: Value = True
FT: HasValue = True: Value = True
FF: HasValue = True: Value = False
FN: HasValue = False: Value =
NT: HasValue = True: Value = True
NF: HasValue = False: Value =
NN: HasValue = False: Value =
]]>
)
End Sub
<Fact()>
Public Sub BinaryBoolConstLeft()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Module MyClass1
Sub Main(args As String())
Print("== And ==")
Print(True And T())
Print(True And F())
Print(True And N())
Print(False And T())
Print(False And F())
Print(False And N())
Print(Nothing And T())
Print(Nothing And F())
Print(Nothing And N())
Print("== Or ==")
Print(True Or T())
Print(True Or F())
Print(True Or N())
Print(False Or T())
Print(False Or F())
Print(False Or N())
Print(Nothing Or T())
Print(Nothing Or F())
Print(Nothing Or N())
Print("== AndAlso ==")
Print(True AndAlso T())
Print(True AndAlso F())
Print(True AndAlso N())
Print(False AndAlso T())
Print(False AndAlso F())
Print(False AndAlso N())
Print(Nothing AndAlso T())
Print(Nothing AndAlso F())
Print(Nothing AndAlso N())
Print("== OrElse ==")
Print(True OrElse T())
Print(True OrElse F())
Print(True OrElse N())
Print(False OrElse T())
Print(False OrElse F())
Print(False OrElse N())
Print(Nothing OrElse T())
Print(Nothing OrElse F())
Print(Nothing OrElse N())
End Sub
Private Sub Print(s As String)
Console.WriteLine(s)
End Sub
Private Sub Print(r As Boolean?)
Console.Write(": HasValue = ")
Console.Write(r.HasValue)
Console.Write(": Value =")
If r.HasValue Then
Console.Write(" ")
Console.Write(r)
End If
Console.WriteLine()
End Sub
Private Function T() As Boolean?
Console.Write("T")
Return True
End Function
Private Function F() As Boolean?
Console.Write("F")
Return False
End Function
Private Function N() As Boolean?
Console.Write("N")
Return Nothing
End Function
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
== And ==
T: HasValue = True: Value = True
F: HasValue = True: Value = False
N: HasValue = False: Value =
T: HasValue = True: Value = False
F: HasValue = True: Value = False
N: HasValue = True: Value = False
T: HasValue = False: Value =
F: HasValue = True: Value = False
N: HasValue = False: Value =
== Or ==
T: HasValue = True: Value = True
F: HasValue = True: Value = True
N: HasValue = True: Value = True
T: HasValue = True: Value = True
F: HasValue = True: Value = False
N: HasValue = False: Value =
T: HasValue = True: Value = True
F: HasValue = False: Value =
N: HasValue = False: Value =
== AndAlso ==
T: HasValue = True: Value = True
F: HasValue = True: Value = False
N: HasValue = False: Value =
: HasValue = True: Value = False
: HasValue = True: Value = False
: HasValue = True: Value = False
T: HasValue = False: Value =
F: HasValue = True: Value = False
N: HasValue = False: Value =
== OrElse ==
: HasValue = True: Value = True
: HasValue = True: Value = True
: HasValue = True: Value = True
T: HasValue = True: Value = True
F: HasValue = True: Value = False
N: HasValue = False: Value =
T: HasValue = True: Value = True
F: HasValue = False: Value =
N: HasValue = False: Value =
]]>
)
End Sub
<Fact()>
Public Sub BinaryBoolConstRight()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Module MyClass1
Sub Main(args As String())
Print("== And ==")
Print(T() And True)
Print(T() And False)
Print(T() And Nothing)
Print(F() And True)
Print(F() And False)
Print(F() And Nothing)
Print(N() And True)
Print(N() And False)
Print(N() And Nothing)
Print("== Or ==")
Print(T() Or True)
Print(T() Or False)
Print(T() Or Nothing)
Print(F() Or True)
Print(F() Or False)
Print(F() Or Nothing)
Print(N() Or True)
Print(N() Or False)
Print(N() Or Nothing)
Print("== AndAlso ==")
Print(T() AndAlso True)
Print(T() AndAlso False)
Print(T() AndAlso Nothing)
Print(F() AndAlso True)
Print(F() AndAlso False)
Print(F() AndAlso Nothing)
Print(N() AndAlso True)
Print(N() AndAlso False)
Print(N() AndAlso Nothing)
Print("== OrElse ==")
Print(T() OrElse True)
Print(T() OrElse False)
Print(T() OrElse Nothing)
Print(F() OrElse True)
Print(F() OrElse False)
Print(F() OrElse Nothing)
Print(N() OrElse True)
Print(N() OrElse False)
Print(N() OrElse Nothing)
End Sub
Private Sub Print(s As String)
Console.WriteLine(s)
End Sub
Private Sub Print(r As Boolean?)
Console.Write(": HasValue = ")
Console.Write(r.HasValue)
Console.Write(": Value =")
If r.HasValue Then
Console.Write(" ")
Console.Write(r)
End If
Console.WriteLine()
End Sub
Private Function T() As Boolean?
Console.Write("T")
Return True
End Function
Private Function F() As Boolean?
Console.Write("F")
Return False
End Function
Private Function N() As Boolean?
Console.Write("N")
Return Nothing
End Function
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
== And ==
T: HasValue = True: Value = True
T: HasValue = True: Value = False
T: HasValue = False: Value =
F: HasValue = True: Value = False
F: HasValue = True: Value = False
F: HasValue = True: Value = False
N: HasValue = False: Value =
N: HasValue = True: Value = False
N: HasValue = False: Value =
== Or ==
T: HasValue = True: Value = True
T: HasValue = True: Value = True
T: HasValue = True: Value = True
F: HasValue = True: Value = True
F: HasValue = True: Value = False
F: HasValue = False: Value =
N: HasValue = True: Value = True
N: HasValue = False: Value =
N: HasValue = False: Value =
== AndAlso ==
T: HasValue = True: Value = True
T: HasValue = True: Value = False
T: HasValue = False: Value =
F: HasValue = True: Value = False
F: HasValue = True: Value = False
F: HasValue = True: Value = False
N: HasValue = False: Value =
N: HasValue = True: Value = False
N: HasValue = False: Value =
== OrElse ==
T: HasValue = True: Value = True
T: HasValue = True: Value = True
T: HasValue = True: Value = True
F: HasValue = True: Value = True
F: HasValue = True: Value = False
F: HasValue = False: Value =
N: HasValue = True: Value = True
N: HasValue = False: Value =
N: HasValue = False: Value =
]]>
)
End Sub
<Fact()>
Public Sub NewBooleanInLogicalExpression()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim bRet As Boolean?
bRet = New Boolean?(True) And Nothing
Console.WriteLine("Ret1={0}", bRet)
Select Case bret
Case Nothing
Console.WriteLine("Nothing")
Case Else
Console.Write("Else: ")
If (Nothing Or New Boolean?(False)) Is Nothing Then
Console.WriteLine("Ret2={0}", New Boolean?(True) OrElse New Boolean?() AndAlso New Boolean?(False))
End If
End Select
End Sub
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
Ret1=
Else: Ret2=True
]]>
).VerifyDiagnostics(Diagnostic(ERRID.WRN_EqualToLiteralNothing, "Nothing"))
End Sub
<Fact(), WorkItem(544948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544948")>
Public Sub NothingOrZeroInBinaryExpression()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Enum E
Zero
One
End Enum
Module M
Friend bN As Boolean? = Nothing
Public x As ULong? = 11
Sub Main()
Dim nZ As Integer? = 0
Dim r = nZ + 0 - nZ * 0
Console.Write("r1={0}", r)
Dim eN As E? = Nothing
Dim y As UShort? = Nothing
r = eN - bN * nZ + Nothing ^ y Mod x
Console.Write(" r2={0}", r)
End Sub
End Module
</file>
</compilation>, expectedOutput:="r1=0 r2=")
End Sub
<Fact()>
Public Sub NullableIs()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Boolean? = Nothing
If (x Is Nothing) Then
Console.WriteLine("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 28 (0x1c)
.maxstack 1
.locals init (Boolean? V_0) //x
IL_0000: ldloca.s V_0
IL_0002: initobj "Boolean?"
IL_0008: ldloca.s V_0
IL_000a: call "Function Boolean?.get_HasValue() As Boolean"
IL_000f: brtrue.s IL_001b
IL_0011: ldstr "hi"
IL_0016: call "Sub System.Console.WriteLine(String)"
IL_001b: ret
}
]]>)
End Sub
<Fact()>
Public Sub NullableIsNot()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
If Nothing IsNot CType(3, Int32?) Then
Console.WriteLine("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr "hi"
IL_0005: call "Sub System.Console.WriteLine(String)"
IL_000a: ret
}
]]>)
End Sub
<Fact()>
Public Sub NullableIsAndIsNot()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main()
While New Boolean?(False) Is Nothing OrElse Nothing IsNot New Boolean?(True)
If Nothing Is New Ulong?() Then
Console.Write("True")
Exit While
End If
End While
End Sub
End Module
</file>
</compilation>, expectedOutput:="True").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr "True"
IL_0005: call "Sub System.Console.Write(String)"
IL_000a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedIntrinsicConversion()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Integer = 123
Dim y As Long? = x
Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>, expectedOutput:="123").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 21 (0x15)
.maxstack 1
.locals init (Integer V_0) //x
IL_0000: ldc.i4.s 123
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: conv.i8
IL_0005: newobj "Sub Long?..ctor(Long)"
IL_000a: box "Long?"
IL_000f: call "Sub System.Console.WriteLine(Object)"
IL_0014: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedInterfaceConversion()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As IComparable(Of Integer) = 123
Dim y As Integer? = x
Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>, expectedOutput:="123").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 28 (0x1c)
.maxstack 1
IL_0000: ldc.i4.s 123
IL_0002: box "Integer"
IL_0007: castclass "System.IComparable(Of Integer)"
IL_000c: unbox.any "Integer?"
IL_0011: box "Integer?"
IL_0016: call "Sub System.Console.WriteLine(Object)"
IL_001b: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedReferenceConversionNarrowingFail()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Short? = 42
Dim z As ValueType = x
Try
Dim y As UInteger? = z
Console.WriteLine(y)
Catch ex As InvalidCastException
Console.WriteLine("pass")
End Try
End Sub
End Module
</file>
</compilation>, expectedOutput:="pass").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 56 (0x38)
.maxstack 2
.locals init (System.ValueType V_0, //z
System.InvalidCastException V_1) //ex
IL_0000: ldc.i4.s 42
IL_0002: newobj "Sub Short?..ctor(Short)"
IL_0007: box "Short?"
IL_000c: stloc.0
.try
{
IL_000d: ldloc.0
IL_000e: unbox.any "UInteger?"
IL_0013: box "UInteger?"
IL_0018: call "Sub System.Console.WriteLine(Object)"
IL_001d: leave.s IL_0037
}
catch System.InvalidCastException
{
IL_001f: dup
IL_0020: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0025: stloc.1
IL_0026: ldstr "pass"
IL_002b: call "Sub System.Console.WriteLine(String)"
IL_0030: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0035: leave.s IL_0037
}
IL_0037: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedInterfaceConversion1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Integer? = 123
Dim y As IComparable(Of Integer) = x
Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>, expectedOutput:="123").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldc.i4.s 123
IL_0002: newobj "Sub Integer?..ctor(Integer)"
IL_0007: box "Integer?"
IL_000c: call "Sub System.Console.WriteLine(Object)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedInterfaceConversionGeneric()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
goo(42)
End Sub
Sub goo(Of T As {Structure, IComparable(Of T)})(x As T?)
Dim y As IComparable(Of T) = x
Console.Write(y.CompareTo(x.Value))
End Sub
End Module
</file>
</compilation>, expectedOutput:="0").
VerifyIL("MyClass1.goo",
<![CDATA[
{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box "T?"
IL_0006: ldarga.s V_0
IL_0008: call "Function T?.get_Value() As T"
IL_000d: callvirt "Function System.IComparable(Of T).CompareTo(T) As Integer"
IL_0012: call "Sub System.Console.Write(Integer)"
IL_0017: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedInterfaceConversionGeneric1()
Dim compilationDef =
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
goo(42)
End Sub
Sub goo(Of T As {Structure, IComparable(Of T)})(x As T?)
Dim y As IComparable(Of Integer) = x
Console.Write(y.CompareTo(43))
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom))
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42016: Implicit conversion from 'T?' to 'IComparable(Of Integer)'.
Dim y As IComparable(Of Integer) = x
~
</expected>)
CompileAndVerify(compilation,
expectedOutput:="-1").
VerifyIL("MyClass1.goo",
<![CDATA[
{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box "T?"
IL_0006: castclass "System.IComparable(Of Integer)"
IL_000b: ldc.i4.s 43
IL_000d: callvirt "Function System.IComparable(Of Integer).CompareTo(Integer) As Integer"
IL_0012: call "Sub System.Console.Write(Integer)"
IL_0017: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedCompoundOp()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
Module MyClass1
Sub Main()
Dim y As Integer? = 42
y += 1
Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>, expectedOutput:="43").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 2
.locals init (Integer? V_0,
Integer? V_1)
IL_0000: ldc.i4.s 42
IL_0002: newobj "Sub Integer?..ctor(Integer)"
IL_0007: stloc.0
IL_0008: ldloca.s V_0
IL_000a: call "Function Integer?.get_HasValue() As Boolean"
IL_000f: brtrue.s IL_001c
IL_0011: ldloca.s V_1
IL_0013: initobj "Integer?"
IL_0019: ldloc.1
IL_001a: br.s IL_002a
IL_001c: ldloca.s V_0
IL_001e: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0023: ldc.i4.1
IL_0024: add.ovf
IL_0025: newobj "Sub Integer?..ctor(Integer)"
IL_002a: box "Integer?"
IL_002f: call "Sub System.Console.WriteLine(Object)"
IL_0034: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedCompoundOp1()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
Module MyClass1
Sub Main()
Dim y As Integer? = 42
y += Nothing
Console.WriteLine(y.HasValue)
End Sub
End Module
</file>
</compilation>, expectedOutput:="False").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 30 (0x1e)
.maxstack 2
.locals init (Integer? V_0) //y
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: call "Sub Integer?..ctor(Integer)"
IL_0009: ldloca.s V_0
IL_000b: initobj "Integer?"
IL_0011: ldloca.s V_0
IL_0013: call "Function Integer?.get_HasValue() As Boolean"
IL_0018: call "Sub System.Console.WriteLine(Boolean)"
IL_001d: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryIf()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
Module MyClass1
Sub Main()
Dim y As Integer? = 123
Console.Write(If(If(New Long?(), New Short?(42)), y))
Console.Write(If(If(New Short?(42), New Long?()), y))
End Sub
End Module
</file>
</compilation>, expectedOutput:="4242").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 35 (0x23)
.maxstack 1
IL_0000: ldc.i4.s 123
IL_0002: newobj "Sub Integer?..ctor(Integer)"
IL_0007: pop
IL_0008: ldc.i4.s 42
IL_000a: conv.i8
IL_000b: box "Long"
IL_0010: call "Sub System.Console.Write(Object)"
IL_0015: ldc.i4.s 42
IL_0017: conv.i8
IL_0018: box "Long"
IL_001d: call "Sub System.Console.Write(Object)"
IL_0022: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryIf1()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
Module MyClass1
Sub Main()
Dim x As Long? = Nothing
Dim y As Integer? = 42
Console.WriteLine(If(y, x))
End Sub
End Module
</file>
</compilation>, expectedOutput:="42").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 2
.locals init (Long? V_0, //x
Integer? V_1) //y
IL_0000: ldloca.s V_0
IL_0002: initobj "Long?"
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.s 42
IL_000c: call "Sub Integer?..ctor(Integer)"
IL_0011: ldloca.s V_1
IL_0013: call "Function Integer?.get_HasValue() As Boolean"
IL_0018: brtrue.s IL_001d
IL_001a: ldloc.0
IL_001b: br.s IL_002a
IL_001d: ldloca.s V_1
IL_001f: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0024: conv.i8
IL_0025: newobj "Sub Long?..ctor(Long)"
IL_002a: box "Long?"
IL_002f: call "Sub System.Console.WriteLine(Object)"
IL_0034: ret
}
]]>)
End Sub
<Fact(), WorkItem(544930, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544930")>
Public Sub LiftedBinaryIf1a()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
Module MyClass1
Sub Main()
Console.Write(If(y, x))
Console.Write(If(x, y))
End Sub
Function x() As Long?
Console.Write("x")
Return Nothing
End Function
Function y() As Integer?
Console.Write("y")
Return 42
End Function
End Module
</file>
</compilation>, expectedOutput:="y42xy42")
End Sub
<Fact()>
Public Sub LiftedBinaryIf2()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
Module MyClass1
Sub Main()
Dim x As Short? = Nothing
Dim y As Ushort? = 42
Console.WriteLine(If(y, x))
End Sub
End Module
</file>
</compilation>, expectedOutput:="42").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 57 (0x39)
.maxstack 2
.locals init (Short? V_0, //x
UShort? V_1) //y
IL_0000: ldloca.s V_0
IL_0002: initobj "Short?"
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.s 42
IL_000c: call "Sub UShort?..ctor(UShort)"
IL_0011: ldloca.s V_1
IL_0013: call "Function UShort?.get_HasValue() As Boolean"
IL_0018: brtrue.s IL_0022
IL_001a: ldloc.0
IL_001b: box "Short?"
IL_0020: br.s IL_002e
IL_0022: ldloca.s V_1
IL_0024: call "Function UShort?.GetValueOrDefault() As UShort"
IL_0029: box "UShort"
IL_002e: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0033: call "Sub System.Console.WriteLine(Object)"
IL_0038: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryIf3()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main()
Dim x As Short? = Nothing
Dim y As Long = 42S
Dim z = If(x, y)
Console.WriteLine(z)
End Sub
End Module
</file>
</compilation>, expectedOutput:="42").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 38 (0x26)
.maxstack 1
.locals init (Short? V_0, //x
Long V_1) //y
IL_0000: ldloca.s V_0
IL_0002: initobj "Short?"
IL_0008: ldc.i4.s 42
IL_000a: conv.i8
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call "Function Short?.get_HasValue() As Boolean"
IL_0013: brtrue.s IL_0018
IL_0015: ldloc.1
IL_0016: br.s IL_0020
IL_0018: ldloca.s V_0
IL_001a: call "Function Short?.GetValueOrDefault() As Short"
IL_001f: conv.i8
IL_0020: call "Sub System.Console.WriteLine(Long)"
IL_0025: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryIf4()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main()
Dim x As Short? = Nothing
Dim y As IComparable(Of Short) = 42S
Dim z = If(x, y)
Console.WriteLine(z)
End Sub
End Module
</file>
</compilation>, expectedOutput:="42").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 56 (0x38)
.maxstack 1
.locals init (Short? V_0, //x
System.IComparable(Of Short) V_1) //y
IL_0000: ldloca.s V_0
IL_0002: initobj "Short?"
IL_0008: ldc.i4.s 42
IL_000a: box "Short"
IL_000f: castclass "System.IComparable(Of Short)"
IL_0014: stloc.1
IL_0015: ldloca.s V_0
IL_0017: call "Function Short?.get_HasValue() As Boolean"
IL_001c: brtrue.s IL_0021
IL_001e: ldloc.1
IL_001f: br.s IL_0032
IL_0021: ldloca.s V_0
IL_0023: call "Function Short?.GetValueOrDefault() As Short"
IL_0028: box "Short"
IL_002d: castclass "System.IComparable(Of Short)"
IL_0032: call "Sub System.Console.WriteLine(Object)"
IL_0037: ret
}
]]>)
End Sub
<Fact, WorkItem(545064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545064")>
Public Sub LiftedBinaryIf5_Nested()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Infer On
Imports System
Module Program
Sub Main()
Dim s4_a As Integer? = Nothing
If If(If(True, s4_a, 0), If(True, s4_a, 0)) Then
Console.Write("Fail")
Else
Console.Write("Pass")
End If
End Sub
End Module
]]>
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedOutput:="Pass")
End Sub
<Fact(), WorkItem(544945, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544945")>
Public Sub LiftedBinaryRelationalWithNothingLiteral()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Shared Sub Main()
Dim x As SByte? = 127
Dim y As SByte? = Nothing
Dim r1 = x >= Nothing ' = Nothing
Console.Write("r1={0} ", r1)
Dim r2 As Boolean? = Nothing < x ' = Nothing
Console.Write("r2={0} ", r2)
r1 = x > y
Console.Write("r3={0} ", r1)
r2 = y <= x
Console.Write("r4={0} ", r2)
End Sub
End Class
]]>
</file>
</compilation>
'emitOptions:=EmitOptions.RefEmitBug,
CompileAndVerify(source, expectedOutput:="r1= r2= r3= r4=")
End Sub
<WorkItem(544946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544946")>
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub LiftedBinaryConcatLikeWithNothingLiteral()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Shared Sub Main()
Dim x As SByte? = 127
Dim r1 = x & Nothing ' = 127
Console.Write("r1={0} ", r1)
Dim r2 = Nothing Like x ' = False
Console.Write("r2={0}", r2)
End Sub
End Class
]]>
</file>
</compilation>
'emitOptions:=EmitOptions.RefEmitBug,
CompileAndVerify(source, expectedOutput:="r1=127 r2=False")
End Sub
<Fact(), WorkItem(544947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544947")>
Public Sub LiftedBinaryDivisionWithNothingLiteral()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Shared Sub Main()
Dim x As SByte? = 127
Dim y As SByte? = Nothing
Dim r1 = y / Nothing ' = Nothing
Console.Write("r1={0} ", r1)
Dim r2 = Nothing / x ' = Nothing
Console.Write("r2={0} ", r2)
r1 = x \ Nothing
Console.Write("r3={0} ", r1)
r2 = Nothing \ y
Console.Write("r4={0} ", r2)
r1 = x \ y
Console.Write("r5={0} ", r1)
r2 = y / x
Console.Write("r6={0} ", r2)
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="r1= r2= r3= r4= r5= r6=")
End Sub
<Fact()>
Public Sub LiftedConversionHasValue()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Structure S1
Public x As Integer
Public Shared Widening Operator CType(ByVal a As S1) As S2
Console.Write("W")
Dim result As S2
result.x = a.x + 1
Return result
End Operator
Sub New(x As Integer)
Me.x = x
End Sub
End Structure
Structure S2
Public x As Integer
End Structure
Sub Main()
Dim y As S2 = New S1?(New S1(42))
Console.WriteLine(y.x)
End Sub
End Module
</file>
</compilation>, expectedOutput:="W43").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldc.i4.s 42
IL_0002: newobj "Sub MyClass1.S1..ctor(Integer)"
IL_0007: call "Function MyClass1.S1.op_Implicit(MyClass1.S1) As MyClass1.S2"
IL_000c: ldfld "MyClass1.S2.x As Integer"
IL_0011: call "Sub System.Console.WriteLine(Integer)"
IL_0016: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedConversionHasNoValue()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Structure S1
Public x As Integer
Public Shared Widening Operator CType(ByVal a As S1) As S2
Console.Write("W")
Dim result As S2
result.x = a.x + 1
Return result
End Operator
Sub New(x As Integer)
Me.x = x
End Sub
End Structure
Structure S2
Public x As Integer
End Structure
Sub Main()
Try
Dim y As S2 = New S1?()
Console.WriteLine(y.x)
Catch ex As InvalidOperationException
Console.WriteLine("pass")
End Try
End Sub
End Module
</file>
</compilation>, expectedOutput:="pass").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 59 (0x3b)
.maxstack 2
.locals init (MyClass1.S1? V_0,
System.InvalidOperationException V_1) //ex
.try
{
IL_0000: ldloca.s V_0
IL_0002: initobj "MyClass1.S1?"
IL_0008: ldloc.0
IL_0009: stloc.0
IL_000a: ldloca.s V_0
IL_000c: call "Function MyClass1.S1?.get_Value() As MyClass1.S1"
IL_0011: call "Function MyClass1.S1.op_Implicit(MyClass1.S1) As MyClass1.S2"
IL_0016: ldfld "MyClass1.S2.x As Integer"
IL_001b: call "Sub System.Console.WriteLine(Integer)"
IL_0020: leave.s IL_003a
}
catch System.InvalidOperationException
{
IL_0022: dup
IL_0023: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0028: stloc.1
IL_0029: ldstr "pass"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0038: leave.s IL_003a
}
IL_003a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedConversion()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Structure S1
Public x As Integer
Public Shared Widening Operator CType(ByVal a As S1) As S2
Console.Write("W")
Dim result As S2
result.x = a.x + 1
Return result
End Operator
Sub New(x As Integer)
Me.x = x
End Sub
End Structure
Structure S2
Public x As Integer
End Structure
Sub Main()
Dim x As S1? = New S1(42)
Dim y As S2? = x
Console.WriteLine(y.Value.x)
End Sub
End Module
</file>
</compilation>, expectedOutput:="W43").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 70 (0x46)
.maxstack 2
.locals init (MyClass1.S1? V_0, //x
MyClass1.S2? V_1, //y
MyClass1.S2? V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: newobj "Sub MyClass1.S1..ctor(Integer)"
IL_0009: call "Sub MyClass1.S1?..ctor(MyClass1.S1)"
IL_000e: ldloca.s V_0
IL_0010: call "Function MyClass1.S1?.get_HasValue() As Boolean"
IL_0015: brtrue.s IL_0022
IL_0017: ldloca.s V_2
IL_0019: initobj "MyClass1.S2?"
IL_001f: ldloc.2
IL_0020: br.s IL_0033
IL_0022: ldloca.s V_0
IL_0024: call "Function MyClass1.S1?.GetValueOrDefault() As MyClass1.S1"
IL_0029: call "Function MyClass1.S1.op_Implicit(MyClass1.S1) As MyClass1.S2"
IL_002e: newobj "Sub MyClass1.S2?..ctor(MyClass1.S2)"
IL_0033: stloc.1
IL_0034: ldloca.s V_1
IL_0036: call "Function MyClass1.S2?.get_Value() As MyClass1.S2"
IL_003b: ldfld "MyClass1.S2.x As Integer"
IL_0040: call "Sub System.Console.WriteLine(Integer)"
IL_0045: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedConversionDev10()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
imports Microsoft.VisualBasic
Module Module1
Sub Main()
Dim av As New S1
Dim c As S1?
Dim d As T1?
d = c
Console.WriteLine("Lifted UD conversion: null check skips conversion call. d.HasValue= {0}" & Environment.NewLine, d.HasValue) 'expect 7
c = 1
Console.WriteLine("widening to nullable UD conversion: c=1; c.value= {0}" & Environment.NewLine, c.Value.i) 'expect 7
c = Nothing
Console.WriteLine("widening to nullable UD conversion: c=Nothing; c.HasValue= {0}" & Environment.NewLine, c.HasValue) 'expect 7
av.i = 7
Dim a2 As New S1?(av)
Dim b2 As T1
b2 = a2
Console.WriteLine("regular UD conversion+PDconversion: S1?->S1 -->T1, value passed:{0}" & Environment.NewLine, b2.i) 'expect 7
Dim a21 As New S1
a21.i = 8
Dim b21 As T1?
b21 = a21
Console.WriteLine("regular UD conversion+PD conversion: S1-->T1->T1?, value passed:{0}" & Environment.NewLine, b21.Value.i) 'expect 8
Dim val As New S1
val.i = 3
c = New S1?(val)
d = c
Console.WriteLine("lifted UD conversion, value passed:{0}" & Environment.NewLine, d.Value.i) 'expect 3
Dim k As New S2
k.i = 2
Dim c2 As New S2?(k)
Dim d2 As T2?
d2 = c2 'UD conversion on nullable preferred over lifting
Console.WriteLine(" UD nullable conversion, preferred over lifted value passed: {0}" & Environment.NewLine, d2.Value.i) 'expect 2
av.i = 5
Dim a As New S1?(av)
'a.i = 2
Dim b As T1?
b = a
Console.WriteLine("lifted UD conversion, value passed:{0}" & Environment.NewLine, b.Value.i) 'expect 5
Dim a1 As S1
a1.i = 6
Dim b1 As T1
b1 = a1
Console.WriteLine("regular UD conversion, value passed:{0}" & Environment.NewLine, b1.i) 'expect 6
Dim a3 As S1
a3.i = 8
Dim b3 As T1?
b3 = a3
Console.WriteLine("regular UD conversion+PD conversion, value passed:{0}" & Environment.NewLine, b3.Value.i) 'expect 8
Dim atv = New st(Of Integer)
atv.i = 9
Dim at As New st(Of Integer)?(atv)
Dim bt As Integer?
bt = at
Console.WriteLine("generic UD, value passed bt.value = :{0}" & Environment.NewLine, bt.Value) 'expect 8
End Sub
Structure S1
Dim i As Integer
'Public Shared Widening Operator CType(ByVal a As S1?) As T1?
' Dim t As New T1
' t.i = a.Value.i
' Return t
'End Operator
Public Shared Narrowing Operator CType(ByVal a As S1) As T1
Dim t As New T1
t.i = a.i
Console.WriteLine("UD regular conversion S1->T1 (possible by lifting) invoked")
Return t
End Operator
Public Shared Widening Operator CType(ByVal a As Integer) As S1
Dim t As New S1
t.i = a
Console.WriteLine("UD regular conversion int->S1 (possible by lifting) invoked")
Return t
End Operator
End Structure
Structure T1
Dim i As Integer
End Structure
Structure S2
Dim i As Integer
Public Shared Widening Operator CType(ByVal a As S2?) As T2?
Console.WriteLine("UD S2?->T2? conversion on nullable invoked")
If a.HasValue Then
Dim t As New T2
t.i = a.Value.i
Return t
Else
Return Nothing
End If
End Operator
Public Shared Narrowing Operator CType(ByVal a As S2) As T2
Dim t As New T2
t.i = a.i
Console.WriteLine("UD regular conversion S2->T2 (possible by lifting) invoked")
Return t
End Operator
End Structure
Structure T2
Dim i As Integer
'Public Shared Narrowing Operator CType(ByVal a As T2) As T2
' Dim t As New T2
' t.i = a.i
' Return t
'End Operator
End Structure
Structure st(Of T As Structure)
Dim i As T
Public Shared Narrowing Operator CType(ByVal a As st(Of T)) As T
Dim t As New T
t = a.i
Console.WriteLine("UD generic regular conversion st(of T)->T (possible by lifting) invoked")
Return t
End Operator
End Structure
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[Lifted UD conversion: null check skips conversion call. d.HasValue= False
UD regular conversion int->S1 (possible by lifting) invoked
widening to nullable UD conversion: c=1; c.value= 1
widening to nullable UD conversion: c=Nothing; c.HasValue= False
UD regular conversion S1->T1 (possible by lifting) invoked
regular UD conversion+PDconversion: S1?->S1 -->T1, value passed:7
UD regular conversion S1->T1 (possible by lifting) invoked
regular UD conversion+PD conversion: S1-->T1->T1?, value passed:8
UD regular conversion S1->T1 (possible by lifting) invoked
lifted UD conversion, value passed:3
UD S2?->T2? conversion on nullable invoked
UD nullable conversion, preferred over lifted value passed: 2
UD regular conversion S1->T1 (possible by lifting) invoked
lifted UD conversion, value passed:5
UD regular conversion S1->T1 (possible by lifting) invoked
regular UD conversion, value passed:6
UD regular conversion S1->T1 (possible by lifting) invoked
regular UD conversion+PD conversion, value passed:8
UD generic regular conversion st(of T)->T (possible by lifting) invoked
generic UD, value passed bt.value = :9
]]>)
End Sub
<Fact()>
Public Sub LiftedWideningAndNarrowingConversions()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Structure S(Of T As Structure)
Shared Narrowing Operator CType(x As S(Of T)) As T
System.Console.Write("Narrowing ")
Return Nothing
End Operator
Shared Widening Operator CType(x As S(Of T)) As T?
System.Console.Write("Widening ")
Return Nothing
End Operator
End Structure
Module Program
Sub Main()
Dim x As S(Of Integer)? = New S(Of Integer)()
Dim y As Integer? = 123
Dim ret = If(x, y)
Console.Write("Ret={0}", ret)
End Sub
End Module
</file>
</compilation>, expectedOutput:="Widening Ret=").
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 67 (0x43)
.maxstack 2
.locals init (S(Of Integer)? V_0, //x
Integer? V_1, //y
Integer? V_2, //ret
S(Of Integer) V_3)
IL_0000: ldloca.s V_0
IL_0002: ldloca.s V_3
IL_0004: initobj "S(Of Integer)"
IL_000a: ldloc.3
IL_000b: call "Sub S(Of Integer)?..ctor(S(Of Integer))"
IL_0010: ldloca.s V_1
IL_0012: ldc.i4.s 123
IL_0014: call "Sub Integer?..ctor(Integer)"
IL_0019: ldloca.s V_0
IL_001b: call "Function S(Of Integer)?.get_HasValue() As Boolean"
IL_0020: brtrue.s IL_0025
IL_0022: ldloc.1
IL_0023: br.s IL_0031
IL_0025: ldloca.s V_0
IL_0027: call "Function S(Of Integer)?.GetValueOrDefault() As S(Of Integer)"
IL_002c: call "Function S(Of Integer).op_Implicit(S(Of Integer)) As Integer?"
IL_0031: stloc.2
IL_0032: ldstr "Ret={0}"
IL_0037: ldloc.2
IL_0038: box "Integer?"
IL_003d: call "Sub System.Console.Write(String, Object)"
IL_0042: ret
}]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryUserDefinedMinusDev10()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
imports Microsoft.VisualBasic
Structure S1
Public x As Integer
Public Sub New(ByVal x As Integer)
Me.x = x
End Sub
Public Shared Operator -(ByVal x As S1, ByVal y As S1?) As S1
Return New S1(x.x - y.Value.x)
End Operator
End Structure
Module M1
Sub OutputEntry(ByVal expr As String, ByVal value As S1)
Console.WriteLine("{0} = {1}", expr, value.x)
End Sub
Sub Main()
Dim a As S1? = Nothing
Dim b As S1? = New S1(1)
Dim c As New S1(2)
Dim tmp As S1
Try
tmp = a - c
Catch ex As InvalidOperationException
Console.WriteLine("a - c threw an InvalidOperationException as expected!")
End Try
Try
tmp = c - a
Catch ex As InvalidOperationException
Console.WriteLine("c - a threw an InvalidOperationException as expected!")
End Try
Try
tmp = a - b
Catch ex As InvalidOperationException
Console.WriteLine("a - b threw an InvalidOperationException as expected!")
End Try
Try
tmp = b - a
Catch ex As InvalidOperationException
Console.WriteLine("a - b threw an InvalidOperationException as expected!")
End Try
OutputEntry("b - c", b - c)
OutputEntry("c - b", c - b)
End Sub
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[a - c threw an InvalidOperationException as expected!
c - a threw an InvalidOperationException as expected!
a - b threw an InvalidOperationException as expected!
a - b threw an InvalidOperationException as expected!
b - c = -1
c - b = 1
]]>)
End Sub
<Fact()>
Public Sub LiftedUnaryUserDefinedMinusDev10()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Structure S1
Dim x As Integer
Public Sub New(ByVal x As Integer)
Me.x = x
End Sub
Public Shared Operator -(ByVal x As S1) As S1
Return New S1(-x.x)
End Operator
End Structure
Module M1
Sub Main()
Dim arg As S1? = New S1(1)
Dim x = -arg
Dim y = -New S1?
Dim z = -New S1?(New S1(4))
Console.WriteLine("x.Value = {0}", x.Value.x)
Console.WriteLine("y.HasValue = {0}", y.HasValue)
Console.WriteLine("z.Value = {0}", z.Value.x)
End Sub
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[x.Value = -1
y.HasValue = False
z.Value = -4
]]>).
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 155 (0x9b)
.maxstack 2
.locals init (S1? V_0, //arg
S1? V_1, //x
S1? V_2, //y
S1? V_3, //z
S1? V_4)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: newobj "Sub S1..ctor(Integer)"
IL_0008: call "Sub S1?..ctor(S1)"
IL_000d: ldloca.s V_0
IL_000f: call "Function S1?.get_HasValue() As Boolean"
IL_0014: brtrue.s IL_0022
IL_0016: ldloca.s V_4
IL_0018: initobj "S1?"
IL_001e: ldloc.s V_4
IL_0020: br.s IL_0033
IL_0022: ldloca.s V_0
IL_0024: call "Function S1?.GetValueOrDefault() As S1"
IL_0029: call "Function S1.op_UnaryNegation(S1) As S1"
IL_002e: newobj "Sub S1?..ctor(S1)"
IL_0033: stloc.1
IL_0034: ldloca.s V_2
IL_0036: initobj "S1?"
IL_003c: ldloca.s V_3
IL_003e: ldc.i4.4
IL_003f: newobj "Sub S1..ctor(Integer)"
IL_0044: call "Function S1.op_UnaryNegation(S1) As S1"
IL_0049: call "Sub S1?..ctor(S1)"
IL_004e: ldstr "x.Value = {0}"
IL_0053: ldloca.s V_1
IL_0055: call "Function S1?.get_Value() As S1"
IL_005a: ldfld "S1.x As Integer"
IL_005f: box "Integer"
IL_0064: call "Sub System.Console.WriteLine(String, Object)"
IL_0069: ldstr "y.HasValue = {0}"
IL_006e: ldloca.s V_2
IL_0070: call "Function S1?.get_HasValue() As Boolean"
IL_0075: box "Boolean"
IL_007a: call "Sub System.Console.WriteLine(String, Object)"
IL_007f: ldstr "z.Value = {0}"
IL_0084: ldloca.s V_3
IL_0086: call "Function S1?.get_Value() As S1"
IL_008b: ldfld "S1.x As Integer"
IL_0090: box "Integer"
IL_0095: call "Sub System.Console.WriteLine(String, Object)"
IL_009a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryUserDefinedOneArgNotNullable()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Structure S1
Dim x As Integer
Public Sub New(ByVal x As Integer)
Me.x = x
End Sub
Public Shared Operator -(ByVal x As S1, ByVal y As S1) As S1
Return New S1(x.x - y.x)
End Operator
End Structure
Module M1
Sub Main()
Dim x As New S1?(New S1(42))
Dim y = x - New S1(2)
Console.WriteLine(y.Value.x)
End Sub
End Module
</file>
</compilation>, expectedOutput:="40").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 79 (0x4f)
.maxstack 2
.locals init (S1? V_0, //x
S1? V_1, //y
S1 V_2,
S1? V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: newobj "Sub S1..ctor(Integer)"
IL_0009: call "Sub S1?..ctor(S1)"
IL_000e: ldloca.s V_2
IL_0010: ldc.i4.2
IL_0011: call "Sub S1..ctor(Integer)"
IL_0016: ldloca.s V_0
IL_0018: call "Function S1?.get_HasValue() As Boolean"
IL_001d: brtrue.s IL_002a
IL_001f: ldloca.s V_3
IL_0021: initobj "S1?"
IL_0027: ldloc.3
IL_0028: br.s IL_003c
IL_002a: ldloca.s V_0
IL_002c: call "Function S1?.GetValueOrDefault() As S1"
IL_0031: ldloc.2
IL_0032: call "Function S1.op_Subtraction(S1, S1) As S1"
IL_0037: newobj "Sub S1?..ctor(S1)"
IL_003c: stloc.1
IL_003d: ldloca.s V_1
IL_003f: call "Function S1?.get_Value() As S1"
IL_0044: ldfld "S1.x As Integer"
IL_0049: call "Sub System.Console.WriteLine(Integer)"
IL_004e: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryUserDefinedReturnsNullable()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Structure S1
Dim x As Integer
Public Sub New(ByVal x As Integer)
Me.x = x
End Sub
Public Shared Operator +(ByVal x As S1, ByVal y As S1) As S1?
Return New S1(x.x + y.x)
End Operator
End Structure
Module M1
Sub Main()
Dim x As New S1?(New S1(42))
Dim y = x + x
Console.WriteLine(y.Value.x)
End Sub
End Module
</file>
</compilation>, expectedOutput:="84").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 80 (0x50)
.maxstack 2
.locals init (S1? V_0, //x
S1? V_1, //y
S1? V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: newobj "Sub S1..ctor(Integer)"
IL_0009: call "Sub S1?..ctor(S1)"
IL_000e: ldloca.s V_0
IL_0010: call "Function S1?.get_HasValue() As Boolean"
IL_0015: ldloca.s V_0
IL_0017: call "Function S1?.get_HasValue() As Boolean"
IL_001c: and
IL_001d: brtrue.s IL_002a
IL_001f: ldloca.s V_2
IL_0021: initobj "S1?"
IL_0027: ldloc.2
IL_0028: br.s IL_003d
IL_002a: ldloca.s V_0
IL_002c: call "Function S1?.GetValueOrDefault() As S1"
IL_0031: ldloca.s V_0
IL_0033: call "Function S1?.GetValueOrDefault() As S1"
IL_0038: call "Function S1.op_Addition(S1, S1) As S1?"
IL_003d: stloc.1
IL_003e: ldloca.s V_1
IL_0040: call "Function S1?.get_Value() As S1"
IL_0045: ldfld "S1.x As Integer"
IL_004a: call "Sub System.Console.WriteLine(Integer)"
IL_004f: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedUserConversionShortToInt()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Structure S1
Shared Widening Operator CType(x As Byte) As S1
Return New S1()
End Operator
End Structure
Sub Main()
Dim y As S1? = new Long?(42) ' === UDC
Console.WriteLine(y.HasValue)
End Sub
End Module
</file>
</compilation>, expectedOutput:="True").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (M1.S1? V_0) //y
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: call "Function M1.S1.op_Implicit(Byte) As M1.S1"
IL_0009: call "Sub M1.S1?..ctor(M1.S1)"
IL_000e: ldloca.s V_0
IL_0010: call "Function M1.S1?.get_HasValue() As Boolean"
IL_0015: call "Sub System.Console.WriteLine(Boolean)"
IL_001a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedUserConversionShortToIntA()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Structure S1
Shared Widening Operator CType(x As Byte) As S1
Return New S1()
End Operator
End Structure
Sub Main()
Dim y As S1? = x ' === UDC
Console.WriteLine(y.HasValue)
End Sub
Function x() As Long?
Console.Write("x")
Return New Long?(42)
End Function
End Module
</file>
</compilation>, expectedOutput:="xTrue").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (M1.S1? V_0, //y
Long? V_1,
Long? V_2,
M1.S1? V_3)
IL_0000: call "Function M1.x() As Long?"
IL_0005: dup
IL_0006: stloc.1
IL_0007: stloc.2
IL_0008: ldloca.s V_2
IL_000a: call "Function Long?.get_HasValue() As Boolean"
IL_000f: brtrue.s IL_001c
IL_0011: ldloca.s V_3
IL_0013: initobj "M1.S1?"
IL_0019: ldloc.3
IL_001a: br.s IL_002e
IL_001c: ldloca.s V_1
IL_001e: call "Function Long?.GetValueOrDefault() As Long"
IL_0023: conv.ovf.u1
IL_0024: call "Function M1.S1.op_Implicit(Byte) As M1.S1"
IL_0029: newobj "Sub M1.S1?..ctor(M1.S1)"
IL_002e: stloc.0
IL_002f: ldloca.s V_0
IL_0031: call "Function M1.S1?.get_HasValue() As Boolean"
IL_0036: call "Sub System.Console.WriteLine(Boolean)"
IL_003b: ret
}
]]>)
End Sub
<Fact(), WorkItem(544589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544589")>
Public Sub LiftedShortCircuitOperations()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim bF As Boolean? = False
Dim bT As Boolean? = True
Dim bN As Boolean? = Nothing
If bF OrElse bT AndAlso bN Then
Console.Write("True")
Else
Console.Write("False")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="False").
VerifyIL("M.Main",
<![CDATA[
{
// Code size 91 (0x5b)
.maxstack 2
.locals init (Boolean? V_0, //bF
Boolean? V_1, //bT
Boolean? V_2) //bN
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: call "Sub Boolean?..ctor(Boolean)"
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.1
IL_000b: call "Sub Boolean?..ctor(Boolean)"
IL_0010: ldloca.s V_2
IL_0012: initobj "Boolean?"
IL_0018: ldloca.s V_0
IL_001a: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001f: brtrue.s IL_0045
IL_0021: ldloca.s V_1
IL_0023: call "Function Boolean?.get_HasValue() As Boolean"
IL_0028: brfalse.s IL_0033
IL_002a: ldloca.s V_1
IL_002c: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0031: brfalse.s IL_0050
IL_0033: ldloca.s V_2
IL_0035: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_003a: brfalse.s IL_0050
IL_003c: ldloca.s V_1
IL_003e: call "Function Boolean?.get_HasValue() As Boolean"
IL_0043: brfalse.s IL_0050
IL_0045: ldstr "True"
IL_004a: call "Sub System.Console.Write(String)"
IL_004f: ret
IL_0050: ldstr "False"
IL_0055: call "Sub System.Console.Write(String)"
IL_005a: ret
}
]]>)
End Sub
<Fact(), WorkItem(545124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545124")>
Public Sub LogicalOperationsWithNullableEnum()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Enum EnumItems
Item1 = 1
Item2 = 2
Item3 = 4
Item4 = 8
End Enum
Module M
Sub Main()
Dim value1a As EnumItems? = 10
Dim value1b As EnumItems = EnumItems.Item3
Console.Write(Not value1a And value1b Or value1a Xor value1b)
End Sub
End Module
</file>
</compilation>, expectedOutput:="10").
VerifyIL("M.Main",
<![CDATA[
{
// Code size 169 (0xa9)
.maxstack 2
.locals init (EnumItems? V_0, //value1a
EnumItems V_1, //value1b
EnumItems? V_2,
EnumItems? V_3,
EnumItems? V_4,
EnumItems? V_5)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 10
IL_0004: call "Sub EnumItems?..ctor(EnumItems)"
IL_0009: ldc.i4.4
IL_000a: stloc.1
IL_000b: ldloca.s V_0
IL_000d: call "Function EnumItems?.get_HasValue() As Boolean"
IL_0012: brtrue.s IL_0017
IL_0014: ldloc.0
IL_0015: br.s IL_0024
IL_0017: ldloca.s V_0
IL_0019: call "Function EnumItems?.GetValueOrDefault() As EnumItems"
IL_001e: not
IL_001f: newobj "Sub EnumItems?..ctor(EnumItems)"
IL_0024: stloc.s V_4
IL_0026: ldloca.s V_4
IL_0028: call "Function EnumItems?.get_HasValue() As Boolean"
IL_002d: brtrue.s IL_003b
IL_002f: ldloca.s V_5
IL_0031: initobj "EnumItems?"
IL_0037: ldloc.s V_5
IL_0039: br.s IL_0049
IL_003b: ldloca.s V_4
IL_003d: call "Function EnumItems?.GetValueOrDefault() As EnumItems"
IL_0042: ldloc.1
IL_0043: and
IL_0044: newobj "Sub EnumItems?..ctor(EnumItems)"
IL_0049: stloc.3
IL_004a: ldloca.s V_3
IL_004c: call "Function EnumItems?.get_HasValue() As Boolean"
IL_0051: ldloca.s V_0
IL_0053: call "Function EnumItems?.get_HasValue() As Boolean"
IL_0058: and
IL_0059: brtrue.s IL_0067
IL_005b: ldloca.s V_4
IL_005d: initobj "EnumItems?"
IL_0063: ldloc.s V_4
IL_0065: br.s IL_007b
IL_0067: ldloca.s V_3
IL_0069: call "Function EnumItems?.GetValueOrDefault() As EnumItems"
IL_006e: ldloca.s V_0
IL_0070: call "Function EnumItems?.GetValueOrDefault() As EnumItems"
IL_0075: or
IL_0076: newobj "Sub EnumItems?..ctor(EnumItems)"
IL_007b: stloc.2
IL_007c: ldloca.s V_2
IL_007e: call "Function EnumItems?.get_HasValue() As Boolean"
IL_0083: brtrue.s IL_0090
IL_0085: ldloca.s V_3
IL_0087: initobj "EnumItems?"
IL_008d: ldloc.3
IL_008e: br.s IL_009e
IL_0090: ldloca.s V_2
IL_0092: call "Function EnumItems?.GetValueOrDefault() As EnumItems"
IL_0097: ldloc.1
IL_0098: xor
IL_0099: newobj "Sub EnumItems?..ctor(EnumItems)"
IL_009e: box "EnumItems?"
IL_00a3: call "Sub System.Console.Write(Object)"
IL_00a8: ret
}
]]>)
End Sub
<Fact(), WorkItem(545125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545125")>
Public Sub ArithmeticOperationsWithNullableType()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Friend Module M
Public Function goo_exception() As Integer
Console.Write("1st Called ")
Throw New ArgumentNullException()
End Function
Public Function goo_eval_check() As Integer?
Console.Write("2nd Called ")
goo_eval_check = 2
End Function
Sub Main()
Try
Dim r1 = goo_exception() \ goo_eval_check()
Catch ex As ArgumentNullException
End Try
End Sub
End Module
</file>
</compilation>, expectedOutput:="1st Called").
VerifyIL("M.Main",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 2
.locals init (Integer V_0,
Integer? V_1,
System.ArgumentNullException V_2) //ex
.try
{
IL_0000: call "Function M.goo_exception() As Integer"
IL_0005: stloc.0
IL_0006: call "Function M.goo_eval_check() As Integer?"
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call "Function Integer?.get_HasValue() As Boolean"
IL_0013: brfalse.s IL_0024
IL_0015: ldloc.0
IL_0016: ldloca.s V_1
IL_0018: call "Function Integer?.GetValueOrDefault() As Integer"
IL_001d: div
IL_001e: newobj "Sub Integer?..ctor(Integer)"
IL_0023: pop
IL_0024: leave.s IL_0034
}
catch System.ArgumentNullException
{
IL_0026: dup
IL_0027: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_002c: stloc.2
IL_002d: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0032: leave.s IL_0034
}
IL_0034: ret
}
]]>)
End Sub
<Fact(), WorkItem(545437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545437")>
Public Sub Regress13840()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim y As MyStruct? = Nothing
If (CType(CType(Nothing, MyStruct?), MyStruct?) = y) Then 'expect warning
System.Console.WriteLine("Equals")
End If
End Sub
Structure MyStruct
Shared Operator =(ByVal left As MyStruct, ByVal right As MyStruct) As Boolean
Return True
End Operator
Shared Operator <>(ByVal left As MyStruct, ByVal right As MyStruct) As Boolean
Return False
End Operator
End Structure
End Module
</file>
</compilation>, expectedOutput:="")
End Sub
#Region "Diagnostics"
<Fact(), WorkItem(544942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544942"), WorkItem(599013, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/599013")>
Public Sub BC30424ERR_ConstAsNonConstant_Nullable()
Dim source =
<compilation>
<file name="a.vb">
Structure S : End Structure
Enum E : Zero : End Enum
Class C
Sub M()
Const c1 As Boolean? = Nothing
Const c2 As ULong? = 12345
Const c3 As E? = E.Zero
Dim d = Sub()
Const c4 As S? = Nothing
End Sub
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source)
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ConstAsNonConstant, "Boolean?"),
Diagnostic(ERRID.ERR_ConstAsNonConstant, "ULong?"),
Diagnostic(ERRID.ERR_ConstAsNonConstant, "E?"),
Diagnostic(ERRID.ERR_ConstAsNonConstant, "S?"))
End Sub
<Fact()>
Public Sub BC30456ERR_NameNotMember2_Nullable()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Option Explicit Off
Imports System
Structure S
Public field As C
End Structure
Class C
Public field As S
Shared Widening Operator CType(p As C) As S
Console.Write("N")
Return p.field
End Operator
Shared Narrowing Operator CType(p As S) As C
Console.Write("W")
Return p.field
End Operator
End Class
Module Program
Sub Main(args As String())
Dim x As New S()
x.field = New C()
x.field.field = x
Dim y As C = x.field
Dim ns As S? = y
Console.Write(ns.field.field Is y) ' BC30456
End Sub
End Module
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source)
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotMember2, "ns.field").WithArguments("field", "S?"))
End Sub
<Fact(), WorkItem(544945, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544945")>
Public Sub BC42037And42038WRN_EqualToLiteralNothing_Nullable()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Shared Sub Main()
Dim x As SByte? = Nothing
Dim y As SByte? = 123
Dim r1 = x = Nothing ' Assert here
If Not (r1 AndAlso Nothing <> y) Then
Console.WriteLine("FAIL")
Else
Console.WriteLine("PASS")
End If
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="PASS").VerifyDiagnostics(
Diagnostic(ERRID.WRN_EqualToLiteralNothing, "x = Nothing"),
Diagnostic(ERRID.WRN_NotEqualToLiteralNothing, "Nothing <> y")
)
End Sub
<Fact(), WorkItem(545050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545050")>
Public Sub DoNotGiveBC32126ERR_AddressOfNullableMethod()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Program
Sub Main()
Dim x As Integer? = Nothing
Dim f1 As Func(Of String) = AddressOf x.ToString
f1()
Dim f2 As Func(Of Integer) = AddressOf x.GetHashCode
f2()
Dim f3 As Func(Of Object, Boolean) = AddressOf x.Equals
f3(Nothing)
Dim f4 As Func(Of Type) = AddressOf x.GetType
f4()
Dim f5 As Func(Of Integer, Integer?) = AddressOf Integer?.op_Implicit
f5(1)
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source).VerifyDiagnostics().VerifyIL("Program.Main", <![CDATA[
{
// Code size 124 (0x7c)
.maxstack 3
.locals init (Integer? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "Integer?"
IL_0008: ldloc.0
IL_0009: dup
IL_000a: box "Integer?"
IL_000f: dup
IL_0010: ldvirtftn "Function System.ValueType.ToString() As String"
IL_0016: newobj "Sub System.Func(Of String)..ctor(Object, System.IntPtr)"
IL_001b: callvirt "Function System.Func(Of String).Invoke() As String"
IL_0020: pop
IL_0021: dup
IL_0022: box "Integer?"
IL_0027: dup
IL_0028: ldvirtftn "Function System.ValueType.GetHashCode() As Integer"
IL_002e: newobj "Sub System.Func(Of Integer)..ctor(Object, System.IntPtr)"
IL_0033: callvirt "Function System.Func(Of Integer).Invoke() As Integer"
IL_0038: pop
IL_0039: dup
IL_003a: box "Integer?"
IL_003f: dup
IL_0040: ldvirtftn "Function System.ValueType.Equals(Object) As Boolean"
IL_0046: newobj "Sub System.Func(Of Object, Boolean)..ctor(Object, System.IntPtr)"
IL_004b: ldnull
IL_004c: callvirt "Function System.Func(Of Object, Boolean).Invoke(Object) As Boolean"
IL_0051: pop
IL_0052: box "Integer?"
IL_0057: ldftn "Function Object.GetType() As System.Type"
IL_005d: newobj "Sub System.Func(Of System.Type)..ctor(Object, System.IntPtr)"
IL_0062: callvirt "Function System.Func(Of System.Type).Invoke() As System.Type"
IL_0067: pop
IL_0068: ldnull
IL_0069: ldftn "Function Integer?.op_Implicit(Integer) As Integer?"
IL_006f: newobj "Sub System.Func(Of Integer, Integer?)..ctor(Object, System.IntPtr)"
IL_0074: ldc.i4.1
IL_0075: callvirt "Function System.Func(Of Integer, Integer?).Invoke(Integer) As Integer?"
IL_007a: pop
IL_007b: ret
}
]]>)
End Sub
<Fact(), WorkItem(545126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545126")>
Public Sub BC36629ERR_NullableTypeInferenceNotSupported()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class C
Public X? = 10
Public X1? = {10}
Public Property Z? = 10
Public Property Z1? = {10}
Sub Test()
Dim Y? = 10
Dim Y1? = {10}
End Sub
Sub Test1()
' Option Strict Off, Option Infer Off - Expected No errors
' Option Strict Off, Option Infer On - Expected BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
' Option Strict On, Option Infer On - Expected BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static U? = 10
' Option Strict Off, Option Infer Off - Expected No errors
' Option Strict Off, Option Infer On - Expected BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
' Option Strict On, Option Infer On - Expected BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static U1? = {10}
Static V?() = Nothing
Static V1?(1) = Nothing
End Sub
Sub Test2()
Const U? = 10
Dim x As Object = U
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off).WithOptionInfer(False))
AssertTheseDiagnostics(compilation,
<expected>
BC36629: Nullable type inference is not supported in this context.
Public X? = 10
~~
BC36629: Nullable type inference is not supported in this context.
Public X1? = {10}
~~~
BC30205: End of statement expected.
Public Property Z? = 10
~
BC30205: End of statement expected.
Public Property Z1? = {10}
~
BC36629: Nullable type inference is not supported in this context.
Dim Y? = 10
~~
BC36629: Nullable type inference is not supported in this context.
Dim Y1? = {10}
~~~
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
Static V1?(1) = Nothing
~~~~~~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off).WithOptionInfer(True))
AssertTheseDiagnostics(compilation,
<expected>
BC36629: Nullable type inference is not supported in this context.
Public X? = 10
~~
BC36629: Nullable type inference is not supported in this context.
Public X1? = {10}
~~~
BC30205: End of statement expected.
Public Property Z? = 10
~
BC30205: End of statement expected.
Public Property Z1? = {10}
~
BC36628: A nullable type cannot be inferred for variable 'Y1'.
Dim Y1? = {10}
~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static U? = 10
~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static U1? = {10}
~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static V?() = Nothing
~~~~
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
Static V1?(1) = Nothing
~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static V1?(1) = Nothing
~~~~~~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On).WithOptionInfer(False))
AssertTheseDiagnostics(compilation,
<expected>
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Public X? = 10
~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Public X1? = {10}
~~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Public Property Z? = 10
~
BC30205: End of statement expected.
Public Property Z? = 10
~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Public Property Z1? = {10}
~~
BC30205: End of statement expected.
Public Property Z1? = {10}
~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Dim Y? = 10
~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Dim Y1? = {10}
~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static U? = 10
~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static U1? = {10}
~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static V?() = Nothing
~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static V1?(1) = Nothing
~~
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
Static V1?(1) = Nothing
~~~~~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Const U? = 10
~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On).WithOptionInfer(True))
AssertTheseDiagnostics(compilation,
<expected>
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Public X? = 10
~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Public X1? = {10}
~~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Public Property Z? = 10
~
BC30205: End of statement expected.
Public Property Z? = 10
~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Public Property Z1? = {10}
~~
BC30205: End of statement expected.
Public Property Z1? = {10}
~
BC36628: A nullable type cannot be inferred for variable 'Y1'.
Dim Y1? = {10}
~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static U? = 10
~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static U? = 10
~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static U1? = {10}
~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static U1? = {10}
~~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static V?() = Nothing
~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static V?() = Nothing
~~~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static V1?(1) = Nothing
~~
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
Static V1?(1) = Nothing
~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static V1?(1) = Nothing
~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(545126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545126")>
Public Sub BC36629ERR_NullableTypeInferenceNotSupported_2()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class C
Public X%? = 10
Public X1%? = {10}
Public Property Z%? = 10
Public Property Z1%? = {10}
Sub Test()
Dim Y%? = 10
Dim Y1%? = {10}
End Sub
Sub Test1()
Static U%? = 10
Static U1%? = {10}
End Sub
Sub Test2()
Const V%? = 10
Dim x As Object = V
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off).WithOptionInfer(False))
AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Public X1%? = {10}
~~~~
BC30205: End of statement expected.
Public Property Z%? = 10
~
BC30205: End of statement expected.
Public Property Z1%? = {10}
~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Dim Y1%? = {10}
~~~~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Static U1%? = {10}
~~~~
BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.
Const V%? = 10
~~~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off).WithOptionInfer(True))
AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Public X1%? = {10}
~~~~
BC30205: End of statement expected.
Public Property Z%? = 10
~
BC30205: End of statement expected.
Public Property Z1%? = {10}
~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Dim Y1%? = {10}
~~~~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Static U1%? = {10}
~~~~
BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.
Const V%? = 10
~~~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On).WithOptionInfer(False))
AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Public X1%? = {10}
~~~~
BC30205: End of statement expected.
Public Property Z%? = 10
~
BC30205: End of statement expected.
Public Property Z1%? = {10}
~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Dim Y1%? = {10}
~~~~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Static U1%? = {10}
~~~~
BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.
Const V%? = 10
~~~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On).WithOptionInfer(True))
AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Public X1%? = {10}
~~~~
BC30205: End of statement expected.
Public Property Z%? = 10
~
BC30205: End of statement expected.
Public Property Z1%? = {10}
~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Dim Y1%? = {10}
~~~~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Static U1%? = {10}
~~~~
BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.
Const V%? = 10
~~~
</expected>)
End Sub
#End Region
#Region "For Loop"
<Fact()>
Public Sub LiftedForTo()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Public Class MyClass1
Public Shared Sub Main()
Dim l As UInteger? = 1
For x As UInteger? = 1 To 10 Step l
Console.Write(x)
If x >= 5 Then
x = Nothing
End If
Next
End Sub
End Class
</file>
</compilation>, expectedOutput:="12345").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 282 (0x11a)
.maxstack 3
.locals init (UInteger? V_0, //l
UInteger? V_1,
UInteger? V_2,
Boolean V_3,
UInteger? V_4, //x
Long? V_5,
Long? V_6,
Boolean? V_7,
UInteger? V_8)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub UInteger?..ctor(UInteger)"
IL_0008: ldc.i4.1
IL_0009: newobj "Sub UInteger?..ctor(UInteger)"
IL_000e: ldloca.s V_1
IL_0010: ldc.i4.s 10
IL_0012: call "Sub UInteger?..ctor(UInteger)"
IL_0017: ldloc.0
IL_0018: stloc.2
IL_0019: ldloca.s V_2
IL_001b: call "Function UInteger?.get_HasValue() As Boolean"
IL_0020: brfalse.s IL_0031
IL_0022: ldloca.s V_2
IL_0024: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_0029: ldc.i4.0
IL_002a: clt.un
IL_002c: ldc.i4.0
IL_002d: ceq
IL_002f: br.s IL_0032
IL_0031: ldc.i4.0
IL_0032: stloc.3
IL_0033: stloc.s V_4
IL_0035: br IL_00d8
IL_003a: ldloc.s V_4
IL_003c: box "UInteger?"
IL_0041: call "Sub System.Console.Write(Object)"
IL_0046: ldloca.s V_4
IL_0048: call "Function UInteger?.get_HasValue() As Boolean"
IL_004d: brtrue.s IL_005b
IL_004f: ldloca.s V_6
IL_0051: initobj "Long?"
IL_0057: ldloc.s V_6
IL_0059: br.s IL_0068
IL_005b: ldloca.s V_4
IL_005d: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_0062: conv.u8
IL_0063: newobj "Sub Long?..ctor(Long)"
IL_0068: stloc.s V_5
IL_006a: ldloca.s V_5
IL_006c: call "Function Long?.get_HasValue() As Boolean"
IL_0071: brtrue.s IL_007f
IL_0073: ldloca.s V_7
IL_0075: initobj "Boolean?"
IL_007b: ldloc.s V_7
IL_007d: br.s IL_0092
IL_007f: ldloca.s V_5
IL_0081: call "Function Long?.GetValueOrDefault() As Long"
IL_0086: ldc.i4.5
IL_0087: conv.i8
IL_0088: clt
IL_008a: ldc.i4.0
IL_008b: ceq
IL_008d: newobj "Sub Boolean?..ctor(Boolean)"
IL_0092: stloc.s V_7
IL_0094: ldloca.s V_7
IL_0096: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_009b: brfalse.s IL_00a5
IL_009d: ldloca.s V_4
IL_009f: initobj "UInteger?"
IL_00a5: ldloca.s V_2
IL_00a7: call "Function UInteger?.get_HasValue() As Boolean"
IL_00ac: ldloca.s V_4
IL_00ae: call "Function UInteger?.get_HasValue() As Boolean"
IL_00b3: and
IL_00b4: brtrue.s IL_00c2
IL_00b6: ldloca.s V_8
IL_00b8: initobj "UInteger?"
IL_00be: ldloc.s V_8
IL_00c0: br.s IL_00d6
IL_00c2: ldloca.s V_4
IL_00c4: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_00c9: ldloca.s V_2
IL_00cb: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_00d0: add.ovf.un
IL_00d1: newobj "Sub UInteger?..ctor(UInteger)"
IL_00d6: stloc.s V_4
IL_00d8: ldloca.s V_1
IL_00da: call "Function UInteger?.get_HasValue() As Boolean"
IL_00df: ldloca.s V_4
IL_00e1: call "Function UInteger?.get_HasValue() As Boolean"
IL_00e6: and
IL_00e7: brfalse.s IL_0119
IL_00e9: ldloc.3
IL_00ea: brtrue.s IL_0101
IL_00ec: ldloca.s V_4
IL_00ee: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_00f3: ldloca.s V_1
IL_00f5: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_00fa: clt.un
IL_00fc: ldc.i4.0
IL_00fd: ceq
IL_00ff: br.s IL_0114
IL_0101: ldloca.s V_4
IL_0103: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_0108: ldloca.s V_1
IL_010a: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_010f: cgt.un
IL_0111: ldc.i4.0
IL_0112: ceq
IL_0114: brtrue IL_003a
IL_0119: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedForToDefaultStep()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Public Class MyClass1
Public Shared Sub Main()
Dim x As Integer? = 1
For x = 1 To 10
Console.Write(x)
If x >= 5 Then
x = Nothing
End If
Next
End Sub
End Class
</file>
</compilation>, expectedOutput:="12345").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 248 (0xf8)
.maxstack 3
.locals init (Integer? V_0, //x
Integer? V_1,
Integer? V_2,
Boolean V_3,
Integer? V_4,
Boolean? V_5)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldc.i4.1
IL_0009: newobj "Sub Integer?..ctor(Integer)"
IL_000e: ldloca.s V_1
IL_0010: ldc.i4.s 10
IL_0012: call "Sub Integer?..ctor(Integer)"
IL_0017: ldloca.s V_2
IL_0019: ldc.i4.1
IL_001a: call "Sub Integer?..ctor(Integer)"
IL_001f: ldloca.s V_2
IL_0021: call "Function Integer?.get_HasValue() As Boolean"
IL_0026: brfalse.s IL_0037
IL_0028: ldloca.s V_2
IL_002a: call "Function Integer?.GetValueOrDefault() As Integer"
IL_002f: ldc.i4.0
IL_0030: clt
IL_0032: ldc.i4.0
IL_0033: ceq
IL_0035: br.s IL_0038
IL_0037: ldc.i4.0
IL_0038: stloc.3
IL_0039: stloc.0
IL_003a: br.s IL_00b6
IL_003c: ldloc.0
IL_003d: box "Integer?"
IL_0042: call "Sub System.Console.Write(Object)"
IL_0047: ldloc.0
IL_0048: stloc.s V_4
IL_004a: ldloca.s V_4
IL_004c: call "Function Integer?.get_HasValue() As Boolean"
IL_0051: brtrue.s IL_005f
IL_0053: ldloca.s V_5
IL_0055: initobj "Boolean?"
IL_005b: ldloc.s V_5
IL_005d: br.s IL_0071
IL_005f: ldloca.s V_4
IL_0061: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0066: ldc.i4.5
IL_0067: clt
IL_0069: ldc.i4.0
IL_006a: ceq
IL_006c: newobj "Sub Boolean?..ctor(Boolean)"
IL_0071: stloc.s V_5
IL_0073: ldloca.s V_5
IL_0075: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_007a: brfalse.s IL_0084
IL_007c: ldloca.s V_0
IL_007e: initobj "Integer?"
IL_0084: ldloca.s V_2
IL_0086: call "Function Integer?.get_HasValue() As Boolean"
IL_008b: ldloca.s V_0
IL_008d: call "Function Integer?.get_HasValue() As Boolean"
IL_0092: and
IL_0093: brtrue.s IL_00a1
IL_0095: ldloca.s V_4
IL_0097: initobj "Integer?"
IL_009d: ldloc.s V_4
IL_009f: br.s IL_00b5
IL_00a1: ldloca.s V_0
IL_00a3: call "Function Integer?.GetValueOrDefault() As Integer"
IL_00a8: ldloca.s V_2
IL_00aa: call "Function Integer?.GetValueOrDefault() As Integer"
IL_00af: add.ovf
IL_00b0: newobj "Sub Integer?..ctor(Integer)"
IL_00b5: stloc.0
IL_00b6: ldloca.s V_1
IL_00b8: call "Function Integer?.get_HasValue() As Boolean"
IL_00bd: ldloca.s V_0
IL_00bf: call "Function Integer?.get_HasValue() As Boolean"
IL_00c4: and
IL_00c5: brfalse.s IL_00f7
IL_00c7: ldloc.3
IL_00c8: brtrue.s IL_00df
IL_00ca: ldloca.s V_0
IL_00cc: call "Function Integer?.GetValueOrDefault() As Integer"
IL_00d1: ldloca.s V_1
IL_00d3: call "Function Integer?.GetValueOrDefault() As Integer"
IL_00d8: clt
IL_00da: ldc.i4.0
IL_00db: ceq
IL_00dd: br.s IL_00f2
IL_00df: ldloca.s V_0
IL_00e1: call "Function Integer?.GetValueOrDefault() As Integer"
IL_00e6: ldloca.s V_1
IL_00e8: call "Function Integer?.GetValueOrDefault() As Integer"
IL_00ed: cgt
IL_00ef: ldc.i4.0
IL_00f0: ceq
IL_00f2: brtrue IL_003c
IL_00f7: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedForToDecimalSideeffectsNullStep()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Public Class MyClass1
Public Shared Sub Main()
For x As Decimal? = Init() To Limit() Step [Step]()
Console.Write(x)
Next
End Sub
Private Shared Function Init() As Integer
Console.WriteLine("init")
Return 9
End Function
Private Shared Function Limit() As Integer
Console.WriteLine("limit")
Return 1
End Function
Private Shared Function [Step]() As Decimal?
Console.WriteLine("step")
Return nothing
End Function
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[init
limit
step
9]]>).
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 220 (0xdc)
.maxstack 3
.locals init (Decimal? V_0,
Decimal? V_1,
Boolean V_2,
Decimal? V_3, //x
Decimal? V_4)
IL_0000: call "Function MyClass1.Init() As Integer"
IL_0005: newobj "Sub Decimal..ctor(Integer)"
IL_000a: newobj "Sub Decimal?..ctor(Decimal)"
IL_000f: ldloca.s V_0
IL_0011: call "Function MyClass1.Limit() As Integer"
IL_0016: newobj "Sub Decimal..ctor(Integer)"
IL_001b: call "Sub Decimal?..ctor(Decimal)"
IL_0020: call "Function MyClass1.Step() As Decimal?"
IL_0025: stloc.1
IL_0026: ldloca.s V_1
IL_0028: call "Function Decimal?.get_HasValue() As Boolean"
IL_002d: brfalse.s IL_0048
IL_002f: ldloca.s V_1
IL_0031: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_0036: ldsfld "Decimal.Zero As Decimal"
IL_003b: call "Function Decimal.Compare(Decimal, Decimal) As Integer"
IL_0040: ldc.i4.0
IL_0041: clt
IL_0043: ldc.i4.0
IL_0044: ceq
IL_0046: br.s IL_0049
IL_0048: ldc.i4.0
IL_0049: stloc.2
IL_004a: stloc.3
IL_004b: br.s IL_008e
IL_004d: ldloc.3
IL_004e: box "Decimal?"
IL_0053: call "Sub System.Console.Write(Object)"
IL_0058: ldloca.s V_1
IL_005a: call "Function Decimal?.get_HasValue() As Boolean"
IL_005f: ldloca.s V_3
IL_0061: call "Function Decimal?.get_HasValue() As Boolean"
IL_0066: and
IL_0067: brtrue.s IL_0075
IL_0069: ldloca.s V_4
IL_006b: initobj "Decimal?"
IL_0071: ldloc.s V_4
IL_0073: br.s IL_008d
IL_0075: ldloca.s V_3
IL_0077: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_007c: ldloca.s V_1
IL_007e: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_0083: call "Function Decimal.Add(Decimal, Decimal) As Decimal"
IL_0088: newobj "Sub Decimal?..ctor(Decimal)"
IL_008d: stloc.3
IL_008e: ldloca.s V_0
IL_0090: call "Function Decimal?.get_HasValue() As Boolean"
IL_0095: ldloca.s V_3
IL_0097: call "Function Decimal?.get_HasValue() As Boolean"
IL_009c: and
IL_009d: brfalse.s IL_00db
IL_009f: ldloc.2
IL_00a0: brtrue.s IL_00bd
IL_00a2: ldloca.s V_3
IL_00a4: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_00a9: ldloca.s V_0
IL_00ab: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_00b0: call "Function Decimal.Compare(Decimal, Decimal) As Integer"
IL_00b5: ldc.i4.0
IL_00b6: clt
IL_00b8: ldc.i4.0
IL_00b9: ceq
IL_00bb: br.s IL_00d6
IL_00bd: ldloca.s V_3
IL_00bf: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_00c4: ldloca.s V_0
IL_00c6: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_00cb: call "Function Decimal.Compare(Decimal, Decimal) As Integer"
IL_00d0: ldc.i4.0
IL_00d1: cgt
IL_00d3: ldc.i4.0
IL_00d4: ceq
IL_00d6: brtrue IL_004d
IL_00db: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedForCombinationsOneToThree()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Public Class MyClass1
Public Shared Sub Main()
' Step 1
For x As Integer? = One() To Three() Step One()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = One() To Null() Step One()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Null() To Three() Step One()
Console.Write(x)
Next
Console.WriteLine()
' Step -1
For x As Integer? = One() To Three() Step MOne()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = One() To Null() Step MOne()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Null() To Three() Step MOne()
Console.Write(x)
Next
Console.WriteLine()
' Step Null
For x As Integer? = One() To Three() Step Null()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = One() To Null() Step Null()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Null() To Three() Step Null()
Console.Write(x)
Next
Console.WriteLine()
End Sub
Private Shared Function One() As Integer?
Console.Write("one ")
Return 1
End Function
Private Shared Function MOne() As Integer?
Console.Write("-one ")
Return -1
End Function
Private Shared Function Three() As Integer?
Console.Write("three ")
Return 3
End Function
Private Shared Function Null() As Integer?
Console.Write("null ")
Return Nothing
End Function
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[one three one 123
one null one
null three one
one three -one
one null -one
null three -one
one three null
one null null
null three null
]]>)
End Sub
<Fact()>
Public Sub LiftedForCombinationsTreeToOne()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Public Class MyClass1
Public Shared Sub Main()
' Step 1
For x As Integer? = Three() To One() Step One()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Three() To Null() Step One()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Null() To One() Step One()
Console.Write(x)
Next
Console.WriteLine()
' Step -1
For x As Integer? = Three() To One() Step MOne()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Three() To Null() Step MOne()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Null() To One() Step MOne()
Console.Write(x)
Next
Console.WriteLine()
' Step Null
For x As Integer? = Three() To One() Step Null()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Three() To Null() Step Null()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Null() To One() Step Null()
Console.Write(x)
Next
Console.WriteLine()
End Sub
Private Shared Function One() As Integer?
Console.Write("one ")
Return 1
End Function
Private Shared Function MOne() As Integer?
Console.Write("-one ")
Return -1
End Function
Private Shared Function Three() As Integer?
Console.Write("three ")
Return 3
End Function
Private Shared Function Null() As Integer?
Console.Write("null ")
Return Nothing
End Function
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[three one one
three null one
null one one
three one -one 321
three null -one
null one -one
three one null 3
three null null
null one null
]]>)
End Sub
<Fact()>
Public Sub LiftedStringConversion()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class MyClass1
Shared Sub Main()
Dim x As SByte? = 42
Dim y As String = x
x = y
Console.Write(x)
End Sub
End Class
</file>
</compilation>, expectedOutput:="42").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (SByte? V_0, //x
String V_1) //y
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: call "Sub SByte?..ctor(SByte)"
IL_0009: ldloca.s V_0
IL_000b: call "Function SByte?.get_Value() As SByte"
IL_0010: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String"
IL_0015: stloc.1
IL_0016: ldloca.s V_0
IL_0018: ldloc.1
IL_0019: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToSByte(String) As SByte"
IL_001e: call "Sub SByte?..ctor(SByte)"
IL_0023: ldloc.0
IL_0024: box "SByte?"
IL_0029: call "Sub System.Console.Write(Object)"
IL_002e: ret
}
]]>)
End Sub
#End Region
<Fact()>
Public Sub Regress14397()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Const a As Integer = If(True, 1, 2)
Sub Main()
Dim s As String
Dim inull As Integer? = Nothing
s = " :catenation right to integer?(null): " & inull
Console.WriteLine(s)
s = inull & " :catenation left to integer?(null): "
Console.WriteLine(s)
s = inull & inull
Console.WriteLine(" :catenation Integer?(null) & Integer?(null): " & s)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[:catenation right to integer?(null):
:catenation left to integer?(null):
:catenation Integer?(null) & Integer?(null): ]]>)
End Sub
''' <summary>
''' same as Dev11
''' implicit: int --> int?
''' explicit: int? --> int
''' </summary>
''' <remarks></remarks>
<Fact, WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")>
Public Sub Op_ExplicitImplicitOnNullable()
CompileAndVerify(
<compilation>
<file name="nullableOp.vb">
Imports System
Module MyClass1
Sub Main()
Dim x = (Integer?).op_Implicit(1)
x = (Integer?).op_Explicit(2)
Dim y = (Nullable(Of Integer)).op_Implicit(1)
y = (Nullable(Of Integer)).op_Explicit(2)
End Sub
End Module
</file>
</compilation>).
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 49 (0x31)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call "Function Integer?.op_Implicit(Integer) As Integer?"
IL_0006: pop
IL_0007: ldc.i4.2
IL_0008: newobj "Sub Integer?..ctor(Integer)"
IL_000d: call "Function Integer?.op_Explicit(Integer?) As Integer"
IL_0012: newobj "Sub Integer?..ctor(Integer)"
IL_0017: pop
IL_0018: ldc.i4.1
IL_0019: call "Function Integer?.op_Implicit(Integer) As Integer?"
IL_001e: pop
IL_001f: ldc.i4.2
IL_0020: newobj "Sub Integer?..ctor(Integer)"
IL_0025: call "Function Integer?.op_Explicit(Integer?) As Integer"
IL_002a: newobj "Sub Integer?..ctor(Integer)"
IL_002f: pop
IL_0030: ret
}
]]>)
End Sub
<Fact()>
Public Sub DecimalConst()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Public Class NullableTest
Shared NULL As Decimal? = Nothing
Public Shared Sub EqualEqual()
Test.Eval(CType(1D, Decimal?) is Nothing, False)
Test.Eval(CType(1D, Decimal?) = NULL, False)
Test.Eval(CType(0, Decimal?) = NULL, False)
End Sub
End Class
Public Class Test
Public Shared Sub Eval(obj1 As Object, obj2 As Object)
End Sub
End Class
</file>
</compilation>).
VerifyIL("NullableTest.EqualEqual",
<![CDATA[
{
// Code size 152 (0x98)
.maxstack 2
.locals init (Decimal? V_0,
Boolean? V_1)
IL_0000: ldc.i4.0
IL_0001: box "Boolean"
IL_0006: ldc.i4.0
IL_0007: box "Boolean"
IL_000c: call "Sub Test.Eval(Object, Object)"
IL_0011: ldsfld "NullableTest.NULL As Decimal?"
IL_0016: stloc.0
IL_0017: ldloca.s V_0
IL_0019: call "Function Decimal?.get_HasValue() As Boolean"
IL_001e: brtrue.s IL_002b
IL_0020: ldloca.s V_1
IL_0022: initobj "Boolean?"
IL_0028: ldloc.1
IL_0029: br.s IL_0044
IL_002b: ldsfld "Decimal.One As Decimal"
IL_0030: ldloca.s V_0
IL_0032: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_0037: call "Function Decimal.Compare(Decimal, Decimal) As Integer"
IL_003c: ldc.i4.0
IL_003d: ceq
IL_003f: newobj "Sub Boolean?..ctor(Boolean)"
IL_0044: box "Boolean?"
IL_0049: ldc.i4.0
IL_004a: box "Boolean"
IL_004f: call "Sub Test.Eval(Object, Object)"
IL_0054: ldsfld "NullableTest.NULL As Decimal?"
IL_0059: stloc.0
IL_005a: ldloca.s V_0
IL_005c: call "Function Decimal?.get_HasValue() As Boolean"
IL_0061: brtrue.s IL_006e
IL_0063: ldloca.s V_1
IL_0065: initobj "Boolean?"
IL_006b: ldloc.1
IL_006c: br.s IL_0087
IL_006e: ldsfld "Decimal.Zero As Decimal"
IL_0073: ldloca.s V_0
IL_0075: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_007a: call "Function Decimal.Compare(Decimal, Decimal) As Integer"
IL_007f: ldc.i4.0
IL_0080: ceq
IL_0082: newobj "Sub Boolean?..ctor(Boolean)"
IL_0087: box "Boolean?"
IL_008c: ldc.i4.0
IL_008d: box "Boolean"
IL_0092: call "Sub Test.Eval(Object, Object)"
IL_0097: ret
}
]]>)
End Sub
<Fact>
Public Sub LiftedToIntPtrConversion()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module M
Sub Main()
Console.WriteLine(CType(M(Nothing), IntPtr?))
Console.WriteLine(CType(M(42), IntPtr?))
End Sub
Function M(p as Integer?) As Integer?
Return p
End Function
End Module
</file>
</compilation>
Dim expectedOutput = "" + vbCrLf + "42"
CompileAndVerify(source, expectedOutput)
End Sub
<Fact()>
Public Sub SubtractFromZero()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim a As Integer? = 1
Dim b As Integer? = 0 - a
Console.WriteLine(String.Format("a: {0}, b: {1}", a, b))
Dim a1 As Integer? = 1
Dim b1 As Integer? = a - 0
Console.WriteLine(String.Format("a1: {0}, b1: {1}", a1, b1))
End Sub
End Module
</file>
</compilation>, expectedOutput:="a: 1, b: -1
a1: 1, b1: 1").
VerifyIL("Module1.Main",
<![CDATA[
{
// Code size 144 (0x90)
.maxstack 3
.locals init (Integer? V_0, //a
Integer? V_1, //b
Integer? V_2, //a1
Integer? V_3, //b1
Integer? V_4,
Integer? V_5)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Integer?.get_HasValue() As Boolean"
IL_000f: brtrue.s IL_001d
IL_0011: ldloca.s V_4
IL_0013: initobj "Integer?"
IL_0019: ldloc.s V_4
IL_001b: br.s IL_002b
IL_001d: ldc.i4.0
IL_001e: ldloca.s V_0
IL_0020: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0025: sub.ovf
IL_0026: newobj "Sub Integer?..ctor(Integer)"
IL_002b: stloc.1
IL_002c: ldstr "a: {0}, b: {1}"
IL_0031: ldloc.0
IL_0032: box "Integer?"
IL_0037: ldloc.1
IL_0038: box "Integer?"
IL_003d: call "Function String.Format(String, Object, Object) As String"
IL_0042: call "Sub System.Console.WriteLine(String)"
IL_0047: ldloca.s V_2
IL_0049: ldc.i4.1
IL_004a: call "Sub Integer?..ctor(Integer)"
IL_004f: ldloc.0
IL_0050: stloc.s V_4
IL_0052: ldloca.s V_4
IL_0054: call "Function Integer?.get_HasValue() As Boolean"
IL_0059: brtrue.s IL_0067
IL_005b: ldloca.s V_5
IL_005d: initobj "Integer?"
IL_0063: ldloc.s V_5
IL_0065: br.s IL_0073
IL_0067: ldloca.s V_4
IL_0069: call "Function Integer?.GetValueOrDefault() As Integer"
IL_006e: newobj "Sub Integer?..ctor(Integer)"
IL_0073: stloc.3
IL_0074: ldstr "a1: {0}, b1: {1}"
IL_0079: ldloc.2
IL_007a: box "Integer?"
IL_007f: ldloc.3
IL_0080: box "Integer?"
IL_0085: call "Function String.Format(String, Object, Object) As String"
IL_008a: call "Sub System.Console.WriteLine(String)"
IL_008f: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_01()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Class C
Public shared Sub Main()
Test1(Nothing, new C())
Test2(Nothing, new C())
Test3(Nothing, new C())
Test4(Nothing, new C())
Test5(Nothing, new C())
End Sub
Public Shared Sub Test1(x as C, y As C)
System.Console.WriteLine("->Test1")
If GetBool3(x) = True AndAlso y.GetBool2()
System.Console.WriteLine("In If")
End If
System.Console.WriteLine("<-Test1")
End Sub
Public Shared Sub Test2(x as C, y As C)
System.Console.WriteLine("->Test2")
If x?.GetBool1() = True AndAlso y.GetBool2()
System.Console.WriteLine("In If")
End If
System.Console.WriteLine("<-Test2")
End Sub
Public Shared Sub Test3(x as C, y As C)
System.Console.WriteLine("->Test3")
Dim z = GetBool3(x) = True AndAlso y.GetBool2()
If z
System.Console.WriteLine("In If")
End If
System.Console.WriteLine("<-Test3")
End Sub
Public Shared Sub Test4(x as C, y As C)
System.Console.WriteLine("->Test4")
Dim z = x?.GetBool1() = True AndAlso y.GetBool2()
If z
System.Console.WriteLine("In If")
End If
System.Console.WriteLine("<-Test4")
End Sub
Public Shared Sub Test5(x as C, y As C)
System.Console.WriteLine("->Test5")
If GetBool3(x) AndAlso y.GetBool2()
System.Console.WriteLine("In If")
End If
System.Console.WriteLine("<-Test5")
End Sub
Function GetBool1() As Boolean
Return True
End Function
Function GetBool2() As Boolean
System.Console.WriteLine("GetBool2")
Return True
End Function
Shared Function GetBool3(x as C) As Boolean?
if x Is Nothing
Return Nothing
End If
Return True
End Function
End Class
]]></file>
</compilation>, expectedOutput:=
<![CDATA[
->Test1
GetBool2
<-Test1
->Test2
GetBool2
<-Test2
->Test3
GetBool2
<-Test3
->Test4
GetBool2
<-Test4
->Test5
GetBool2
<-Test5
]]>
)
End Sub
<ConditionalFact(GetType(DesktopClrOnly))>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_02()
CompileAndVerify(
<compilation>
<file name="a.vb"><) As C
Return Me
End Function
Function Where(filter As System.Linq.Expressions.Expression(Of System.Func(Of C, Boolean))) As C
System.Console.WriteLine(filter.ToString())
Return Me
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Class
]]></file>
</compilation>, expectedOutput:=
<![CDATA[
y => (((y.GetBool3() == Convert(True)) AndAlso Convert(y.GetBool2())) ?? False)
y => (((y.GetBool3() == Convert(True)) OrElse Convert(y.GetBool2())) ?? False)
]]>
)
End Sub
<ConditionalFact(GetType(DesktopClrOnly))>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_03()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
Dim x As System.Linq.Expressions.Expression(Of System.Func(Of Boolean))
x = Function() If(GetBool3() = True AndAlso GetBool2(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() = True OrElse GetBool2(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(New Boolean?() AndAlso New Boolean?(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(New Boolean?() OrElse New Boolean?(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(New Boolean?() AndAlso GetBool2(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(New Boolean?() OrElse GetBool2(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(New Boolean?() AndAlso GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(New Boolean?() OrElse GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool2() AndAlso New Boolean?(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool2() OrElse New Boolean?(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() AndAlso New Boolean?(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() OrElse New Boolean?(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() AndAlso GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() OrElse GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() OrElse GetBool3() OrElse GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If((GetBool3() OrElse GetBool3()) OrElse GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() OrElse (GetBool3() OrElse GetBool3()), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If((GetBool3() OrElse GetBool3()) OrElse (GetBool3() OrElse GetBool3()), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If((GetBool3() OrElse GetBool3()) OrElse GetBool3() OrElse GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() AndAlso GetBool2() AndAlso GetBool2(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If((GetBool3() AndAlso GetBool2()) AndAlso GetBool2(), True, False)
System.Console.WriteLine(x.ToString())
End Sub
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>, expectedOutput:=
<![CDATA[
() => IIF((((GetBool3() == Convert(True)) AndAlso Convert(GetBool2())) ?? False), True, False)
() => IIF((((GetBool3() == Convert(True)) ?? False) OrElse GetBool2()), True, False)
() => IIF(((new Nullable`1() AndAlso new Nullable`1()) ?? False), True, False)
() => IIF(((new Nullable`1() ?? False) OrElse (new Nullable`1() ?? False)), True, False)
() => IIF(((new Nullable`1() AndAlso Convert(GetBool2())) ?? False), True, False)
() => IIF(((new Nullable`1() ?? False) OrElse GetBool2()), True, False)
() => IIF(((new Nullable`1() AndAlso GetBool3()) ?? False), True, False)
() => IIF(((new Nullable`1() ?? False) OrElse (GetBool3() ?? False)), True, False)
() => IIF((GetBool2() AndAlso (new Nullable`1() ?? False)), True, False)
() => IIF((GetBool2() OrElse (new Nullable`1() ?? False)), True, False)
() => IIF(((GetBool3() AndAlso new Nullable`1()) ?? False), True, False)
() => IIF(((GetBool3() ?? False) OrElse (new Nullable`1() ?? False)), True, False)
() => IIF(((GetBool3() AndAlso GetBool3()) ?? False), True, False)
() => IIF(((GetBool3() ?? False) OrElse (GetBool3() ?? False)), True, False)
() => IIF((((GetBool3() ?? False) OrElse (GetBool3() ?? False)) OrElse (GetBool3() ?? False)), True, False)
() => IIF((((GetBool3() ?? False) OrElse (GetBool3() ?? False)) OrElse (GetBool3() ?? False)), True, False)
() => IIF(((GetBool3() ?? False) OrElse ((GetBool3() ?? False) OrElse (GetBool3() ?? False))), True, False)
() => IIF((((GetBool3() ?? False) OrElse (GetBool3() ?? False)) OrElse ((GetBool3() ?? False) OrElse (GetBool3() ?? False))), True, False)
() => IIF(((((GetBool3() ?? False) OrElse (GetBool3() ?? False)) OrElse (GetBool3() ?? False)) OrElse (GetBool3() ?? False)), True, False)
() => IIF((((GetBool3() AndAlso Convert(GetBool2())) AndAlso Convert(GetBool2())) ?? False), True, False)
() => IIF((((GetBool3() AndAlso Convert(GetBool2())) AndAlso Convert(GetBool2())) ?? False), True, False)
]]>
)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_04()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() AndAlso GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 48 (0x30)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.get_HasValue() As Boolean"
IL_000d: brfalse.s IL_0018
IL_000f: ldloca.s V_1
IL_0011: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0016: brfalse.s IL_002c
IL_0018: call "Function Module1.GetBool2() As Boolean"
IL_001d: brfalse.s IL_002c
IL_001f: ldloca.s V_1
IL_0021: call "Function Boolean?.get_HasValue() As Boolean"
IL_0026: brfalse.s IL_002c
IL_0028: ldc.i4.2
IL_0029: stloc.0
IL_002a: br.s IL_002e
IL_002c: ldc.i4.3
IL_002d: stloc.0
IL_002e: ldloc.0
IL_002f: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_05()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() OrElse GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 30 (0x1e)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_0016
IL_000f: call "Function Module1.GetBool2() As Boolean"
IL_0014: brfalse.s IL_001a
IL_0016: ldc.i4.2
IL_0017: stloc.0
IL_0018: br.s IL_001c
IL_001a: ldc.i4.3
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_06()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool2() AndAlso GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 30 (0x1e)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: brfalse.s IL_001a
IL_0007: call "Function Module1.GetBool3() As Boolean?"
IL_000c: stloc.1
IL_000d: ldloca.s V_1
IL_000f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0014: brfalse.s IL_001a
IL_0016: ldc.i4.2
IL_0017: stloc.0
IL_0018: br.s IL_001c
IL_001a: ldc.i4.3
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_07()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool2() OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 30 (0x1e)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: brtrue.s IL_0016
IL_0007: call "Function Module1.GetBool3() As Boolean?"
IL_000c: stloc.1
IL_000d: ldloca.s V_1
IL_000f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0014: brfalse.s IL_001a
IL_0016: ldc.i4.2
IL_0017: stloc.0
IL_0018: br.s IL_001c
IL_001a: ldc.i4.3
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_08()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If New Boolean?() AndAlso GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: pop
IL_0006: ldc.i4.3
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_09()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If New Boolean?() OrElse GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 15 (0xf)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: brfalse.s IL_000b
IL_0007: ldc.i4.2
IL_0008: stloc.0
IL_0009: br.s IL_000d
IL_000b: ldc.i4.3
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_10()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If New Boolean?() AndAlso GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: pop
IL_0006: ldc.i4.3
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_11()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If New Boolean?() OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 23 (0x17)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brfalse.s IL_0013
IL_000f: ldc.i4.2
IL_0010: stloc.0
IL_0011: br.s IL_0015
IL_0013: ldc.i4.3
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_12()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() AndAlso New Boolean?() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: pop
IL_0006: ldc.i4.3
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_13()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() OrElse New Boolean?() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 23 (0x17)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brfalse.s IL_0013
IL_000f: ldc.i4.2
IL_0010: stloc.0
IL_0011: br.s IL_0015
IL_0013: ldc.i4.3
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_14()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool2() AndAlso New Boolean?() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: pop
IL_0006: ldc.i4.3
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_15()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool2() OrElse New Boolean?() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 15 (0xf)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: brfalse.s IL_000b
IL_0007: ldc.i4.2
IL_0008: stloc.0
IL_0009: br.s IL_000d
IL_000b: ldc.i4.3
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_16()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If New Boolean?() AndAlso New Boolean?() Then
Return 2
Else
Return 3
End If
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 4 (0x4)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_17()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If New Boolean?() OrElse New Boolean?() Then
Return 2
Else
Return 3
End If
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 4 (0x4)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_18()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() AndAlso GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 56 (0x38)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1,
Boolean? V_2)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.get_HasValue() As Boolean"
IL_000d: brfalse.s IL_0018
IL_000f: ldloca.s V_1
IL_0011: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0016: brfalse.s IL_0034
IL_0018: call "Function Module1.GetBool3() As Boolean?"
IL_001d: stloc.2
IL_001e: ldloca.s V_2
IL_0020: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0025: brfalse.s IL_0034
IL_0027: ldloca.s V_1
IL_0029: call "Function Boolean?.get_HasValue() As Boolean"
IL_002e: brfalse.s IL_0034
IL_0030: ldc.i4.2
IL_0031: stloc.0
IL_0032: br.s IL_0036
IL_0034: ldc.i4.3
IL_0035: stloc.0
IL_0036: ldloc.0
IL_0037: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_19()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 38 (0x26)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_001e
IL_000f: call "Function Module1.GetBool3() As Boolean?"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brfalse.s IL_0022
IL_001e: ldc.i4.2
IL_001f: stloc.0
IL_0020: br.s IL_0024
IL_0022: ldc.i4.3
IL_0023: stloc.0
IL_0024: ldloc.0
IL_0025: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_20()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool2() AndAlso (GetBool2() AndAlso GetBool3()) Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 37 (0x25)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: brfalse.s IL_0021
IL_0007: call "Function Module1.GetBool2() As Boolean"
IL_000c: brfalse.s IL_0021
IL_000e: call "Function Module1.GetBool3() As Boolean?"
IL_0013: stloc.1
IL_0014: ldloca.s V_1
IL_0016: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001b: brfalse.s IL_0021
IL_001d: ldc.i4.2
IL_001e: stloc.0
IL_001f: br.s IL_0023
IL_0021: ldc.i4.3
IL_0022: stloc.0
IL_0023: ldloc.0
IL_0024: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_21()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() OrElse (GetBool3() OrElse GetBool3()) Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_002d
IL_000f: call "Function Module1.GetBool3() As Boolean?"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brtrue.s IL_002d
IL_001e: call "Function Module1.GetBool3() As Boolean?"
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_002b: brfalse.s IL_0031
IL_002d: ldc.i4.2
IL_002e: stloc.0
IL_002f: br.s IL_0033
IL_0031: ldc.i4.3
IL_0032: stloc.0
IL_0033: ldloc.0
IL_0034: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_22()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetBool3() OrElse GetBool3()) AndAlso GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 134 (0x86)
.maxstack 2
.locals init (Integer V_0, //Test1
Boolean? V_1,
Boolean? V_2,
Boolean? V_3,
Boolean? V_4)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: dup
IL_0006: stloc.2
IL_0007: stloc.s V_4
IL_0009: ldloca.s V_4
IL_000b: call "Function Boolean?.get_HasValue() As Boolean"
IL_0010: brfalse.s IL_001b
IL_0012: ldloca.s V_2
IL_0014: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0019: brtrue.s IL_004d
IL_001b: call "Function Module1.GetBool3() As Boolean?"
IL_0020: dup
IL_0021: stloc.3
IL_0022: stloc.s V_4
IL_0024: ldloca.s V_4
IL_0026: call "Function Boolean?.get_HasValue() As Boolean"
IL_002b: brtrue.s IL_0039
IL_002d: ldloca.s V_4
IL_002f: initobj "Boolean?"
IL_0035: ldloc.s V_4
IL_0037: br.s IL_0053
IL_0039: ldloca.s V_3
IL_003b: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0040: brtrue.s IL_0045
IL_0042: ldloc.2
IL_0043: br.s IL_0053
IL_0045: ldc.i4.1
IL_0046: newobj "Sub Boolean?..ctor(Boolean)"
IL_004b: br.s IL_0053
IL_004d: ldc.i4.1
IL_004e: newobj "Sub Boolean?..ctor(Boolean)"
IL_0053: stloc.1
IL_0054: ldloca.s V_1
IL_0056: call "Function Boolean?.get_HasValue() As Boolean"
IL_005b: brfalse.s IL_0066
IL_005d: ldloca.s V_1
IL_005f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0064: brfalse.s IL_0082
IL_0066: call "Function Module1.GetBool3() As Boolean?"
IL_006b: stloc.3
IL_006c: ldloca.s V_3
IL_006e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0073: brfalse.s IL_0082
IL_0075: ldloca.s V_1
IL_0077: call "Function Boolean?.get_HasValue() As Boolean"
IL_007c: brfalse.s IL_0082
IL_007e: ldc.i4.2
IL_007f: stloc.0
IL_0080: br.s IL_0084
IL_0082: ldc.i4.3
IL_0083: stloc.0
IL_0084: ldloc.0
IL_0085: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_23()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetBool3() OrElse GetBool3()) AndAlso GetBool3() OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 149 (0x95)
.maxstack 2
.locals init (Integer V_0, //Test1
Boolean? V_1,
Boolean? V_2,
Boolean? V_3,
Boolean? V_4)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: dup
IL_0006: stloc.2
IL_0007: stloc.s V_4
IL_0009: ldloca.s V_4
IL_000b: call "Function Boolean?.get_HasValue() As Boolean"
IL_0010: brfalse.s IL_001b
IL_0012: ldloca.s V_2
IL_0014: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0019: brtrue.s IL_004d
IL_001b: call "Function Module1.GetBool3() As Boolean?"
IL_0020: dup
IL_0021: stloc.3
IL_0022: stloc.s V_4
IL_0024: ldloca.s V_4
IL_0026: call "Function Boolean?.get_HasValue() As Boolean"
IL_002b: brtrue.s IL_0039
IL_002d: ldloca.s V_4
IL_002f: initobj "Boolean?"
IL_0035: ldloc.s V_4
IL_0037: br.s IL_0053
IL_0039: ldloca.s V_3
IL_003b: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0040: brtrue.s IL_0045
IL_0042: ldloc.2
IL_0043: br.s IL_0053
IL_0045: ldc.i4.1
IL_0046: newobj "Sub Boolean?..ctor(Boolean)"
IL_004b: br.s IL_0053
IL_004d: ldc.i4.1
IL_004e: newobj "Sub Boolean?..ctor(Boolean)"
IL_0053: stloc.1
IL_0054: ldloca.s V_1
IL_0056: call "Function Boolean?.get_HasValue() As Boolean"
IL_005b: brfalse.s IL_0066
IL_005d: ldloca.s V_1
IL_005f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0064: brfalse.s IL_007e
IL_0066: call "Function Module1.GetBool3() As Boolean?"
IL_006b: stloc.3
IL_006c: ldloca.s V_3
IL_006e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0073: brfalse.s IL_007e
IL_0075: ldloca.s V_1
IL_0077: call "Function Boolean?.get_HasValue() As Boolean"
IL_007c: brtrue.s IL_008d
IL_007e: call "Function Module1.GetBool3() As Boolean?"
IL_0083: stloc.1
IL_0084: ldloca.s V_1
IL_0086: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_008b: brfalse.s IL_0091
IL_008d: ldc.i4.2
IL_008e: stloc.0
IL_008f: br.s IL_0093
IL_0091: ldc.i4.3
IL_0092: stloc.0
IL_0093: ldloc.0
IL_0094: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_24()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetBool3() OrElse GetBool3()) OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_002d
IL_000f: call "Function Module1.GetBool3() As Boolean?"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brtrue.s IL_002d
IL_001e: call "Function Module1.GetBool3() As Boolean?"
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_002b: brfalse.s IL_0031
IL_002d: ldc.i4.2
IL_002e: stloc.0
IL_002f: br.s IL_0033
IL_0031: ldc.i4.3
IL_0032: stloc.0
IL_0033: ldloc.0
IL_0034: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_25()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() OrElse GetBool3() OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_002d
IL_000f: call "Function Module1.GetBool3() As Boolean?"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brtrue.s IL_002d
IL_001e: call "Function Module1.GetBool3() As Boolean?"
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_002b: brfalse.s IL_0031
IL_002d: ldc.i4.2
IL_002e: stloc.0
IL_002f: br.s IL_0033
IL_0031: ldc.i4.3
IL_0032: stloc.0
IL_0033: ldloc.0
IL_0034: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_26()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetBool3() AndAlso GetBool2()) AndAlso GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 93 (0x5d)
.maxstack 2
.locals init (Integer V_0, //Test1
Boolean? V_1,
Boolean? V_2,
Boolean? V_3)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: dup
IL_0006: stloc.2
IL_0007: stloc.3
IL_0008: ldloca.s V_3
IL_000a: call "Function Boolean?.get_HasValue() As Boolean"
IL_000f: brfalse.s IL_001a
IL_0011: ldloca.s V_2
IL_0013: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0018: brfalse.s IL_002c
IL_001a: call "Function Module1.GetBool2() As Boolean"
IL_001f: brtrue.s IL_0029
IL_0021: ldc.i4.0
IL_0022: newobj "Sub Boolean?..ctor(Boolean)"
IL_0027: br.s IL_0032
IL_0029: ldloc.2
IL_002a: br.s IL_0032
IL_002c: ldc.i4.0
IL_002d: newobj "Sub Boolean?..ctor(Boolean)"
IL_0032: stloc.1
IL_0033: ldloca.s V_1
IL_0035: call "Function Boolean?.get_HasValue() As Boolean"
IL_003a: brfalse.s IL_0045
IL_003c: ldloca.s V_1
IL_003e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0043: brfalse.s IL_0059
IL_0045: call "Function Module1.GetBool2() As Boolean"
IL_004a: brfalse.s IL_0059
IL_004c: ldloca.s V_1
IL_004e: call "Function Boolean?.get_HasValue() As Boolean"
IL_0053: brfalse.s IL_0059
IL_0055: ldc.i4.2
IL_0056: stloc.0
IL_0057: br.s IL_005b
IL_0059: ldc.i4.3
IL_005a: stloc.0
IL_005b: ldloc.0
IL_005c: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_27()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() AndAlso GetBool2() AndAlso GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 93 (0x5d)
.maxstack 2
.locals init (Integer V_0, //Test1
Boolean? V_1,
Boolean? V_2,
Boolean? V_3)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: dup
IL_0006: stloc.2
IL_0007: stloc.3
IL_0008: ldloca.s V_3
IL_000a: call "Function Boolean?.get_HasValue() As Boolean"
IL_000f: brfalse.s IL_001a
IL_0011: ldloca.s V_2
IL_0013: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0018: brfalse.s IL_002c
IL_001a: call "Function Module1.GetBool2() As Boolean"
IL_001f: brtrue.s IL_0029
IL_0021: ldc.i4.0
IL_0022: newobj "Sub Boolean?..ctor(Boolean)"
IL_0027: br.s IL_0032
IL_0029: ldloc.2
IL_002a: br.s IL_0032
IL_002c: ldc.i4.0
IL_002d: newobj "Sub Boolean?..ctor(Boolean)"
IL_0032: stloc.1
IL_0033: ldloca.s V_1
IL_0035: call "Function Boolean?.get_HasValue() As Boolean"
IL_003a: brfalse.s IL_0045
IL_003c: ldloca.s V_1
IL_003e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0043: brfalse.s IL_0059
IL_0045: call "Function Module1.GetBool2() As Boolean"
IL_004a: brfalse.s IL_0059
IL_004c: ldloca.s V_1
IL_004e: call "Function Boolean?.get_HasValue() As Boolean"
IL_0053: brfalse.s IL_0059
IL_0055: ldc.i4.2
IL_0056: stloc.0
IL_0057: br.s IL_005b
IL_0059: ldc.i4.3
IL_005a: stloc.0
IL_005b: ldloc.0
IL_005c: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_28()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetBool3() OrElse GetBool3()) OrElse (GetBool3() OrElse GetBool3()) Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 68 (0x44)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_003c
IL_000f: call "Function Module1.GetBool3() As Boolean?"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brtrue.s IL_003c
IL_001e: call "Function Module1.GetBool3() As Boolean?"
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_002b: brtrue.s IL_003c
IL_002d: call "Function Module1.GetBool3() As Boolean?"
IL_0032: stloc.1
IL_0033: ldloca.s V_1
IL_0035: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_003a: brfalse.s IL_0040
IL_003c: ldc.i4.2
IL_003d: stloc.0
IL_003e: br.s IL_0042
IL_0040: ldc.i4.3
IL_0041: stloc.0
IL_0042: ldloc.0
IL_0043: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_29()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetBool3() OrElse GetBool3()) OrElse GetBool3() OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 68 (0x44)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_003c
IL_000f: call "Function Module1.GetBool3() As Boolean?"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brtrue.s IL_003c
IL_001e: call "Function Module1.GetBool3() As Boolean?"
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_002b: brtrue.s IL_003c
IL_002d: call "Function Module1.GetBool3() As Boolean?"
IL_0032: stloc.1
IL_0033: ldloca.s V_1
IL_0035: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_003a: brfalse.s IL_0040
IL_003c: ldc.i4.2
IL_003d: stloc.0
IL_003e: br.s IL_0042
IL_0040: ldc.i4.3
IL_0041: stloc.0
IL_0042: ldloc.0
IL_0043: ret
}
]]>)
End Sub
<Fact>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_30()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System.Text
Module Test
Dim builder As New StringBuilder()
Sub Main()
Test()
System.Console.WriteLine("Done")
End Sub
Sub Test()
Dim condition = placeholder
Dim s1 As String = GetResultString(If(condition, " => True", " => False"))
Dim d As System.Linq.Expressions.Expression(Of System.Func(Of String)) = Function() If(placeholder, " => True", " => False")
Dim s2 = GetResultString(d.Compile()())
Dim s3 = GetResultString(If(placeholder, " => True", " => False"))
Verify(d, s1, s2, s3)
End Sub
Private Function GetResultString(result As String) As String
builder.Append(result)
Dim s1 = builder.ToString()
builder.Clear()
Return s1
End Function
Private Sub Verify(d As System.Linq.Expressions.Expression(Of System.Func(Of String)), s1 As String, s2 As String, s3 As String)
If s1 <> s3 Then
System.Console.WriteLine("1 => ")
System.Console.WriteLine(d.ToString())
System.Console.WriteLine(s1)
System.Console.WriteLine(s3)
End If
If s2 <> s3 Then
System.Console.WriteLine("2 => ")
System.Console.WriteLine(d.ToString())
System.Console.WriteLine(s2)
System.Console.WriteLine(s3)
End If
End Sub
Function BooleanTrue(i As Integer) As Boolean
builder.AppendFormat(" BooleanTrue({0})", i)
Return True
End Function
Function BooleanFalse(i As Integer) As Boolean
builder.AppendFormat(" BooleanFalse({0})", i)
Return False
End Function
Function NullableTrue(i As Integer) As Boolean?
builder.AppendFormat(" NullableTrue({0})", i)
Return True
End Function
Function NullableFalse(i As Integer) As Boolean?
builder.AppendFormat(" NullableFalse({0})", i)
Return False
End Function
Function NullableNull(i As Integer) As Boolean?
builder.AppendFormat(" NullableNull({0})", i)
Return Nothing
End Function
End Module
]]></file>
</compilation>
Dim compilation1 = CreateCompilation(source, options:=TestOptions.ReleaseExe)
Dim tree1 = compilation1.SyntaxTrees.Single()
Dim placeholders = tree1.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "placeholder").ToArray()
Assert.Equal(3, placeholders.Length)
Dim nameInInvocation = tree1.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "Test").Single()
Dim invocation = nameInInvocation.Ancestors().OfType(Of ExpressionStatementSyntax)().Single()
Dim testMethod = tree1.GetRoot().DescendantNodes().OfType(Of MethodBlockSyntax)().Where(Function(block) block.SubOrFunctionStatement.Identifier.ValueText = "Test").Single()
Assert.Equal("Test()", invocation.ToString())
Dim enumerator = BooleanExpression_30_Helpers.BuildConditions(2, 2).GetEnumerator()
Const batchSize As Integer = 250
Dim newBlocks = ArrayBuilder(Of MethodBlockSyntax).GetInstance(batchSize)
While enumerator.MoveNext
newBlocks.Clear()
Do
Dim replacement = enumerator.Current
Dim newBlock = testMethod.ReplaceNodes(placeholders, Function(n1, n2) replacement)
newBlock = newBlock.ReplaceToken(newBlock.SubOrFunctionStatement.Identifier, SyntaxFactory.Identifier("Test" + (newBlocks.Count + 1).ToString()))
newBlocks.Add(newBlock)
Loop While newBlocks.Count < batchSize AndAlso enumerator.MoveNext()
Dim newRoot = tree1.GetRoot().ReplaceNode(invocation, Enumerable.Range(1, newBlocks.Count).
Select(Function(i) invocation.ReplaceToken(nameInInvocation.Identifier,
SyntaxFactory.Identifier("Test" + i.ToString()))))
Dim oldBlock = newRoot.DescendantNodes().OfType(Of MethodBlockSyntax)().Where(Function(block) block.SubOrFunctionStatement.Identifier.ValueText = "Test").Single()
newRoot = newRoot.ReplaceNode(oldBlock, newBlocks)
Dim tree2 = newRoot.SyntaxTree
Dim compilation2 = compilation1.ReplaceSyntaxTree(tree1, tree2)
CompileAndVerify(compilation2, expectedOutput:="Done")
End While
newBlocks.Free()
End Sub
Private Class BooleanExpression_30_Helpers
Class TreeNode
Public Left As TreeNode
Public Right As TreeNode
End Class
Public Shared Iterator Function BuildConditions(fromOperators As Integer, toOperators As Integer) As IEnumerable(Of ExpressionSyntax)
For operatorCount = fromOperators To toOperators
For Each shape In Shapes(operatorCount)
For Each operators In OperatorSets(operatorCount)
For Each operands In OperandSets(operatorCount + 1)
Yield BuildCondition(shape, operators, operands)
Next
Next
Next
Next
End Function
Public Shared Function BuildCondition(shape As TreeNode, operators As ImmutableList(Of SyntaxKind), operands As ImmutableList(Of ExpressionSyntax)) As ExpressionSyntax
Dim result = BuildConditionWorker(shape, operators, operands)
Assert.Empty(operators)
Assert.Empty(operands)
Return result
End Function
Private Shared Function BuildConditionWorker(shape As TreeNode, ByRef operators As ImmutableList(Of SyntaxKind), ByRef operands As ImmutableList(Of ExpressionSyntax)) As ExpressionSyntax
If shape Is Nothing Then
Dim result = operands(0)
operands = operands.RemoveAt(0)
Return result
End If
Dim left = BuildConditionWorker(shape.Left, operators, operands)
Dim opKind = operators(0)
operators = operators.RemoveAt(0)
Dim right = BuildConditionWorker(shape.Right, operators, operands)
Return SyntaxFactory.BinaryExpression(
If(opKind = SyntaxKind.OrElseKeyword, SyntaxKind.OrElseExpression, SyntaxKind.AndAlsoExpression),
left, SyntaxFactory.Token(opKind), right)
End Function
''' <summary>
''' Enumerate all possible shapes of binary trees with given amount of nodes in it.
''' </summary>
''' <param name="count"></param>
''' <returns></returns>
Public Shared Iterator Function Shapes(count As Integer) As IEnumerable(Of TreeNode)
Select Case (count)
Case 0
Yield Nothing
Case 1
Yield New TreeNode()
Case Else
For i = 0 To count - 1
For Each leftTree In Shapes(count - 1 - i)
For Each rightTree In Shapes(i)
Yield New TreeNode() With {.Left = leftTree, .Right = rightTree}
Next
Next
Next
End Select
End Function
Shared Iterator Function OperatorSets(count As Integer) As IEnumerable(Of ImmutableList(Of SyntaxKind))
Select Case (count)
Case 0
Yield ImmutableList(Of SyntaxKind).Empty
Case Else
For Each s In OperatorSets(count - 1)
Yield s.Add(SyntaxKind.AndAlsoKeyword)
Yield s.Add(SyntaxKind.OrElseKeyword)
Next
End Select
End Function
Shared Iterator Function OperandSets(count As Integer) As IEnumerable(Of ImmutableList(Of ExpressionSyntax))
Select Case (count)
Case 0
Yield ImmutableList(Of ExpressionSyntax).Empty
Case Else
For Each s In OperandSets(count - 1)
' New Boolean?()
Yield s.Add(SyntaxFactory.ObjectCreationExpression(SyntaxFactory.NullableType(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BooleanKeyword)))))
For Each name In {"BooleanTrue", "BooleanFalse", "NullableTrue", "NullableFalse", "NullableNull"}
Yield s.Add(SyntaxFactory.InvocationExpression(
SyntaxFactory.IdentifierName(name),
SyntaxFactory.ArgumentList(
SyntaxFactory.SeparatedList(Of ArgumentSyntax)(
New ArgumentSyntax() {SyntaxFactory.SimpleArgument(
SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression,
SyntaxFactory.IntegerLiteralToken(count.ToString(),
LiteralBase.Decimal,
TypeCharacter.None,
CType(count, ULong))))}))))
Next
Next
End Select
End Function
End Class
<Fact()>
Public Sub BooleanExpression_31()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetC()?.F Then
Return 2
Else
Return 3
End If
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetC() As C"
IL_0005: dup
IL_0006: brtrue.s IL_000c
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: br.s IL_0011
IL_000c: ldfld "C.F As Boolean"
IL_0011: brfalse.s IL_0017
IL_0013: ldc.i4.2
IL_0014: stloc.0
IL_0015: br.s IL_0019
IL_0017: ldc.i4.3
IL_0018: stloc.0
IL_0019: ldloc.0
IL_001a: ret
}
]]>)
End Sub
<Fact()>
Public Sub BooleanExpression_32()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool1() AndAlso GetC()?.F Then
Return 2
Else
Return 3
End If
End Function
Function GetBool1() As Boolean
Return Nothing
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 34 (0x22)
.maxstack 2
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool1() As Boolean"
IL_0005: brfalse.s IL_001e
IL_0007: call "Function Module1.GetC() As C"
IL_000c: dup
IL_000d: brtrue.s IL_0013
IL_000f: pop
IL_0010: ldc.i4.0
IL_0011: br.s IL_0018
IL_0013: ldfld "C.F As Boolean"
IL_0018: brfalse.s IL_001e
IL_001a: ldc.i4.2
IL_001b: stloc.0
IL_001c: br.s IL_0020
IL_001e: ldc.i4.3
IL_001f: stloc.0
IL_0020: ldloc.0
IL_0021: ret
}
]]>)
End Sub
<Fact()>
Public Sub BooleanExpression_33()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetC()?.F OrElse GetBool1() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool1() As Boolean
Return Nothing
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 34 (0x22)
.maxstack 2
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetC() As C"
IL_0005: dup
IL_0006: brtrue.s IL_000c
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: br.s IL_0011
IL_000c: ldfld "C.F As Boolean"
IL_0011: brtrue.s IL_001a
IL_0013: call "Function Module1.GetBool1() As Boolean"
IL_0018: brfalse.s IL_001e
IL_001a: ldc.i4.2
IL_001b: stloc.0
IL_001c: br.s IL_0020
IL_001e: ldc.i4.3
IL_001f: stloc.0
IL_0020: ldloc.0
IL_0021: ret
}
]]>)
End Sub
<Fact()>
Public Sub BooleanExpression_34()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool1() AndAlso GetC()?.F OrElse GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool1() As Boolean
Return Nothing
End Function
Function GetBool2() As Boolean
Return Nothing
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 41 (0x29)
.maxstack 2
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool1() As Boolean"
IL_0005: brfalse.s IL_001a
IL_0007: call "Function Module1.GetC() As C"
IL_000c: dup
IL_000d: brtrue.s IL_0013
IL_000f: pop
IL_0010: ldc.i4.0
IL_0011: br.s IL_0018
IL_0013: ldfld "C.F As Boolean"
IL_0018: brtrue.s IL_0021
IL_001a: call "Function Module1.GetBool2() As Boolean"
IL_001f: brfalse.s IL_0025
IL_0021: ldc.i4.2
IL_0022: stloc.0
IL_0023: br.s IL_0027
IL_0025: ldc.i4.3
IL_0026: stloc.0
IL_0027: ldloc.0
IL_0028: ret
}
]]>)
End Sub
<Fact()>
Public Sub BooleanExpression_35()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetNullable() AndAlso GetC()?.F Then
Return 2
Else
Return 3
End If
End Function
Function GetNullable() As Boolean?
Return Nothing
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetNullable() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.get_HasValue() As Boolean"
IL_000d: brfalse.s IL_0018
IL_000f: ldloca.s V_1
IL_0011: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0016: brfalse.s IL_0038
IL_0018: call "Function Module1.GetC() As C"
IL_001d: dup
IL_001e: brtrue.s IL_0024
IL_0020: pop
IL_0021: ldc.i4.0
IL_0022: br.s IL_0029
IL_0024: ldfld "C.F As Boolean"
IL_0029: brfalse.s IL_0038
IL_002b: ldloca.s V_1
IL_002d: call "Function Boolean?.get_HasValue() As Boolean"
IL_0032: brfalse.s IL_0038
IL_0034: ldc.i4.2
IL_0035: stloc.0
IL_0036: br.s IL_003a
IL_0038: ldc.i4.3
IL_0039: stloc.0
IL_003a: ldloc.0
IL_003b: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38306, "https://github.com/dotnet/roslyn/issues/38306")>
Public Sub BooleanExpression_36()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetC()?.F).GetValueOrDefault() AndAlso GetBool1() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool1() As Boolean
Return Nothing
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 55 (0x37)
.maxstack 2
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetC() As C"
IL_0005: dup
IL_0006: brtrue.s IL_0014
IL_0008: pop
IL_0009: ldloca.s V_1
IL_000b: initobj "Boolean?"
IL_0011: ldloc.1
IL_0012: br.s IL_001e
IL_0014: ldfld "C.F As Boolean"
IL_0019: newobj "Sub Boolean?..ctor(Boolean)"
IL_001e: stloc.1
IL_001f: ldloca.s V_1
IL_0021: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0026: brfalse.s IL_0033
IL_0028: call "Function Module1.GetBool1() As Boolean"
IL_002d: brfalse.s IL_0033
IL_002f: ldc.i4.2
IL_0030: stloc.0
IL_0031: br.s IL_0035
IL_0033: ldc.i4.3
IL_0034: stloc.0
IL_0035: ldloc.0
IL_0036: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38306, "https://github.com/dotnet/roslyn/issues/38306")>
Public Sub BooleanExpression_37()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If If(GetC()?.F, False) AndAlso GetBool1() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool1() As Boolean
Return Nothing
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 34 (0x22)
.maxstack 2
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetC() As C"
IL_0005: dup
IL_0006: brtrue.s IL_000c
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: br.s IL_0011
IL_000c: ldfld "C.F As Boolean"
IL_0011: brfalse.s IL_001e
IL_0013: call "Function Module1.GetBool1() As Boolean"
IL_0018: brfalse.s IL_001e
IL_001a: ldc.i4.2
IL_001b: stloc.0
IL_001c: br.s IL_0020
IL_001e: ldc.i4.3
IL_001f: stloc.0
IL_0020: ldloc.0
IL_0021: ret
}
]]>)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports System.Collections.Immutable
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenNullable
Inherits BasicTestBase
<Fact(), WorkItem(544947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544947")>
Public Sub LiftedIntrinsicNegationLocal()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As New Integer?(1)
Dim y = -x
Console.Write("y1={0} ", y)
x = Nothing
y = -x
Console.Write("y2={0} ", y)
y = -New Long?()
Console.Write("y3={0} ", y)
End Sub
End Module
</file>
</compilation>, expectedOutput:="y1=-1 y2= y3=").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 127 (0x7f)
.maxstack 2
.locals init (Integer? V_0, //x
Integer? V_1) //y
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Integer?.get_HasValue() As Boolean"
IL_000f: brtrue.s IL_0014
IL_0011: ldloc.0
IL_0012: br.s IL_0022
IL_0014: ldc.i4.0
IL_0015: ldloca.s V_0
IL_0017: call "Function Integer?.GetValueOrDefault() As Integer"
IL_001c: sub.ovf
IL_001d: newobj "Sub Integer?..ctor(Integer)"
IL_0022: stloc.1
IL_0023: ldstr "y1={0} "
IL_0028: ldloc.1
IL_0029: box "Integer?"
IL_002e: call "Sub System.Console.Write(String, Object)"
IL_0033: ldloca.s V_0
IL_0035: initobj "Integer?"
IL_003b: ldloca.s V_0
IL_003d: call "Function Integer?.get_HasValue() As Boolean"
IL_0042: brtrue.s IL_0047
IL_0044: ldloc.0
IL_0045: br.s IL_0055
IL_0047: ldc.i4.0
IL_0048: ldloca.s V_0
IL_004a: call "Function Integer?.GetValueOrDefault() As Integer"
IL_004f: sub.ovf
IL_0050: newobj "Sub Integer?..ctor(Integer)"
IL_0055: stloc.1
IL_0056: ldstr "y2={0} "
IL_005b: ldloc.1
IL_005c: box "Integer?"
IL_0061: call "Sub System.Console.Write(String, Object)"
IL_0066: ldloca.s V_1
IL_0068: initobj "Integer?"
IL_006e: ldstr "y3={0} "
IL_0073: ldloc.1
IL_0074: box "Integer?"
IL_0079: call "Sub System.Console.Write(String, Object)"
IL_007e: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedIntrinsicNegationField()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Dim x As New Integer?(1)
Sub Main(args As String())
Dim y = -x
Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>, expectedOutput:="-1").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 43 (0x2b)
.maxstack 2
.locals init (Integer? V_0)
IL_0000: ldsfld "MyClass1.x As Integer?"
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call "Function Integer?.get_HasValue() As Boolean"
IL_000d: brtrue.s IL_0012
IL_000f: ldloc.0
IL_0010: br.s IL_0020
IL_0012: ldc.i4.0
IL_0013: ldloca.s V_0
IL_0015: call "Function Integer?.GetValueOrDefault() As Integer"
IL_001a: sub.ovf
IL_001b: newobj "Sub Integer?..ctor(Integer)"
IL_0020: box "Integer?"
IL_0025: call "Sub System.Console.WriteLine(Object)"
IL_002a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedIntrinsicNegationNull()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim y = ---CType(Nothing, Int32?)
Console.WriteLine(y.HasValue)
End Sub
End Module
</file>
</compilation>, expectedOutput:="False").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 21 (0x15)
.maxstack 1
.locals init (Integer? V_0) //y
IL_0000: ldloca.s V_0
IL_0002: initobj "Integer?"
IL_0008: ldloca.s V_0
IL_000a: call "Function Integer?.get_HasValue() As Boolean"
IL_000f: call "Sub System.Console.WriteLine(Boolean)"
IL_0014: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedIntrinsicNegationNotNull()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim y = ---CType(42, Int32?)
Console.WriteLine(y.HasValue)
End Sub
End Module
</file>
</compilation>, expectedOutput:="True").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 28 (0x1c)
.maxstack 5
.locals init (Integer? V_0) //y
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldc.i4.s 42
IL_0007: sub.ovf
IL_0008: sub.ovf
IL_0009: sub.ovf
IL_000a: call "Sub Integer?..ctor(Integer)"
IL_000f: ldloca.s V_0
IL_0011: call "Function Integer?.get_HasValue() As Boolean"
IL_0016: call "Sub System.Console.WriteLine(Boolean)"
IL_001b: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedIsTrueLiteral()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
If Not Not Not (CType(False, Boolean?)) Then
Console.Write("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr "hi"
IL_0005: call "Sub System.Console.Write(String)"
IL_000a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedIsTrueLocal()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x as boolean? = false
If Not Not Not x Then
Console.Write("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 112 (0x70)
.maxstack 2
.locals init (Boolean? V_0, //x
Boolean? V_1,
Boolean? V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: call "Sub Boolean?..ctor(Boolean)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Boolean?.get_HasValue() As Boolean"
IL_000f: brtrue.s IL_0014
IL_0011: ldloc.0
IL_0012: br.s IL_0023
IL_0014: ldloca.s V_0
IL_0016: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001b: ldc.i4.0
IL_001c: ceq
IL_001e: newobj "Sub Boolean?..ctor(Boolean)"
IL_0023: stloc.2
IL_0024: ldloca.s V_2
IL_0026: call "Function Boolean?.get_HasValue() As Boolean"
IL_002b: brtrue.s IL_0030
IL_002d: ldloc.2
IL_002e: br.s IL_003f
IL_0030: ldloca.s V_2
IL_0032: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0037: ldc.i4.0
IL_0038: ceq
IL_003a: newobj "Sub Boolean?..ctor(Boolean)"
IL_003f: stloc.1
IL_0040: ldloca.s V_1
IL_0042: call "Function Boolean?.get_HasValue() As Boolean"
IL_0047: brtrue.s IL_004c
IL_0049: ldloc.1
IL_004a: br.s IL_005b
IL_004c: ldloca.s V_1
IL_004e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0053: ldc.i4.0
IL_0054: ceq
IL_0056: newobj "Sub Boolean?..ctor(Boolean)"
IL_005b: stloc.1
IL_005c: ldloca.s V_1
IL_005e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0063: brfalse.s IL_006f
IL_0065: ldstr "hi"
IL_006a: call "Sub System.Console.Write(String)"
IL_006f: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryPlus()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Integer? = 2
Dim y As Integer? = 4
If x + x = y Then
Console.Write("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 137 (0x89)
.maxstack 2
.locals init (Integer? V_0, //x
Integer? V_1, //y
Integer? V_2,
Integer? V_3,
Boolean? V_4)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.2
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.4
IL_000b: call "Sub Integer?..ctor(Integer)"
IL_0010: ldloca.s V_0
IL_0012: call "Function Integer?.get_HasValue() As Boolean"
IL_0017: ldloca.s V_0
IL_0019: call "Function Integer?.get_HasValue() As Boolean"
IL_001e: and
IL_001f: brtrue.s IL_002c
IL_0021: ldloca.s V_3
IL_0023: initobj "Integer?"
IL_0029: ldloc.3
IL_002a: br.s IL_0040
IL_002c: ldloca.s V_0
IL_002e: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0033: ldloca.s V_0
IL_0035: call "Function Integer?.GetValueOrDefault() As Integer"
IL_003a: add.ovf
IL_003b: newobj "Sub Integer?..ctor(Integer)"
IL_0040: stloc.2
IL_0041: ldloca.s V_2
IL_0043: call "Function Integer?.get_HasValue() As Boolean"
IL_0048: ldloca.s V_1
IL_004a: call "Function Integer?.get_HasValue() As Boolean"
IL_004f: and
IL_0050: brtrue.s IL_005e
IL_0052: ldloca.s V_4
IL_0054: initobj "Boolean?"
IL_005a: ldloc.s V_4
IL_005c: br.s IL_0073
IL_005e: ldloca.s V_2
IL_0060: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0065: ldloca.s V_1
IL_0067: call "Function Integer?.GetValueOrDefault() As Integer"
IL_006c: ceq
IL_006e: newobj "Sub Boolean?..ctor(Boolean)"
IL_0073: stloc.s V_4
IL_0075: ldloca.s V_4
IL_0077: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_007c: brfalse.s IL_0088
IL_007e: ldstr "hi"
IL_0083: call "Sub System.Console.Write(String)"
IL_0088: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryPlus1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Integer? = 0
Console.WriteLine(x + goo(x))
End Sub
Function goo(ByRef v As Integer?) As Integer
v = 0
Return 42
End Function
End Module
</file>
</compilation>, expectedOutput:="42").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 63 (0x3f)
.maxstack 2
.locals init (Integer? V_0, //x
Integer? V_1,
Integer V_2,
Integer? V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldloc.0
IL_0009: stloc.1
IL_000a: ldloca.s V_0
IL_000c: call "Function MyClass1.goo(ByRef Integer?) As Integer"
IL_0011: stloc.2
IL_0012: ldloca.s V_1
IL_0014: call "Function Integer?.get_HasValue() As Boolean"
IL_0019: brtrue.s IL_0026
IL_001b: ldloca.s V_3
IL_001d: initobj "Integer?"
IL_0023: ldloc.3
IL_0024: br.s IL_0034
IL_0026: ldloca.s V_1
IL_0028: call "Function Integer?.GetValueOrDefault() As Integer"
IL_002d: ldloc.2
IL_002e: add.ovf
IL_002f: newobj "Sub Integer?..ctor(Integer)"
IL_0034: box "Integer?"
IL_0039: call "Sub System.Console.WriteLine(Object)"
IL_003e: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryPlusHasValue1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Integer? = 2
If x + x = 4 Then
Console.Write("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 113 (0x71)
.maxstack 2
.locals init (Integer? V_0, //x
Integer? V_1,
Integer? V_2,
Boolean? V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.2
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Integer?.get_HasValue() As Boolean"
IL_000f: ldloca.s V_0
IL_0011: call "Function Integer?.get_HasValue() As Boolean"
IL_0016: and
IL_0017: brtrue.s IL_0024
IL_0019: ldloca.s V_2
IL_001b: initobj "Integer?"
IL_0021: ldloc.2
IL_0022: br.s IL_0038
IL_0024: ldloca.s V_0
IL_0026: call "Function Integer?.GetValueOrDefault() As Integer"
IL_002b: ldloca.s V_0
IL_002d: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0032: add.ovf
IL_0033: newobj "Sub Integer?..ctor(Integer)"
IL_0038: stloc.1
IL_0039: ldloca.s V_1
IL_003b: call "Function Integer?.get_HasValue() As Boolean"
IL_0040: brtrue.s IL_004d
IL_0042: ldloca.s V_3
IL_0044: initobj "Boolean?"
IL_004a: ldloc.3
IL_004b: br.s IL_005c
IL_004d: ldloca.s V_1
IL_004f: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0054: ldc.i4.4
IL_0055: ceq
IL_0057: newobj "Sub Boolean?..ctor(Boolean)"
IL_005c: stloc.3
IL_005d: ldloca.s V_3
IL_005f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0064: brfalse.s IL_0070
IL_0066: ldstr "hi"
IL_006b: call "Sub System.Console.Write(String)"
IL_0070: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryPlusHasValue2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Integer? = 2
If 4 = x + x Then
Console.Write("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 113 (0x71)
.maxstack 2
.locals init (Integer? V_0, //x
Integer? V_1,
Integer? V_2,
Boolean? V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.2
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Integer?.get_HasValue() As Boolean"
IL_000f: ldloca.s V_0
IL_0011: call "Function Integer?.get_HasValue() As Boolean"
IL_0016: and
IL_0017: brtrue.s IL_0024
IL_0019: ldloca.s V_2
IL_001b: initobj "Integer?"
IL_0021: ldloc.2
IL_0022: br.s IL_0038
IL_0024: ldloca.s V_0
IL_0026: call "Function Integer?.GetValueOrDefault() As Integer"
IL_002b: ldloca.s V_0
IL_002d: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0032: add.ovf
IL_0033: newobj "Sub Integer?..ctor(Integer)"
IL_0038: stloc.1
IL_0039: ldloca.s V_1
IL_003b: call "Function Integer?.get_HasValue() As Boolean"
IL_0040: brtrue.s IL_004d
IL_0042: ldloca.s V_3
IL_0044: initobj "Boolean?"
IL_004a: ldloc.3
IL_004b: br.s IL_005c
IL_004d: ldc.i4.4
IL_004e: ldloca.s V_1
IL_0050: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0055: ceq
IL_0057: newobj "Sub Boolean?..ctor(Boolean)"
IL_005c: stloc.3
IL_005d: ldloca.s V_3
IL_005f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0064: brfalse.s IL_0070
IL_0066: ldstr "hi"
IL_006b: call "Sub System.Console.Write(String)"
IL_0070: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryBooleanXor()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Boolean? = True
If (x Xor Nothing) Then
Else
Console.WriteLine("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: newobj "Sub Boolean?..ctor(Boolean)"
IL_0006: pop
IL_0007: ldstr "hi"
IL_000c: call "Sub System.Console.WriteLine(String)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryBooleanXor1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Boolean? = True
Dim y As Boolean? = False
If (x Xor y) Then
Console.WriteLine("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 85 (0x55)
.maxstack 2
.locals init (Boolean? V_0, //x
Boolean? V_1, //y
Boolean? V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Boolean?..ctor(Boolean)"
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.0
IL_000b: call "Sub Boolean?..ctor(Boolean)"
IL_0010: ldloca.s V_0
IL_0012: call "Function Boolean?.get_HasValue() As Boolean"
IL_0017: ldloca.s V_1
IL_0019: call "Function Boolean?.get_HasValue() As Boolean"
IL_001e: and
IL_001f: brtrue.s IL_002c
IL_0021: ldloca.s V_2
IL_0023: initobj "Boolean?"
IL_0029: ldloc.2
IL_002a: br.s IL_0040
IL_002c: ldloca.s V_0
IL_002e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0033: ldloca.s V_1
IL_0035: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_003a: xor
IL_003b: newobj "Sub Boolean?..ctor(Boolean)"
IL_0040: stloc.2
IL_0041: ldloca.s V_2
IL_0043: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0048: brfalse.s IL_0054
IL_004a: ldstr "hi"
IL_004f: call "Sub System.Console.WriteLine(String)"
IL_0054: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryBooleanOrNothing()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Boolean? = True
If (x or Nothing) Then
Console.WriteLine("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 50 (0x32)
.maxstack 2
.locals init (Boolean? V_0, //x
Boolean? V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Boolean?..ctor(Boolean)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000f: brtrue.s IL_001c
IL_0011: ldloca.s V_1
IL_0013: initobj "Boolean?"
IL_0019: ldloc.1
IL_001a: br.s IL_001d
IL_001c: ldloc.0
IL_001d: stloc.1
IL_001e: ldloca.s V_1
IL_0020: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0025: brfalse.s IL_0031
IL_0027: ldstr "hi"
IL_002c: call "Sub System.Console.WriteLine(String)"
IL_0031: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryBooleanAndNothing()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Boolean? = True
If (Nothing And x) Then
Else
Console.WriteLine("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 61 (0x3d)
.maxstack 3
.locals init (Boolean? V_0, //x
Boolean? V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Boolean?..ctor(Boolean)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Boolean?.get_HasValue() As Boolean"
IL_000f: ldloca.s V_0
IL_0011: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0016: ldc.i4.0
IL_0017: ceq
IL_0019: and
IL_001a: brtrue.s IL_0027
IL_001c: ldloca.s V_1
IL_001e: initobj "Boolean?"
IL_0024: ldloc.1
IL_0025: br.s IL_0028
IL_0027: ldloc.0
IL_0028: stloc.1
IL_0029: ldloca.s V_1
IL_002b: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0030: brtrue.s IL_003c
IL_0032: ldstr "hi"
IL_0037: call "Sub System.Console.WriteLine(String)"
IL_003c: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryBooleanAnd()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
If (T() And T()) Then
Console.Write("hi")
End If
End Sub
Function T() As Boolean?
Return True
End Function
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 97 (0x61)
.maxstack 1
.locals init (Boolean? V_0,
Boolean? V_1,
Boolean? V_2)
IL_0000: call "Function MyClass1.T() As Boolean?"
IL_0005: stloc.0
IL_0006: call "Function MyClass1.T() As Boolean?"
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call "Function Boolean?.get_HasValue() As Boolean"
IL_0013: brfalse.s IL_001e
IL_0015: ldloca.s V_0
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brfalse.s IL_0046
IL_001e: ldloca.s V_1
IL_0020: call "Function Boolean?.get_HasValue() As Boolean"
IL_0025: brtrue.s IL_0032
IL_0027: ldloca.s V_2
IL_0029: initobj "Boolean?"
IL_002f: ldloc.2
IL_0030: br.s IL_004c
IL_0032: ldloca.s V_1
IL_0034: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0039: brtrue.s IL_0043
IL_003b: ldc.i4.0
IL_003c: newobj "Sub Boolean?..ctor(Boolean)"
IL_0041: br.s IL_004c
IL_0043: ldloc.0
IL_0044: br.s IL_004c
IL_0046: ldc.i4.0
IL_0047: newobj "Sub Boolean?..ctor(Boolean)"
IL_004c: stloc.1
IL_004d: ldloca.s V_1
IL_004f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0054: brfalse.s IL_0060
IL_0056: ldstr "hi"
IL_005b: call "Sub System.Console.Write(String)"
IL_0060: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryBooleanOr()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Boolean? = True
Dim y As Boolean? = True
If (x Or y) Then
Console.Write("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 101 (0x65)
.maxstack 2
.locals init (Boolean? V_0, //x
Boolean? V_1, //y
Boolean? V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Boolean?..ctor(Boolean)"
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.1
IL_000b: call "Sub Boolean?..ctor(Boolean)"
IL_0010: ldloca.s V_0
IL_0012: call "Function Boolean?.get_HasValue() As Boolean"
IL_0017: brfalse.s IL_0022
IL_0019: ldloca.s V_0
IL_001b: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0020: brtrue.s IL_004a
IL_0022: ldloca.s V_1
IL_0024: call "Function Boolean?.get_HasValue() As Boolean"
IL_0029: brtrue.s IL_0036
IL_002b: ldloca.s V_2
IL_002d: initobj "Boolean?"
IL_0033: ldloc.2
IL_0034: br.s IL_0050
IL_0036: ldloca.s V_1
IL_0038: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_003d: brtrue.s IL_0042
IL_003f: ldloc.0
IL_0040: br.s IL_0050
IL_0042: ldc.i4.1
IL_0043: newobj "Sub Boolean?..ctor(Boolean)"
IL_0048: br.s IL_0050
IL_004a: ldc.i4.1
IL_004b: newobj "Sub Boolean?..ctor(Boolean)"
IL_0050: stloc.2
IL_0051: ldloca.s V_2
IL_0053: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0058: brfalse.s IL_0064
IL_005a: ldstr "hi"
IL_005f: call "Sub System.Console.Write(String)"
IL_0064: ret
}
]]>)
End Sub
<Fact()>
Public Sub BinaryBool()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Module MyClass1
Sub Main(args As String())
Print("== And ==")
Print(T() And T())
Print(T() And F())
Print(T() And N())
Print(F() And T())
Print(F() And F())
Print(F() And N())
Print(N() And T())
Print(N() And F())
Print(N() And N())
Print("== Or ==")
Print(T() Or T())
Print(T() Or F())
Print(T() Or N())
Print(F() Or T())
Print(F() Or F())
Print(F() Or N())
Print(N() Or T())
Print(N() Or F())
Print(N() Or N())
Print("== AndAlso ==")
Print(T() AndAlso T())
Print(T() AndAlso F())
Print(T() AndAlso N())
Print(F() AndAlso T())
Print(F() AndAlso F())
Print(F() AndAlso N())
Print(N() AndAlso T())
Print(N() AndAlso F())
Print(N() AndAlso N())
Print("== OrElse ==")
Print(T() OrElse T())
Print(T() OrElse F())
Print(T() OrElse N())
Print(F() OrElse T())
Print(F() OrElse F())
Print(F() OrElse N())
Print(N() OrElse T())
Print(N() OrElse F())
Print(N() OrElse N())
End Sub
Private Sub Print(s As String)
Console.WriteLine(s)
End Sub
Private Sub Print(r As Boolean?)
Console.Write(": HasValue = ")
Console.Write(r.HasValue)
Console.Write(": Value =")
If r.HasValue Then
Console.Write(" ")
Console.Write(r)
End If
Console.WriteLine()
End Sub
Private Function T() As Boolean?
Console.Write("T")
Return True
End Function
Private Function F() As Boolean?
Console.Write("F")
Return False
End Function
Private Function N() As Boolean?
Console.Write("N")
Return Nothing
End Function
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
== And ==
TT: HasValue = True: Value = True
TF: HasValue = True: Value = False
TN: HasValue = False: Value =
FT: HasValue = True: Value = False
FF: HasValue = True: Value = False
FN: HasValue = True: Value = False
NT: HasValue = False: Value =
NF: HasValue = True: Value = False
NN: HasValue = False: Value =
== Or ==
TT: HasValue = True: Value = True
TF: HasValue = True: Value = True
TN: HasValue = True: Value = True
FT: HasValue = True: Value = True
FF: HasValue = True: Value = False
FN: HasValue = False: Value =
NT: HasValue = True: Value = True
NF: HasValue = False: Value =
NN: HasValue = False: Value =
== AndAlso ==
TT: HasValue = True: Value = True
TF: HasValue = True: Value = False
TN: HasValue = False: Value =
F: HasValue = True: Value = False
F: HasValue = True: Value = False
F: HasValue = True: Value = False
NT: HasValue = False: Value =
NF: HasValue = True: Value = False
NN: HasValue = False: Value =
== OrElse ==
T: HasValue = True: Value = True
T: HasValue = True: Value = True
T: HasValue = True: Value = True
FT: HasValue = True: Value = True
FF: HasValue = True: Value = False
FN: HasValue = False: Value =
NT: HasValue = True: Value = True
NF: HasValue = False: Value =
NN: HasValue = False: Value =
]]>
)
End Sub
<Fact()>
Public Sub BinaryBoolConstLeft()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Module MyClass1
Sub Main(args As String())
Print("== And ==")
Print(True And T())
Print(True And F())
Print(True And N())
Print(False And T())
Print(False And F())
Print(False And N())
Print(Nothing And T())
Print(Nothing And F())
Print(Nothing And N())
Print("== Or ==")
Print(True Or T())
Print(True Or F())
Print(True Or N())
Print(False Or T())
Print(False Or F())
Print(False Or N())
Print(Nothing Or T())
Print(Nothing Or F())
Print(Nothing Or N())
Print("== AndAlso ==")
Print(True AndAlso T())
Print(True AndAlso F())
Print(True AndAlso N())
Print(False AndAlso T())
Print(False AndAlso F())
Print(False AndAlso N())
Print(Nothing AndAlso T())
Print(Nothing AndAlso F())
Print(Nothing AndAlso N())
Print("== OrElse ==")
Print(True OrElse T())
Print(True OrElse F())
Print(True OrElse N())
Print(False OrElse T())
Print(False OrElse F())
Print(False OrElse N())
Print(Nothing OrElse T())
Print(Nothing OrElse F())
Print(Nothing OrElse N())
End Sub
Private Sub Print(s As String)
Console.WriteLine(s)
End Sub
Private Sub Print(r As Boolean?)
Console.Write(": HasValue = ")
Console.Write(r.HasValue)
Console.Write(": Value =")
If r.HasValue Then
Console.Write(" ")
Console.Write(r)
End If
Console.WriteLine()
End Sub
Private Function T() As Boolean?
Console.Write("T")
Return True
End Function
Private Function F() As Boolean?
Console.Write("F")
Return False
End Function
Private Function N() As Boolean?
Console.Write("N")
Return Nothing
End Function
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
== And ==
T: HasValue = True: Value = True
F: HasValue = True: Value = False
N: HasValue = False: Value =
T: HasValue = True: Value = False
F: HasValue = True: Value = False
N: HasValue = True: Value = False
T: HasValue = False: Value =
F: HasValue = True: Value = False
N: HasValue = False: Value =
== Or ==
T: HasValue = True: Value = True
F: HasValue = True: Value = True
N: HasValue = True: Value = True
T: HasValue = True: Value = True
F: HasValue = True: Value = False
N: HasValue = False: Value =
T: HasValue = True: Value = True
F: HasValue = False: Value =
N: HasValue = False: Value =
== AndAlso ==
T: HasValue = True: Value = True
F: HasValue = True: Value = False
N: HasValue = False: Value =
: HasValue = True: Value = False
: HasValue = True: Value = False
: HasValue = True: Value = False
T: HasValue = False: Value =
F: HasValue = True: Value = False
N: HasValue = False: Value =
== OrElse ==
: HasValue = True: Value = True
: HasValue = True: Value = True
: HasValue = True: Value = True
T: HasValue = True: Value = True
F: HasValue = True: Value = False
N: HasValue = False: Value =
T: HasValue = True: Value = True
F: HasValue = False: Value =
N: HasValue = False: Value =
]]>
)
End Sub
<Fact()>
Public Sub BinaryBoolConstRight()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Module MyClass1
Sub Main(args As String())
Print("== And ==")
Print(T() And True)
Print(T() And False)
Print(T() And Nothing)
Print(F() And True)
Print(F() And False)
Print(F() And Nothing)
Print(N() And True)
Print(N() And False)
Print(N() And Nothing)
Print("== Or ==")
Print(T() Or True)
Print(T() Or False)
Print(T() Or Nothing)
Print(F() Or True)
Print(F() Or False)
Print(F() Or Nothing)
Print(N() Or True)
Print(N() Or False)
Print(N() Or Nothing)
Print("== AndAlso ==")
Print(T() AndAlso True)
Print(T() AndAlso False)
Print(T() AndAlso Nothing)
Print(F() AndAlso True)
Print(F() AndAlso False)
Print(F() AndAlso Nothing)
Print(N() AndAlso True)
Print(N() AndAlso False)
Print(N() AndAlso Nothing)
Print("== OrElse ==")
Print(T() OrElse True)
Print(T() OrElse False)
Print(T() OrElse Nothing)
Print(F() OrElse True)
Print(F() OrElse False)
Print(F() OrElse Nothing)
Print(N() OrElse True)
Print(N() OrElse False)
Print(N() OrElse Nothing)
End Sub
Private Sub Print(s As String)
Console.WriteLine(s)
End Sub
Private Sub Print(r As Boolean?)
Console.Write(": HasValue = ")
Console.Write(r.HasValue)
Console.Write(": Value =")
If r.HasValue Then
Console.Write(" ")
Console.Write(r)
End If
Console.WriteLine()
End Sub
Private Function T() As Boolean?
Console.Write("T")
Return True
End Function
Private Function F() As Boolean?
Console.Write("F")
Return False
End Function
Private Function N() As Boolean?
Console.Write("N")
Return Nothing
End Function
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
== And ==
T: HasValue = True: Value = True
T: HasValue = True: Value = False
T: HasValue = False: Value =
F: HasValue = True: Value = False
F: HasValue = True: Value = False
F: HasValue = True: Value = False
N: HasValue = False: Value =
N: HasValue = True: Value = False
N: HasValue = False: Value =
== Or ==
T: HasValue = True: Value = True
T: HasValue = True: Value = True
T: HasValue = True: Value = True
F: HasValue = True: Value = True
F: HasValue = True: Value = False
F: HasValue = False: Value =
N: HasValue = True: Value = True
N: HasValue = False: Value =
N: HasValue = False: Value =
== AndAlso ==
T: HasValue = True: Value = True
T: HasValue = True: Value = False
T: HasValue = False: Value =
F: HasValue = True: Value = False
F: HasValue = True: Value = False
F: HasValue = True: Value = False
N: HasValue = False: Value =
N: HasValue = True: Value = False
N: HasValue = False: Value =
== OrElse ==
T: HasValue = True: Value = True
T: HasValue = True: Value = True
T: HasValue = True: Value = True
F: HasValue = True: Value = True
F: HasValue = True: Value = False
F: HasValue = False: Value =
N: HasValue = True: Value = True
N: HasValue = False: Value =
N: HasValue = False: Value =
]]>
)
End Sub
<Fact()>
Public Sub NewBooleanInLogicalExpression()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim bRet As Boolean?
bRet = New Boolean?(True) And Nothing
Console.WriteLine("Ret1={0}", bRet)
Select Case bret
Case Nothing
Console.WriteLine("Nothing")
Case Else
Console.Write("Else: ")
If (Nothing Or New Boolean?(False)) Is Nothing Then
Console.WriteLine("Ret2={0}", New Boolean?(True) OrElse New Boolean?() AndAlso New Boolean?(False))
End If
End Select
End Sub
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
Ret1=
Else: Ret2=True
]]>
).VerifyDiagnostics(Diagnostic(ERRID.WRN_EqualToLiteralNothing, "Nothing"))
End Sub
<Fact(), WorkItem(544948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544948")>
Public Sub NothingOrZeroInBinaryExpression()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Enum E
Zero
One
End Enum
Module M
Friend bN As Boolean? = Nothing
Public x As ULong? = 11
Sub Main()
Dim nZ As Integer? = 0
Dim r = nZ + 0 - nZ * 0
Console.Write("r1={0}", r)
Dim eN As E? = Nothing
Dim y As UShort? = Nothing
r = eN - bN * nZ + Nothing ^ y Mod x
Console.Write(" r2={0}", r)
End Sub
End Module
</file>
</compilation>, expectedOutput:="r1=0 r2=")
End Sub
<Fact()>
Public Sub NullableIs()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Boolean? = Nothing
If (x Is Nothing) Then
Console.WriteLine("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 28 (0x1c)
.maxstack 1
.locals init (Boolean? V_0) //x
IL_0000: ldloca.s V_0
IL_0002: initobj "Boolean?"
IL_0008: ldloca.s V_0
IL_000a: call "Function Boolean?.get_HasValue() As Boolean"
IL_000f: brtrue.s IL_001b
IL_0011: ldstr "hi"
IL_0016: call "Sub System.Console.WriteLine(String)"
IL_001b: ret
}
]]>)
End Sub
<Fact()>
Public Sub NullableIsNot()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
If Nothing IsNot CType(3, Int32?) Then
Console.WriteLine("hi")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="hi").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr "hi"
IL_0005: call "Sub System.Console.WriteLine(String)"
IL_000a: ret
}
]]>)
End Sub
<Fact()>
Public Sub NullableIsAndIsNot()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main()
While New Boolean?(False) Is Nothing OrElse Nothing IsNot New Boolean?(True)
If Nothing Is New Ulong?() Then
Console.Write("True")
Exit While
End If
End While
End Sub
End Module
</file>
</compilation>, expectedOutput:="True").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr "True"
IL_0005: call "Sub System.Console.Write(String)"
IL_000a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedIntrinsicConversion()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Integer = 123
Dim y As Long? = x
Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>, expectedOutput:="123").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 21 (0x15)
.maxstack 1
.locals init (Integer V_0) //x
IL_0000: ldc.i4.s 123
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: conv.i8
IL_0005: newobj "Sub Long?..ctor(Long)"
IL_000a: box "Long?"
IL_000f: call "Sub System.Console.WriteLine(Object)"
IL_0014: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedInterfaceConversion()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As IComparable(Of Integer) = 123
Dim y As Integer? = x
Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>, expectedOutput:="123").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 28 (0x1c)
.maxstack 1
IL_0000: ldc.i4.s 123
IL_0002: box "Integer"
IL_0007: castclass "System.IComparable(Of Integer)"
IL_000c: unbox.any "Integer?"
IL_0011: box "Integer?"
IL_0016: call "Sub System.Console.WriteLine(Object)"
IL_001b: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedReferenceConversionNarrowingFail()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Short? = 42
Dim z As ValueType = x
Try
Dim y As UInteger? = z
Console.WriteLine(y)
Catch ex As InvalidCastException
Console.WriteLine("pass")
End Try
End Sub
End Module
</file>
</compilation>, expectedOutput:="pass").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 56 (0x38)
.maxstack 2
.locals init (System.ValueType V_0, //z
System.InvalidCastException V_1) //ex
IL_0000: ldc.i4.s 42
IL_0002: newobj "Sub Short?..ctor(Short)"
IL_0007: box "Short?"
IL_000c: stloc.0
.try
{
IL_000d: ldloc.0
IL_000e: unbox.any "UInteger?"
IL_0013: box "UInteger?"
IL_0018: call "Sub System.Console.WriteLine(Object)"
IL_001d: leave.s IL_0037
}
catch System.InvalidCastException
{
IL_001f: dup
IL_0020: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0025: stloc.1
IL_0026: ldstr "pass"
IL_002b: call "Sub System.Console.WriteLine(String)"
IL_0030: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0035: leave.s IL_0037
}
IL_0037: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedInterfaceConversion1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim x As Integer? = 123
Dim y As IComparable(Of Integer) = x
Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>, expectedOutput:="123").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldc.i4.s 123
IL_0002: newobj "Sub Integer?..ctor(Integer)"
IL_0007: box "Integer?"
IL_000c: call "Sub System.Console.WriteLine(Object)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedInterfaceConversionGeneric()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
goo(42)
End Sub
Sub goo(Of T As {Structure, IComparable(Of T)})(x As T?)
Dim y As IComparable(Of T) = x
Console.Write(y.CompareTo(x.Value))
End Sub
End Module
</file>
</compilation>, expectedOutput:="0").
VerifyIL("MyClass1.goo",
<![CDATA[
{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box "T?"
IL_0006: ldarga.s V_0
IL_0008: call "Function T?.get_Value() As T"
IL_000d: callvirt "Function System.IComparable(Of T).CompareTo(T) As Integer"
IL_0012: call "Sub System.Console.Write(Integer)"
IL_0017: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedInterfaceConversionGeneric1()
Dim compilationDef =
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main(args As String())
goo(42)
End Sub
Sub goo(Of T As {Structure, IComparable(Of T)})(x As T?)
Dim y As IComparable(Of Integer) = x
Console.Write(y.CompareTo(43))
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom))
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42016: Implicit conversion from 'T?' to 'IComparable(Of Integer)'.
Dim y As IComparable(Of Integer) = x
~
</expected>)
CompileAndVerify(compilation,
expectedOutput:="-1").
VerifyIL("MyClass1.goo",
<![CDATA[
{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box "T?"
IL_0006: castclass "System.IComparable(Of Integer)"
IL_000b: ldc.i4.s 43
IL_000d: callvirt "Function System.IComparable(Of Integer).CompareTo(Integer) As Integer"
IL_0012: call "Sub System.Console.Write(Integer)"
IL_0017: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedCompoundOp()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
Module MyClass1
Sub Main()
Dim y As Integer? = 42
y += 1
Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>, expectedOutput:="43").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 2
.locals init (Integer? V_0,
Integer? V_1)
IL_0000: ldc.i4.s 42
IL_0002: newobj "Sub Integer?..ctor(Integer)"
IL_0007: stloc.0
IL_0008: ldloca.s V_0
IL_000a: call "Function Integer?.get_HasValue() As Boolean"
IL_000f: brtrue.s IL_001c
IL_0011: ldloca.s V_1
IL_0013: initobj "Integer?"
IL_0019: ldloc.1
IL_001a: br.s IL_002a
IL_001c: ldloca.s V_0
IL_001e: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0023: ldc.i4.1
IL_0024: add.ovf
IL_0025: newobj "Sub Integer?..ctor(Integer)"
IL_002a: box "Integer?"
IL_002f: call "Sub System.Console.WriteLine(Object)"
IL_0034: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedCompoundOp1()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
Module MyClass1
Sub Main()
Dim y As Integer? = 42
y += Nothing
Console.WriteLine(y.HasValue)
End Sub
End Module
</file>
</compilation>, expectedOutput:="False").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 30 (0x1e)
.maxstack 2
.locals init (Integer? V_0) //y
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: call "Sub Integer?..ctor(Integer)"
IL_0009: ldloca.s V_0
IL_000b: initobj "Integer?"
IL_0011: ldloca.s V_0
IL_0013: call "Function Integer?.get_HasValue() As Boolean"
IL_0018: call "Sub System.Console.WriteLine(Boolean)"
IL_001d: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryIf()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
Module MyClass1
Sub Main()
Dim y As Integer? = 123
Console.Write(If(If(New Long?(), New Short?(42)), y))
Console.Write(If(If(New Short?(42), New Long?()), y))
End Sub
End Module
</file>
</compilation>, expectedOutput:="4242").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 35 (0x23)
.maxstack 1
IL_0000: ldc.i4.s 123
IL_0002: newobj "Sub Integer?..ctor(Integer)"
IL_0007: pop
IL_0008: ldc.i4.s 42
IL_000a: conv.i8
IL_000b: box "Long"
IL_0010: call "Sub System.Console.Write(Object)"
IL_0015: ldc.i4.s 42
IL_0017: conv.i8
IL_0018: box "Long"
IL_001d: call "Sub System.Console.Write(Object)"
IL_0022: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryIf1()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
Module MyClass1
Sub Main()
Dim x As Long? = Nothing
Dim y As Integer? = 42
Console.WriteLine(If(y, x))
End Sub
End Module
</file>
</compilation>, expectedOutput:="42").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 2
.locals init (Long? V_0, //x
Integer? V_1) //y
IL_0000: ldloca.s V_0
IL_0002: initobj "Long?"
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.s 42
IL_000c: call "Sub Integer?..ctor(Integer)"
IL_0011: ldloca.s V_1
IL_0013: call "Function Integer?.get_HasValue() As Boolean"
IL_0018: brtrue.s IL_001d
IL_001a: ldloc.0
IL_001b: br.s IL_002a
IL_001d: ldloca.s V_1
IL_001f: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0024: conv.i8
IL_0025: newobj "Sub Long?..ctor(Long)"
IL_002a: box "Long?"
IL_002f: call "Sub System.Console.WriteLine(Object)"
IL_0034: ret
}
]]>)
End Sub
<Fact(), WorkItem(544930, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544930")>
Public Sub LiftedBinaryIf1a()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
Module MyClass1
Sub Main()
Console.Write(If(y, x))
Console.Write(If(x, y))
End Sub
Function x() As Long?
Console.Write("x")
Return Nothing
End Function
Function y() As Integer?
Console.Write("y")
Return 42
End Function
End Module
</file>
</compilation>, expectedOutput:="y42xy42")
End Sub
<Fact()>
Public Sub LiftedBinaryIf2()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
Module MyClass1
Sub Main()
Dim x As Short? = Nothing
Dim y As Ushort? = 42
Console.WriteLine(If(y, x))
End Sub
End Module
</file>
</compilation>, expectedOutput:="42").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 57 (0x39)
.maxstack 2
.locals init (Short? V_0, //x
UShort? V_1) //y
IL_0000: ldloca.s V_0
IL_0002: initobj "Short?"
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.s 42
IL_000c: call "Sub UShort?..ctor(UShort)"
IL_0011: ldloca.s V_1
IL_0013: call "Function UShort?.get_HasValue() As Boolean"
IL_0018: brtrue.s IL_0022
IL_001a: ldloc.0
IL_001b: box "Short?"
IL_0020: br.s IL_002e
IL_0022: ldloca.s V_1
IL_0024: call "Function UShort?.GetValueOrDefault() As UShort"
IL_0029: box "UShort"
IL_002e: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0033: call "Sub System.Console.WriteLine(Object)"
IL_0038: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryIf3()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main()
Dim x As Short? = Nothing
Dim y As Long = 42S
Dim z = If(x, y)
Console.WriteLine(z)
End Sub
End Module
</file>
</compilation>, expectedOutput:="42").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 38 (0x26)
.maxstack 1
.locals init (Short? V_0, //x
Long V_1) //y
IL_0000: ldloca.s V_0
IL_0002: initobj "Short?"
IL_0008: ldc.i4.s 42
IL_000a: conv.i8
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call "Function Short?.get_HasValue() As Boolean"
IL_0013: brtrue.s IL_0018
IL_0015: ldloc.1
IL_0016: br.s IL_0020
IL_0018: ldloca.s V_0
IL_001a: call "Function Short?.GetValueOrDefault() As Short"
IL_001f: conv.i8
IL_0020: call "Sub System.Console.WriteLine(Long)"
IL_0025: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryIf4()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Sub Main()
Dim x As Short? = Nothing
Dim y As IComparable(Of Short) = 42S
Dim z = If(x, y)
Console.WriteLine(z)
End Sub
End Module
</file>
</compilation>, expectedOutput:="42").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 56 (0x38)
.maxstack 1
.locals init (Short? V_0, //x
System.IComparable(Of Short) V_1) //y
IL_0000: ldloca.s V_0
IL_0002: initobj "Short?"
IL_0008: ldc.i4.s 42
IL_000a: box "Short"
IL_000f: castclass "System.IComparable(Of Short)"
IL_0014: stloc.1
IL_0015: ldloca.s V_0
IL_0017: call "Function Short?.get_HasValue() As Boolean"
IL_001c: brtrue.s IL_0021
IL_001e: ldloc.1
IL_001f: br.s IL_0032
IL_0021: ldloca.s V_0
IL_0023: call "Function Short?.GetValueOrDefault() As Short"
IL_0028: box "Short"
IL_002d: castclass "System.IComparable(Of Short)"
IL_0032: call "Sub System.Console.WriteLine(Object)"
IL_0037: ret
}
]]>)
End Sub
<Fact, WorkItem(545064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545064")>
Public Sub LiftedBinaryIf5_Nested()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Infer On
Imports System
Module Program
Sub Main()
Dim s4_a As Integer? = Nothing
If If(If(True, s4_a, 0), If(True, s4_a, 0)) Then
Console.Write("Fail")
Else
Console.Write("Pass")
End If
End Sub
End Module
]]>
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedOutput:="Pass")
End Sub
<Fact(), WorkItem(544945, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544945")>
Public Sub LiftedBinaryRelationalWithNothingLiteral()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Shared Sub Main()
Dim x As SByte? = 127
Dim y As SByte? = Nothing
Dim r1 = x >= Nothing ' = Nothing
Console.Write("r1={0} ", r1)
Dim r2 As Boolean? = Nothing < x ' = Nothing
Console.Write("r2={0} ", r2)
r1 = x > y
Console.Write("r3={0} ", r1)
r2 = y <= x
Console.Write("r4={0} ", r2)
End Sub
End Class
]]>
</file>
</compilation>
'emitOptions:=EmitOptions.RefEmitBug,
CompileAndVerify(source, expectedOutput:="r1= r2= r3= r4=")
End Sub
<WorkItem(544946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544946")>
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub LiftedBinaryConcatLikeWithNothingLiteral()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Shared Sub Main()
Dim x As SByte? = 127
Dim r1 = x & Nothing ' = 127
Console.Write("r1={0} ", r1)
Dim r2 = Nothing Like x ' = False
Console.Write("r2={0}", r2)
End Sub
End Class
]]>
</file>
</compilation>
'emitOptions:=EmitOptions.RefEmitBug,
CompileAndVerify(source, expectedOutput:="r1=127 r2=False")
End Sub
<Fact(), WorkItem(544947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544947")>
Public Sub LiftedBinaryDivisionWithNothingLiteral()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Shared Sub Main()
Dim x As SByte? = 127
Dim y As SByte? = Nothing
Dim r1 = y / Nothing ' = Nothing
Console.Write("r1={0} ", r1)
Dim r2 = Nothing / x ' = Nothing
Console.Write("r2={0} ", r2)
r1 = x \ Nothing
Console.Write("r3={0} ", r1)
r2 = Nothing \ y
Console.Write("r4={0} ", r2)
r1 = x \ y
Console.Write("r5={0} ", r1)
r2 = y / x
Console.Write("r6={0} ", r2)
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="r1= r2= r3= r4= r5= r6=")
End Sub
<Fact()>
Public Sub LiftedConversionHasValue()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Structure S1
Public x As Integer
Public Shared Widening Operator CType(ByVal a As S1) As S2
Console.Write("W")
Dim result As S2
result.x = a.x + 1
Return result
End Operator
Sub New(x As Integer)
Me.x = x
End Sub
End Structure
Structure S2
Public x As Integer
End Structure
Sub Main()
Dim y As S2 = New S1?(New S1(42))
Console.WriteLine(y.x)
End Sub
End Module
</file>
</compilation>, expectedOutput:="W43").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldc.i4.s 42
IL_0002: newobj "Sub MyClass1.S1..ctor(Integer)"
IL_0007: call "Function MyClass1.S1.op_Implicit(MyClass1.S1) As MyClass1.S2"
IL_000c: ldfld "MyClass1.S2.x As Integer"
IL_0011: call "Sub System.Console.WriteLine(Integer)"
IL_0016: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedConversionHasNoValue()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Structure S1
Public x As Integer
Public Shared Widening Operator CType(ByVal a As S1) As S2
Console.Write("W")
Dim result As S2
result.x = a.x + 1
Return result
End Operator
Sub New(x As Integer)
Me.x = x
End Sub
End Structure
Structure S2
Public x As Integer
End Structure
Sub Main()
Try
Dim y As S2 = New S1?()
Console.WriteLine(y.x)
Catch ex As InvalidOperationException
Console.WriteLine("pass")
End Try
End Sub
End Module
</file>
</compilation>, expectedOutput:="pass").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 59 (0x3b)
.maxstack 2
.locals init (MyClass1.S1? V_0,
System.InvalidOperationException V_1) //ex
.try
{
IL_0000: ldloca.s V_0
IL_0002: initobj "MyClass1.S1?"
IL_0008: ldloc.0
IL_0009: stloc.0
IL_000a: ldloca.s V_0
IL_000c: call "Function MyClass1.S1?.get_Value() As MyClass1.S1"
IL_0011: call "Function MyClass1.S1.op_Implicit(MyClass1.S1) As MyClass1.S2"
IL_0016: ldfld "MyClass1.S2.x As Integer"
IL_001b: call "Sub System.Console.WriteLine(Integer)"
IL_0020: leave.s IL_003a
}
catch System.InvalidOperationException
{
IL_0022: dup
IL_0023: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0028: stloc.1
IL_0029: ldstr "pass"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0038: leave.s IL_003a
}
IL_003a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedConversion()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module MyClass1
Structure S1
Public x As Integer
Public Shared Widening Operator CType(ByVal a As S1) As S2
Console.Write("W")
Dim result As S2
result.x = a.x + 1
Return result
End Operator
Sub New(x As Integer)
Me.x = x
End Sub
End Structure
Structure S2
Public x As Integer
End Structure
Sub Main()
Dim x As S1? = New S1(42)
Dim y As S2? = x
Console.WriteLine(y.Value.x)
End Sub
End Module
</file>
</compilation>, expectedOutput:="W43").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 70 (0x46)
.maxstack 2
.locals init (MyClass1.S1? V_0, //x
MyClass1.S2? V_1, //y
MyClass1.S2? V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: newobj "Sub MyClass1.S1..ctor(Integer)"
IL_0009: call "Sub MyClass1.S1?..ctor(MyClass1.S1)"
IL_000e: ldloca.s V_0
IL_0010: call "Function MyClass1.S1?.get_HasValue() As Boolean"
IL_0015: brtrue.s IL_0022
IL_0017: ldloca.s V_2
IL_0019: initobj "MyClass1.S2?"
IL_001f: ldloc.2
IL_0020: br.s IL_0033
IL_0022: ldloca.s V_0
IL_0024: call "Function MyClass1.S1?.GetValueOrDefault() As MyClass1.S1"
IL_0029: call "Function MyClass1.S1.op_Implicit(MyClass1.S1) As MyClass1.S2"
IL_002e: newobj "Sub MyClass1.S2?..ctor(MyClass1.S2)"
IL_0033: stloc.1
IL_0034: ldloca.s V_1
IL_0036: call "Function MyClass1.S2?.get_Value() As MyClass1.S2"
IL_003b: ldfld "MyClass1.S2.x As Integer"
IL_0040: call "Sub System.Console.WriteLine(Integer)"
IL_0045: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedConversionDev10()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
imports Microsoft.VisualBasic
Module Module1
Sub Main()
Dim av As New S1
Dim c As S1?
Dim d As T1?
d = c
Console.WriteLine("Lifted UD conversion: null check skips conversion call. d.HasValue= {0}" & Environment.NewLine, d.HasValue) 'expect 7
c = 1
Console.WriteLine("widening to nullable UD conversion: c=1; c.value= {0}" & Environment.NewLine, c.Value.i) 'expect 7
c = Nothing
Console.WriteLine("widening to nullable UD conversion: c=Nothing; c.HasValue= {0}" & Environment.NewLine, c.HasValue) 'expect 7
av.i = 7
Dim a2 As New S1?(av)
Dim b2 As T1
b2 = a2
Console.WriteLine("regular UD conversion+PDconversion: S1?->S1 -->T1, value passed:{0}" & Environment.NewLine, b2.i) 'expect 7
Dim a21 As New S1
a21.i = 8
Dim b21 As T1?
b21 = a21
Console.WriteLine("regular UD conversion+PD conversion: S1-->T1->T1?, value passed:{0}" & Environment.NewLine, b21.Value.i) 'expect 8
Dim val As New S1
val.i = 3
c = New S1?(val)
d = c
Console.WriteLine("lifted UD conversion, value passed:{0}" & Environment.NewLine, d.Value.i) 'expect 3
Dim k As New S2
k.i = 2
Dim c2 As New S2?(k)
Dim d2 As T2?
d2 = c2 'UD conversion on nullable preferred over lifting
Console.WriteLine(" UD nullable conversion, preferred over lifted value passed: {0}" & Environment.NewLine, d2.Value.i) 'expect 2
av.i = 5
Dim a As New S1?(av)
'a.i = 2
Dim b As T1?
b = a
Console.WriteLine("lifted UD conversion, value passed:{0}" & Environment.NewLine, b.Value.i) 'expect 5
Dim a1 As S1
a1.i = 6
Dim b1 As T1
b1 = a1
Console.WriteLine("regular UD conversion, value passed:{0}" & Environment.NewLine, b1.i) 'expect 6
Dim a3 As S1
a3.i = 8
Dim b3 As T1?
b3 = a3
Console.WriteLine("regular UD conversion+PD conversion, value passed:{0}" & Environment.NewLine, b3.Value.i) 'expect 8
Dim atv = New st(Of Integer)
atv.i = 9
Dim at As New st(Of Integer)?(atv)
Dim bt As Integer?
bt = at
Console.WriteLine("generic UD, value passed bt.value = :{0}" & Environment.NewLine, bt.Value) 'expect 8
End Sub
Structure S1
Dim i As Integer
'Public Shared Widening Operator CType(ByVal a As S1?) As T1?
' Dim t As New T1
' t.i = a.Value.i
' Return t
'End Operator
Public Shared Narrowing Operator CType(ByVal a As S1) As T1
Dim t As New T1
t.i = a.i
Console.WriteLine("UD regular conversion S1->T1 (possible by lifting) invoked")
Return t
End Operator
Public Shared Widening Operator CType(ByVal a As Integer) As S1
Dim t As New S1
t.i = a
Console.WriteLine("UD regular conversion int->S1 (possible by lifting) invoked")
Return t
End Operator
End Structure
Structure T1
Dim i As Integer
End Structure
Structure S2
Dim i As Integer
Public Shared Widening Operator CType(ByVal a As S2?) As T2?
Console.WriteLine("UD S2?->T2? conversion on nullable invoked")
If a.HasValue Then
Dim t As New T2
t.i = a.Value.i
Return t
Else
Return Nothing
End If
End Operator
Public Shared Narrowing Operator CType(ByVal a As S2) As T2
Dim t As New T2
t.i = a.i
Console.WriteLine("UD regular conversion S2->T2 (possible by lifting) invoked")
Return t
End Operator
End Structure
Structure T2
Dim i As Integer
'Public Shared Narrowing Operator CType(ByVal a As T2) As T2
' Dim t As New T2
' t.i = a.i
' Return t
'End Operator
End Structure
Structure st(Of T As Structure)
Dim i As T
Public Shared Narrowing Operator CType(ByVal a As st(Of T)) As T
Dim t As New T
t = a.i
Console.WriteLine("UD generic regular conversion st(of T)->T (possible by lifting) invoked")
Return t
End Operator
End Structure
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[Lifted UD conversion: null check skips conversion call. d.HasValue= False
UD regular conversion int->S1 (possible by lifting) invoked
widening to nullable UD conversion: c=1; c.value= 1
widening to nullable UD conversion: c=Nothing; c.HasValue= False
UD regular conversion S1->T1 (possible by lifting) invoked
regular UD conversion+PDconversion: S1?->S1 -->T1, value passed:7
UD regular conversion S1->T1 (possible by lifting) invoked
regular UD conversion+PD conversion: S1-->T1->T1?, value passed:8
UD regular conversion S1->T1 (possible by lifting) invoked
lifted UD conversion, value passed:3
UD S2?->T2? conversion on nullable invoked
UD nullable conversion, preferred over lifted value passed: 2
UD regular conversion S1->T1 (possible by lifting) invoked
lifted UD conversion, value passed:5
UD regular conversion S1->T1 (possible by lifting) invoked
regular UD conversion, value passed:6
UD regular conversion S1->T1 (possible by lifting) invoked
regular UD conversion+PD conversion, value passed:8
UD generic regular conversion st(of T)->T (possible by lifting) invoked
generic UD, value passed bt.value = :9
]]>)
End Sub
<Fact()>
Public Sub LiftedWideningAndNarrowingConversions()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Structure S(Of T As Structure)
Shared Narrowing Operator CType(x As S(Of T)) As T
System.Console.Write("Narrowing ")
Return Nothing
End Operator
Shared Widening Operator CType(x As S(Of T)) As T?
System.Console.Write("Widening ")
Return Nothing
End Operator
End Structure
Module Program
Sub Main()
Dim x As S(Of Integer)? = New S(Of Integer)()
Dim y As Integer? = 123
Dim ret = If(x, y)
Console.Write("Ret={0}", ret)
End Sub
End Module
</file>
</compilation>, expectedOutput:="Widening Ret=").
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 67 (0x43)
.maxstack 2
.locals init (S(Of Integer)? V_0, //x
Integer? V_1, //y
Integer? V_2, //ret
S(Of Integer) V_3)
IL_0000: ldloca.s V_0
IL_0002: ldloca.s V_3
IL_0004: initobj "S(Of Integer)"
IL_000a: ldloc.3
IL_000b: call "Sub S(Of Integer)?..ctor(S(Of Integer))"
IL_0010: ldloca.s V_1
IL_0012: ldc.i4.s 123
IL_0014: call "Sub Integer?..ctor(Integer)"
IL_0019: ldloca.s V_0
IL_001b: call "Function S(Of Integer)?.get_HasValue() As Boolean"
IL_0020: brtrue.s IL_0025
IL_0022: ldloc.1
IL_0023: br.s IL_0031
IL_0025: ldloca.s V_0
IL_0027: call "Function S(Of Integer)?.GetValueOrDefault() As S(Of Integer)"
IL_002c: call "Function S(Of Integer).op_Implicit(S(Of Integer)) As Integer?"
IL_0031: stloc.2
IL_0032: ldstr "Ret={0}"
IL_0037: ldloc.2
IL_0038: box "Integer?"
IL_003d: call "Sub System.Console.Write(String, Object)"
IL_0042: ret
}]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryUserDefinedMinusDev10()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports System
imports Microsoft.VisualBasic
Structure S1
Public x As Integer
Public Sub New(ByVal x As Integer)
Me.x = x
End Sub
Public Shared Operator -(ByVal x As S1, ByVal y As S1?) As S1
Return New S1(x.x - y.Value.x)
End Operator
End Structure
Module M1
Sub OutputEntry(ByVal expr As String, ByVal value As S1)
Console.WriteLine("{0} = {1}", expr, value.x)
End Sub
Sub Main()
Dim a As S1? = Nothing
Dim b As S1? = New S1(1)
Dim c As New S1(2)
Dim tmp As S1
Try
tmp = a - c
Catch ex As InvalidOperationException
Console.WriteLine("a - c threw an InvalidOperationException as expected!")
End Try
Try
tmp = c - a
Catch ex As InvalidOperationException
Console.WriteLine("c - a threw an InvalidOperationException as expected!")
End Try
Try
tmp = a - b
Catch ex As InvalidOperationException
Console.WriteLine("a - b threw an InvalidOperationException as expected!")
End Try
Try
tmp = b - a
Catch ex As InvalidOperationException
Console.WriteLine("a - b threw an InvalidOperationException as expected!")
End Try
OutputEntry("b - c", b - c)
OutputEntry("c - b", c - b)
End Sub
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[a - c threw an InvalidOperationException as expected!
c - a threw an InvalidOperationException as expected!
a - b threw an InvalidOperationException as expected!
a - b threw an InvalidOperationException as expected!
b - c = -1
c - b = 1
]]>)
End Sub
<Fact()>
Public Sub LiftedUnaryUserDefinedMinusDev10()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Structure S1
Dim x As Integer
Public Sub New(ByVal x As Integer)
Me.x = x
End Sub
Public Shared Operator -(ByVal x As S1) As S1
Return New S1(-x.x)
End Operator
End Structure
Module M1
Sub Main()
Dim arg As S1? = New S1(1)
Dim x = -arg
Dim y = -New S1?
Dim z = -New S1?(New S1(4))
Console.WriteLine("x.Value = {0}", x.Value.x)
Console.WriteLine("y.HasValue = {0}", y.HasValue)
Console.WriteLine("z.Value = {0}", z.Value.x)
End Sub
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[x.Value = -1
y.HasValue = False
z.Value = -4
]]>).
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 155 (0x9b)
.maxstack 2
.locals init (S1? V_0, //arg
S1? V_1, //x
S1? V_2, //y
S1? V_3, //z
S1? V_4)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: newobj "Sub S1..ctor(Integer)"
IL_0008: call "Sub S1?..ctor(S1)"
IL_000d: ldloca.s V_0
IL_000f: call "Function S1?.get_HasValue() As Boolean"
IL_0014: brtrue.s IL_0022
IL_0016: ldloca.s V_4
IL_0018: initobj "S1?"
IL_001e: ldloc.s V_4
IL_0020: br.s IL_0033
IL_0022: ldloca.s V_0
IL_0024: call "Function S1?.GetValueOrDefault() As S1"
IL_0029: call "Function S1.op_UnaryNegation(S1) As S1"
IL_002e: newobj "Sub S1?..ctor(S1)"
IL_0033: stloc.1
IL_0034: ldloca.s V_2
IL_0036: initobj "S1?"
IL_003c: ldloca.s V_3
IL_003e: ldc.i4.4
IL_003f: newobj "Sub S1..ctor(Integer)"
IL_0044: call "Function S1.op_UnaryNegation(S1) As S1"
IL_0049: call "Sub S1?..ctor(S1)"
IL_004e: ldstr "x.Value = {0}"
IL_0053: ldloca.s V_1
IL_0055: call "Function S1?.get_Value() As S1"
IL_005a: ldfld "S1.x As Integer"
IL_005f: box "Integer"
IL_0064: call "Sub System.Console.WriteLine(String, Object)"
IL_0069: ldstr "y.HasValue = {0}"
IL_006e: ldloca.s V_2
IL_0070: call "Function S1?.get_HasValue() As Boolean"
IL_0075: box "Boolean"
IL_007a: call "Sub System.Console.WriteLine(String, Object)"
IL_007f: ldstr "z.Value = {0}"
IL_0084: ldloca.s V_3
IL_0086: call "Function S1?.get_Value() As S1"
IL_008b: ldfld "S1.x As Integer"
IL_0090: box "Integer"
IL_0095: call "Sub System.Console.WriteLine(String, Object)"
IL_009a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryUserDefinedOneArgNotNullable()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Structure S1
Dim x As Integer
Public Sub New(ByVal x As Integer)
Me.x = x
End Sub
Public Shared Operator -(ByVal x As S1, ByVal y As S1) As S1
Return New S1(x.x - y.x)
End Operator
End Structure
Module M1
Sub Main()
Dim x As New S1?(New S1(42))
Dim y = x - New S1(2)
Console.WriteLine(y.Value.x)
End Sub
End Module
</file>
</compilation>, expectedOutput:="40").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 79 (0x4f)
.maxstack 2
.locals init (S1? V_0, //x
S1? V_1, //y
S1 V_2,
S1? V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: newobj "Sub S1..ctor(Integer)"
IL_0009: call "Sub S1?..ctor(S1)"
IL_000e: ldloca.s V_2
IL_0010: ldc.i4.2
IL_0011: call "Sub S1..ctor(Integer)"
IL_0016: ldloca.s V_0
IL_0018: call "Function S1?.get_HasValue() As Boolean"
IL_001d: brtrue.s IL_002a
IL_001f: ldloca.s V_3
IL_0021: initobj "S1?"
IL_0027: ldloc.3
IL_0028: br.s IL_003c
IL_002a: ldloca.s V_0
IL_002c: call "Function S1?.GetValueOrDefault() As S1"
IL_0031: ldloc.2
IL_0032: call "Function S1.op_Subtraction(S1, S1) As S1"
IL_0037: newobj "Sub S1?..ctor(S1)"
IL_003c: stloc.1
IL_003d: ldloca.s V_1
IL_003f: call "Function S1?.get_Value() As S1"
IL_0044: ldfld "S1.x As Integer"
IL_0049: call "Sub System.Console.WriteLine(Integer)"
IL_004e: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedBinaryUserDefinedReturnsNullable()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Structure S1
Dim x As Integer
Public Sub New(ByVal x As Integer)
Me.x = x
End Sub
Public Shared Operator +(ByVal x As S1, ByVal y As S1) As S1?
Return New S1(x.x + y.x)
End Operator
End Structure
Module M1
Sub Main()
Dim x As New S1?(New S1(42))
Dim y = x + x
Console.WriteLine(y.Value.x)
End Sub
End Module
</file>
</compilation>, expectedOutput:="84").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 80 (0x50)
.maxstack 2
.locals init (S1? V_0, //x
S1? V_1, //y
S1? V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: newobj "Sub S1..ctor(Integer)"
IL_0009: call "Sub S1?..ctor(S1)"
IL_000e: ldloca.s V_0
IL_0010: call "Function S1?.get_HasValue() As Boolean"
IL_0015: ldloca.s V_0
IL_0017: call "Function S1?.get_HasValue() As Boolean"
IL_001c: and
IL_001d: brtrue.s IL_002a
IL_001f: ldloca.s V_2
IL_0021: initobj "S1?"
IL_0027: ldloc.2
IL_0028: br.s IL_003d
IL_002a: ldloca.s V_0
IL_002c: call "Function S1?.GetValueOrDefault() As S1"
IL_0031: ldloca.s V_0
IL_0033: call "Function S1?.GetValueOrDefault() As S1"
IL_0038: call "Function S1.op_Addition(S1, S1) As S1?"
IL_003d: stloc.1
IL_003e: ldloca.s V_1
IL_0040: call "Function S1?.get_Value() As S1"
IL_0045: ldfld "S1.x As Integer"
IL_004a: call "Sub System.Console.WriteLine(Integer)"
IL_004f: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedUserConversionShortToInt()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Structure S1
Shared Widening Operator CType(x As Byte) As S1
Return New S1()
End Operator
End Structure
Sub Main()
Dim y As S1? = new Long?(42) ' === UDC
Console.WriteLine(y.HasValue)
End Sub
End Module
</file>
</compilation>, expectedOutput:="True").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (M1.S1? V_0) //y
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: call "Function M1.S1.op_Implicit(Byte) As M1.S1"
IL_0009: call "Sub M1.S1?..ctor(M1.S1)"
IL_000e: ldloca.s V_0
IL_0010: call "Function M1.S1?.get_HasValue() As Boolean"
IL_0015: call "Sub System.Console.WriteLine(Boolean)"
IL_001a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedUserConversionShortToIntA()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Structure S1
Shared Widening Operator CType(x As Byte) As S1
Return New S1()
End Operator
End Structure
Sub Main()
Dim y As S1? = x ' === UDC
Console.WriteLine(y.HasValue)
End Sub
Function x() As Long?
Console.Write("x")
Return New Long?(42)
End Function
End Module
</file>
</compilation>, expectedOutput:="xTrue").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (M1.S1? V_0, //y
Long? V_1,
Long? V_2,
M1.S1? V_3)
IL_0000: call "Function M1.x() As Long?"
IL_0005: dup
IL_0006: stloc.1
IL_0007: stloc.2
IL_0008: ldloca.s V_2
IL_000a: call "Function Long?.get_HasValue() As Boolean"
IL_000f: brtrue.s IL_001c
IL_0011: ldloca.s V_3
IL_0013: initobj "M1.S1?"
IL_0019: ldloc.3
IL_001a: br.s IL_002e
IL_001c: ldloca.s V_1
IL_001e: call "Function Long?.GetValueOrDefault() As Long"
IL_0023: conv.ovf.u1
IL_0024: call "Function M1.S1.op_Implicit(Byte) As M1.S1"
IL_0029: newobj "Sub M1.S1?..ctor(M1.S1)"
IL_002e: stloc.0
IL_002f: ldloca.s V_0
IL_0031: call "Function M1.S1?.get_HasValue() As Boolean"
IL_0036: call "Sub System.Console.WriteLine(Boolean)"
IL_003b: ret
}
]]>)
End Sub
<Fact(), WorkItem(544589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544589")>
Public Sub LiftedShortCircuitOperations()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim bF As Boolean? = False
Dim bT As Boolean? = True
Dim bN As Boolean? = Nothing
If bF OrElse bT AndAlso bN Then
Console.Write("True")
Else
Console.Write("False")
End If
End Sub
End Module
</file>
</compilation>, expectedOutput:="False").
VerifyIL("M.Main",
<![CDATA[
{
// Code size 91 (0x5b)
.maxstack 2
.locals init (Boolean? V_0, //bF
Boolean? V_1, //bT
Boolean? V_2) //bN
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: call "Sub Boolean?..ctor(Boolean)"
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.1
IL_000b: call "Sub Boolean?..ctor(Boolean)"
IL_0010: ldloca.s V_2
IL_0012: initobj "Boolean?"
IL_0018: ldloca.s V_0
IL_001a: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001f: brtrue.s IL_0045
IL_0021: ldloca.s V_1
IL_0023: call "Function Boolean?.get_HasValue() As Boolean"
IL_0028: brfalse.s IL_0033
IL_002a: ldloca.s V_1
IL_002c: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0031: brfalse.s IL_0050
IL_0033: ldloca.s V_2
IL_0035: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_003a: brfalse.s IL_0050
IL_003c: ldloca.s V_1
IL_003e: call "Function Boolean?.get_HasValue() As Boolean"
IL_0043: brfalse.s IL_0050
IL_0045: ldstr "True"
IL_004a: call "Sub System.Console.Write(String)"
IL_004f: ret
IL_0050: ldstr "False"
IL_0055: call "Sub System.Console.Write(String)"
IL_005a: ret
}
]]>)
End Sub
<Fact(), WorkItem(545124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545124")>
Public Sub LogicalOperationsWithNullableEnum()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Enum EnumItems
Item1 = 1
Item2 = 2
Item3 = 4
Item4 = 8
End Enum
Module M
Sub Main()
Dim value1a As EnumItems? = 10
Dim value1b As EnumItems = EnumItems.Item3
Console.Write(Not value1a And value1b Or value1a Xor value1b)
End Sub
End Module
</file>
</compilation>, expectedOutput:="10").
VerifyIL("M.Main",
<![CDATA[
{
// Code size 169 (0xa9)
.maxstack 2
.locals init (EnumItems? V_0, //value1a
EnumItems V_1, //value1b
EnumItems? V_2,
EnumItems? V_3,
EnumItems? V_4,
EnumItems? V_5)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 10
IL_0004: call "Sub EnumItems?..ctor(EnumItems)"
IL_0009: ldc.i4.4
IL_000a: stloc.1
IL_000b: ldloca.s V_0
IL_000d: call "Function EnumItems?.get_HasValue() As Boolean"
IL_0012: brtrue.s IL_0017
IL_0014: ldloc.0
IL_0015: br.s IL_0024
IL_0017: ldloca.s V_0
IL_0019: call "Function EnumItems?.GetValueOrDefault() As EnumItems"
IL_001e: not
IL_001f: newobj "Sub EnumItems?..ctor(EnumItems)"
IL_0024: stloc.s V_4
IL_0026: ldloca.s V_4
IL_0028: call "Function EnumItems?.get_HasValue() As Boolean"
IL_002d: brtrue.s IL_003b
IL_002f: ldloca.s V_5
IL_0031: initobj "EnumItems?"
IL_0037: ldloc.s V_5
IL_0039: br.s IL_0049
IL_003b: ldloca.s V_4
IL_003d: call "Function EnumItems?.GetValueOrDefault() As EnumItems"
IL_0042: ldloc.1
IL_0043: and
IL_0044: newobj "Sub EnumItems?..ctor(EnumItems)"
IL_0049: stloc.3
IL_004a: ldloca.s V_3
IL_004c: call "Function EnumItems?.get_HasValue() As Boolean"
IL_0051: ldloca.s V_0
IL_0053: call "Function EnumItems?.get_HasValue() As Boolean"
IL_0058: and
IL_0059: brtrue.s IL_0067
IL_005b: ldloca.s V_4
IL_005d: initobj "EnumItems?"
IL_0063: ldloc.s V_4
IL_0065: br.s IL_007b
IL_0067: ldloca.s V_3
IL_0069: call "Function EnumItems?.GetValueOrDefault() As EnumItems"
IL_006e: ldloca.s V_0
IL_0070: call "Function EnumItems?.GetValueOrDefault() As EnumItems"
IL_0075: or
IL_0076: newobj "Sub EnumItems?..ctor(EnumItems)"
IL_007b: stloc.2
IL_007c: ldloca.s V_2
IL_007e: call "Function EnumItems?.get_HasValue() As Boolean"
IL_0083: brtrue.s IL_0090
IL_0085: ldloca.s V_3
IL_0087: initobj "EnumItems?"
IL_008d: ldloc.3
IL_008e: br.s IL_009e
IL_0090: ldloca.s V_2
IL_0092: call "Function EnumItems?.GetValueOrDefault() As EnumItems"
IL_0097: ldloc.1
IL_0098: xor
IL_0099: newobj "Sub EnumItems?..ctor(EnumItems)"
IL_009e: box "EnumItems?"
IL_00a3: call "Sub System.Console.Write(Object)"
IL_00a8: ret
}
]]>)
End Sub
<Fact(), WorkItem(545125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545125")>
Public Sub ArithmeticOperationsWithNullableType()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Friend Module M
Public Function goo_exception() As Integer
Console.Write("1st Called ")
Throw New ArgumentNullException()
End Function
Public Function goo_eval_check() As Integer?
Console.Write("2nd Called ")
goo_eval_check = 2
End Function
Sub Main()
Try
Dim r1 = goo_exception() \ goo_eval_check()
Catch ex As ArgumentNullException
End Try
End Sub
End Module
</file>
</compilation>, expectedOutput:="1st Called").
VerifyIL("M.Main",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 2
.locals init (Integer V_0,
Integer? V_1,
System.ArgumentNullException V_2) //ex
.try
{
IL_0000: call "Function M.goo_exception() As Integer"
IL_0005: stloc.0
IL_0006: call "Function M.goo_eval_check() As Integer?"
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call "Function Integer?.get_HasValue() As Boolean"
IL_0013: brfalse.s IL_0024
IL_0015: ldloc.0
IL_0016: ldloca.s V_1
IL_0018: call "Function Integer?.GetValueOrDefault() As Integer"
IL_001d: div
IL_001e: newobj "Sub Integer?..ctor(Integer)"
IL_0023: pop
IL_0024: leave.s IL_0034
}
catch System.ArgumentNullException
{
IL_0026: dup
IL_0027: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_002c: stloc.2
IL_002d: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0032: leave.s IL_0034
}
IL_0034: ret
}
]]>)
End Sub
<Fact(), WorkItem(545437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545437")>
Public Sub Regress13840()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim y As MyStruct? = Nothing
If (CType(CType(Nothing, MyStruct?), MyStruct?) = y) Then 'expect warning
System.Console.WriteLine("Equals")
End If
End Sub
Structure MyStruct
Shared Operator =(ByVal left As MyStruct, ByVal right As MyStruct) As Boolean
Return True
End Operator
Shared Operator <>(ByVal left As MyStruct, ByVal right As MyStruct) As Boolean
Return False
End Operator
End Structure
End Module
</file>
</compilation>, expectedOutput:="")
End Sub
#Region "Diagnostics"
<Fact(), WorkItem(544942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544942"), WorkItem(599013, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/599013")>
Public Sub BC30424ERR_ConstAsNonConstant_Nullable()
Dim source =
<compilation>
<file name="a.vb">
Structure S : End Structure
Enum E : Zero : End Enum
Class C
Sub M()
Const c1 As Boolean? = Nothing
Const c2 As ULong? = 12345
Const c3 As E? = E.Zero
Dim d = Sub()
Const c4 As S? = Nothing
End Sub
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source)
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ConstAsNonConstant, "Boolean?"),
Diagnostic(ERRID.ERR_ConstAsNonConstant, "ULong?"),
Diagnostic(ERRID.ERR_ConstAsNonConstant, "E?"),
Diagnostic(ERRID.ERR_ConstAsNonConstant, "S?"))
End Sub
<Fact()>
Public Sub BC30456ERR_NameNotMember2_Nullable()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Option Explicit Off
Imports System
Structure S
Public field As C
End Structure
Class C
Public field As S
Shared Widening Operator CType(p As C) As S
Console.Write("N")
Return p.field
End Operator
Shared Narrowing Operator CType(p As S) As C
Console.Write("W")
Return p.field
End Operator
End Class
Module Program
Sub Main(args As String())
Dim x As New S()
x.field = New C()
x.field.field = x
Dim y As C = x.field
Dim ns As S? = y
Console.Write(ns.field.field Is y) ' BC30456
End Sub
End Module
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source)
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotMember2, "ns.field").WithArguments("field", "S?"))
End Sub
<Fact(), WorkItem(544945, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544945")>
Public Sub BC42037And42038WRN_EqualToLiteralNothing_Nullable()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Shared Sub Main()
Dim x As SByte? = Nothing
Dim y As SByte? = 123
Dim r1 = x = Nothing ' Assert here
If Not (r1 AndAlso Nothing <> y) Then
Console.WriteLine("FAIL")
Else
Console.WriteLine("PASS")
End If
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="PASS").VerifyDiagnostics(
Diagnostic(ERRID.WRN_EqualToLiteralNothing, "x = Nothing"),
Diagnostic(ERRID.WRN_NotEqualToLiteralNothing, "Nothing <> y")
)
End Sub
<Fact(), WorkItem(545050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545050")>
Public Sub DoNotGiveBC32126ERR_AddressOfNullableMethod()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Program
Sub Main()
Dim x As Integer? = Nothing
Dim f1 As Func(Of String) = AddressOf x.ToString
f1()
Dim f2 As Func(Of Integer) = AddressOf x.GetHashCode
f2()
Dim f3 As Func(Of Object, Boolean) = AddressOf x.Equals
f3(Nothing)
Dim f4 As Func(Of Type) = AddressOf x.GetType
f4()
Dim f5 As Func(Of Integer, Integer?) = AddressOf Integer?.op_Implicit
f5(1)
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source).VerifyDiagnostics().VerifyIL("Program.Main", <![CDATA[
{
// Code size 124 (0x7c)
.maxstack 3
.locals init (Integer? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "Integer?"
IL_0008: ldloc.0
IL_0009: dup
IL_000a: box "Integer?"
IL_000f: dup
IL_0010: ldvirtftn "Function System.ValueType.ToString() As String"
IL_0016: newobj "Sub System.Func(Of String)..ctor(Object, System.IntPtr)"
IL_001b: callvirt "Function System.Func(Of String).Invoke() As String"
IL_0020: pop
IL_0021: dup
IL_0022: box "Integer?"
IL_0027: dup
IL_0028: ldvirtftn "Function System.ValueType.GetHashCode() As Integer"
IL_002e: newobj "Sub System.Func(Of Integer)..ctor(Object, System.IntPtr)"
IL_0033: callvirt "Function System.Func(Of Integer).Invoke() As Integer"
IL_0038: pop
IL_0039: dup
IL_003a: box "Integer?"
IL_003f: dup
IL_0040: ldvirtftn "Function System.ValueType.Equals(Object) As Boolean"
IL_0046: newobj "Sub System.Func(Of Object, Boolean)..ctor(Object, System.IntPtr)"
IL_004b: ldnull
IL_004c: callvirt "Function System.Func(Of Object, Boolean).Invoke(Object) As Boolean"
IL_0051: pop
IL_0052: box "Integer?"
IL_0057: ldftn "Function Object.GetType() As System.Type"
IL_005d: newobj "Sub System.Func(Of System.Type)..ctor(Object, System.IntPtr)"
IL_0062: callvirt "Function System.Func(Of System.Type).Invoke() As System.Type"
IL_0067: pop
IL_0068: ldnull
IL_0069: ldftn "Function Integer?.op_Implicit(Integer) As Integer?"
IL_006f: newobj "Sub System.Func(Of Integer, Integer?)..ctor(Object, System.IntPtr)"
IL_0074: ldc.i4.1
IL_0075: callvirt "Function System.Func(Of Integer, Integer?).Invoke(Integer) As Integer?"
IL_007a: pop
IL_007b: ret
}
]]>)
End Sub
<Fact(), WorkItem(545126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545126")>
Public Sub BC36629ERR_NullableTypeInferenceNotSupported()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class C
Public X? = 10
Public X1? = {10}
Public Property Z? = 10
Public Property Z1? = {10}
Sub Test()
Dim Y? = 10
Dim Y1? = {10}
End Sub
Sub Test1()
' Option Strict Off, Option Infer Off - Expected No errors
' Option Strict Off, Option Infer On - Expected BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
' Option Strict On, Option Infer On - Expected BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static U? = 10
' Option Strict Off, Option Infer Off - Expected No errors
' Option Strict Off, Option Infer On - Expected BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
' Option Strict On, Option Infer On - Expected BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static U1? = {10}
Static V?() = Nothing
Static V1?(1) = Nothing
End Sub
Sub Test2()
Const U? = 10
Dim x As Object = U
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off).WithOptionInfer(False))
AssertTheseDiagnostics(compilation,
<expected>
BC36629: Nullable type inference is not supported in this context.
Public X? = 10
~~
BC36629: Nullable type inference is not supported in this context.
Public X1? = {10}
~~~
BC30205: End of statement expected.
Public Property Z? = 10
~
BC30205: End of statement expected.
Public Property Z1? = {10}
~
BC36629: Nullable type inference is not supported in this context.
Dim Y? = 10
~~
BC36629: Nullable type inference is not supported in this context.
Dim Y1? = {10}
~~~
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
Static V1?(1) = Nothing
~~~~~~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off).WithOptionInfer(True))
AssertTheseDiagnostics(compilation,
<expected>
BC36629: Nullable type inference is not supported in this context.
Public X? = 10
~~
BC36629: Nullable type inference is not supported in this context.
Public X1? = {10}
~~~
BC30205: End of statement expected.
Public Property Z? = 10
~
BC30205: End of statement expected.
Public Property Z1? = {10}
~
BC36628: A nullable type cannot be inferred for variable 'Y1'.
Dim Y1? = {10}
~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static U? = 10
~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static U1? = {10}
~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static V?() = Nothing
~~~~
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
Static V1?(1) = Nothing
~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static V1?(1) = Nothing
~~~~~~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On).WithOptionInfer(False))
AssertTheseDiagnostics(compilation,
<expected>
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Public X? = 10
~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Public X1? = {10}
~~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Public Property Z? = 10
~
BC30205: End of statement expected.
Public Property Z? = 10
~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Public Property Z1? = {10}
~~
BC30205: End of statement expected.
Public Property Z1? = {10}
~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Dim Y? = 10
~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Dim Y1? = {10}
~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static U? = 10
~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static U1? = {10}
~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static V?() = Nothing
~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static V1?(1) = Nothing
~~
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
Static V1?(1) = Nothing
~~~~~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Const U? = 10
~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On).WithOptionInfer(True))
AssertTheseDiagnostics(compilation,
<expected>
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Public X? = 10
~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Public X1? = {10}
~~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Public Property Z? = 10
~
BC30205: End of statement expected.
Public Property Z? = 10
~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Public Property Z1? = {10}
~~
BC30205: End of statement expected.
Public Property Z1? = {10}
~
BC36628: A nullable type cannot be inferred for variable 'Y1'.
Dim Y1? = {10}
~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static U? = 10
~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static U? = 10
~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static U1? = {10}
~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static U1? = {10}
~~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static V?() = Nothing
~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static V?() = Nothing
~~~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static V1?(1) = Nothing
~~
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
Static V1?(1) = Nothing
~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Static V1?(1) = Nothing
~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(545126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545126")>
Public Sub BC36629ERR_NullableTypeInferenceNotSupported_2()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class C
Public X%? = 10
Public X1%? = {10}
Public Property Z%? = 10
Public Property Z1%? = {10}
Sub Test()
Dim Y%? = 10
Dim Y1%? = {10}
End Sub
Sub Test1()
Static U%? = 10
Static U1%? = {10}
End Sub
Sub Test2()
Const V%? = 10
Dim x As Object = V
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off).WithOptionInfer(False))
AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Public X1%? = {10}
~~~~
BC30205: End of statement expected.
Public Property Z%? = 10
~
BC30205: End of statement expected.
Public Property Z1%? = {10}
~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Dim Y1%? = {10}
~~~~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Static U1%? = {10}
~~~~
BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.
Const V%? = 10
~~~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off).WithOptionInfer(True))
AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Public X1%? = {10}
~~~~
BC30205: End of statement expected.
Public Property Z%? = 10
~
BC30205: End of statement expected.
Public Property Z1%? = {10}
~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Dim Y1%? = {10}
~~~~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Static U1%? = {10}
~~~~
BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.
Const V%? = 10
~~~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On).WithOptionInfer(False))
AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Public X1%? = {10}
~~~~
BC30205: End of statement expected.
Public Property Z%? = 10
~
BC30205: End of statement expected.
Public Property Z1%? = {10}
~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Dim Y1%? = {10}
~~~~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Static U1%? = {10}
~~~~
BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.
Const V%? = 10
~~~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On).WithOptionInfer(True))
AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Public X1%? = {10}
~~~~
BC30205: End of statement expected.
Public Property Z%? = 10
~
BC30205: End of statement expected.
Public Property Z1%? = {10}
~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Dim Y1%? = {10}
~~~~
BC30311: Value of type 'Integer()' cannot be converted to 'Integer?'.
Static U1%? = {10}
~~~~
BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.
Const V%? = 10
~~~
</expected>)
End Sub
#End Region
#Region "For Loop"
<Fact()>
Public Sub LiftedForTo()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Public Class MyClass1
Public Shared Sub Main()
Dim l As UInteger? = 1
For x As UInteger? = 1 To 10 Step l
Console.Write(x)
If x >= 5 Then
x = Nothing
End If
Next
End Sub
End Class
</file>
</compilation>, expectedOutput:="12345").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 282 (0x11a)
.maxstack 3
.locals init (UInteger? V_0, //l
UInteger? V_1,
UInteger? V_2,
Boolean V_3,
UInteger? V_4, //x
Long? V_5,
Long? V_6,
Boolean? V_7,
UInteger? V_8)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub UInteger?..ctor(UInteger)"
IL_0008: ldc.i4.1
IL_0009: newobj "Sub UInteger?..ctor(UInteger)"
IL_000e: ldloca.s V_1
IL_0010: ldc.i4.s 10
IL_0012: call "Sub UInteger?..ctor(UInteger)"
IL_0017: ldloc.0
IL_0018: stloc.2
IL_0019: ldloca.s V_2
IL_001b: call "Function UInteger?.get_HasValue() As Boolean"
IL_0020: brfalse.s IL_0031
IL_0022: ldloca.s V_2
IL_0024: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_0029: ldc.i4.0
IL_002a: clt.un
IL_002c: ldc.i4.0
IL_002d: ceq
IL_002f: br.s IL_0032
IL_0031: ldc.i4.0
IL_0032: stloc.3
IL_0033: stloc.s V_4
IL_0035: br IL_00d8
IL_003a: ldloc.s V_4
IL_003c: box "UInteger?"
IL_0041: call "Sub System.Console.Write(Object)"
IL_0046: ldloca.s V_4
IL_0048: call "Function UInteger?.get_HasValue() As Boolean"
IL_004d: brtrue.s IL_005b
IL_004f: ldloca.s V_6
IL_0051: initobj "Long?"
IL_0057: ldloc.s V_6
IL_0059: br.s IL_0068
IL_005b: ldloca.s V_4
IL_005d: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_0062: conv.u8
IL_0063: newobj "Sub Long?..ctor(Long)"
IL_0068: stloc.s V_5
IL_006a: ldloca.s V_5
IL_006c: call "Function Long?.get_HasValue() As Boolean"
IL_0071: brtrue.s IL_007f
IL_0073: ldloca.s V_7
IL_0075: initobj "Boolean?"
IL_007b: ldloc.s V_7
IL_007d: br.s IL_0092
IL_007f: ldloca.s V_5
IL_0081: call "Function Long?.GetValueOrDefault() As Long"
IL_0086: ldc.i4.5
IL_0087: conv.i8
IL_0088: clt
IL_008a: ldc.i4.0
IL_008b: ceq
IL_008d: newobj "Sub Boolean?..ctor(Boolean)"
IL_0092: stloc.s V_7
IL_0094: ldloca.s V_7
IL_0096: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_009b: brfalse.s IL_00a5
IL_009d: ldloca.s V_4
IL_009f: initobj "UInteger?"
IL_00a5: ldloca.s V_2
IL_00a7: call "Function UInteger?.get_HasValue() As Boolean"
IL_00ac: ldloca.s V_4
IL_00ae: call "Function UInteger?.get_HasValue() As Boolean"
IL_00b3: and
IL_00b4: brtrue.s IL_00c2
IL_00b6: ldloca.s V_8
IL_00b8: initobj "UInteger?"
IL_00be: ldloc.s V_8
IL_00c0: br.s IL_00d6
IL_00c2: ldloca.s V_4
IL_00c4: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_00c9: ldloca.s V_2
IL_00cb: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_00d0: add.ovf.un
IL_00d1: newobj "Sub UInteger?..ctor(UInteger)"
IL_00d6: stloc.s V_4
IL_00d8: ldloca.s V_1
IL_00da: call "Function UInteger?.get_HasValue() As Boolean"
IL_00df: ldloca.s V_4
IL_00e1: call "Function UInteger?.get_HasValue() As Boolean"
IL_00e6: and
IL_00e7: brfalse.s IL_0119
IL_00e9: ldloc.3
IL_00ea: brtrue.s IL_0101
IL_00ec: ldloca.s V_4
IL_00ee: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_00f3: ldloca.s V_1
IL_00f5: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_00fa: clt.un
IL_00fc: ldc.i4.0
IL_00fd: ceq
IL_00ff: br.s IL_0114
IL_0101: ldloca.s V_4
IL_0103: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_0108: ldloca.s V_1
IL_010a: call "Function UInteger?.GetValueOrDefault() As UInteger"
IL_010f: cgt.un
IL_0111: ldc.i4.0
IL_0112: ceq
IL_0114: brtrue IL_003a
IL_0119: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedForToDefaultStep()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Public Class MyClass1
Public Shared Sub Main()
Dim x As Integer? = 1
For x = 1 To 10
Console.Write(x)
If x >= 5 Then
x = Nothing
End If
Next
End Sub
End Class
</file>
</compilation>, expectedOutput:="12345").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 248 (0xf8)
.maxstack 3
.locals init (Integer? V_0, //x
Integer? V_1,
Integer? V_2,
Boolean V_3,
Integer? V_4,
Boolean? V_5)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldc.i4.1
IL_0009: newobj "Sub Integer?..ctor(Integer)"
IL_000e: ldloca.s V_1
IL_0010: ldc.i4.s 10
IL_0012: call "Sub Integer?..ctor(Integer)"
IL_0017: ldloca.s V_2
IL_0019: ldc.i4.1
IL_001a: call "Sub Integer?..ctor(Integer)"
IL_001f: ldloca.s V_2
IL_0021: call "Function Integer?.get_HasValue() As Boolean"
IL_0026: brfalse.s IL_0037
IL_0028: ldloca.s V_2
IL_002a: call "Function Integer?.GetValueOrDefault() As Integer"
IL_002f: ldc.i4.0
IL_0030: clt
IL_0032: ldc.i4.0
IL_0033: ceq
IL_0035: br.s IL_0038
IL_0037: ldc.i4.0
IL_0038: stloc.3
IL_0039: stloc.0
IL_003a: br.s IL_00b6
IL_003c: ldloc.0
IL_003d: box "Integer?"
IL_0042: call "Sub System.Console.Write(Object)"
IL_0047: ldloc.0
IL_0048: stloc.s V_4
IL_004a: ldloca.s V_4
IL_004c: call "Function Integer?.get_HasValue() As Boolean"
IL_0051: brtrue.s IL_005f
IL_0053: ldloca.s V_5
IL_0055: initobj "Boolean?"
IL_005b: ldloc.s V_5
IL_005d: br.s IL_0071
IL_005f: ldloca.s V_4
IL_0061: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0066: ldc.i4.5
IL_0067: clt
IL_0069: ldc.i4.0
IL_006a: ceq
IL_006c: newobj "Sub Boolean?..ctor(Boolean)"
IL_0071: stloc.s V_5
IL_0073: ldloca.s V_5
IL_0075: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_007a: brfalse.s IL_0084
IL_007c: ldloca.s V_0
IL_007e: initobj "Integer?"
IL_0084: ldloca.s V_2
IL_0086: call "Function Integer?.get_HasValue() As Boolean"
IL_008b: ldloca.s V_0
IL_008d: call "Function Integer?.get_HasValue() As Boolean"
IL_0092: and
IL_0093: brtrue.s IL_00a1
IL_0095: ldloca.s V_4
IL_0097: initobj "Integer?"
IL_009d: ldloc.s V_4
IL_009f: br.s IL_00b5
IL_00a1: ldloca.s V_0
IL_00a3: call "Function Integer?.GetValueOrDefault() As Integer"
IL_00a8: ldloca.s V_2
IL_00aa: call "Function Integer?.GetValueOrDefault() As Integer"
IL_00af: add.ovf
IL_00b0: newobj "Sub Integer?..ctor(Integer)"
IL_00b5: stloc.0
IL_00b6: ldloca.s V_1
IL_00b8: call "Function Integer?.get_HasValue() As Boolean"
IL_00bd: ldloca.s V_0
IL_00bf: call "Function Integer?.get_HasValue() As Boolean"
IL_00c4: and
IL_00c5: brfalse.s IL_00f7
IL_00c7: ldloc.3
IL_00c8: brtrue.s IL_00df
IL_00ca: ldloca.s V_0
IL_00cc: call "Function Integer?.GetValueOrDefault() As Integer"
IL_00d1: ldloca.s V_1
IL_00d3: call "Function Integer?.GetValueOrDefault() As Integer"
IL_00d8: clt
IL_00da: ldc.i4.0
IL_00db: ceq
IL_00dd: br.s IL_00f2
IL_00df: ldloca.s V_0
IL_00e1: call "Function Integer?.GetValueOrDefault() As Integer"
IL_00e6: ldloca.s V_1
IL_00e8: call "Function Integer?.GetValueOrDefault() As Integer"
IL_00ed: cgt
IL_00ef: ldc.i4.0
IL_00f0: ceq
IL_00f2: brtrue IL_003c
IL_00f7: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedForToDecimalSideeffectsNullStep()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Public Class MyClass1
Public Shared Sub Main()
For x As Decimal? = Init() To Limit() Step [Step]()
Console.Write(x)
Next
End Sub
Private Shared Function Init() As Integer
Console.WriteLine("init")
Return 9
End Function
Private Shared Function Limit() As Integer
Console.WriteLine("limit")
Return 1
End Function
Private Shared Function [Step]() As Decimal?
Console.WriteLine("step")
Return nothing
End Function
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[init
limit
step
9]]>).
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 220 (0xdc)
.maxstack 3
.locals init (Decimal? V_0,
Decimal? V_1,
Boolean V_2,
Decimal? V_3, //x
Decimal? V_4)
IL_0000: call "Function MyClass1.Init() As Integer"
IL_0005: newobj "Sub Decimal..ctor(Integer)"
IL_000a: newobj "Sub Decimal?..ctor(Decimal)"
IL_000f: ldloca.s V_0
IL_0011: call "Function MyClass1.Limit() As Integer"
IL_0016: newobj "Sub Decimal..ctor(Integer)"
IL_001b: call "Sub Decimal?..ctor(Decimal)"
IL_0020: call "Function MyClass1.Step() As Decimal?"
IL_0025: stloc.1
IL_0026: ldloca.s V_1
IL_0028: call "Function Decimal?.get_HasValue() As Boolean"
IL_002d: brfalse.s IL_0048
IL_002f: ldloca.s V_1
IL_0031: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_0036: ldsfld "Decimal.Zero As Decimal"
IL_003b: call "Function Decimal.Compare(Decimal, Decimal) As Integer"
IL_0040: ldc.i4.0
IL_0041: clt
IL_0043: ldc.i4.0
IL_0044: ceq
IL_0046: br.s IL_0049
IL_0048: ldc.i4.0
IL_0049: stloc.2
IL_004a: stloc.3
IL_004b: br.s IL_008e
IL_004d: ldloc.3
IL_004e: box "Decimal?"
IL_0053: call "Sub System.Console.Write(Object)"
IL_0058: ldloca.s V_1
IL_005a: call "Function Decimal?.get_HasValue() As Boolean"
IL_005f: ldloca.s V_3
IL_0061: call "Function Decimal?.get_HasValue() As Boolean"
IL_0066: and
IL_0067: brtrue.s IL_0075
IL_0069: ldloca.s V_4
IL_006b: initobj "Decimal?"
IL_0071: ldloc.s V_4
IL_0073: br.s IL_008d
IL_0075: ldloca.s V_3
IL_0077: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_007c: ldloca.s V_1
IL_007e: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_0083: call "Function Decimal.Add(Decimal, Decimal) As Decimal"
IL_0088: newobj "Sub Decimal?..ctor(Decimal)"
IL_008d: stloc.3
IL_008e: ldloca.s V_0
IL_0090: call "Function Decimal?.get_HasValue() As Boolean"
IL_0095: ldloca.s V_3
IL_0097: call "Function Decimal?.get_HasValue() As Boolean"
IL_009c: and
IL_009d: brfalse.s IL_00db
IL_009f: ldloc.2
IL_00a0: brtrue.s IL_00bd
IL_00a2: ldloca.s V_3
IL_00a4: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_00a9: ldloca.s V_0
IL_00ab: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_00b0: call "Function Decimal.Compare(Decimal, Decimal) As Integer"
IL_00b5: ldc.i4.0
IL_00b6: clt
IL_00b8: ldc.i4.0
IL_00b9: ceq
IL_00bb: br.s IL_00d6
IL_00bd: ldloca.s V_3
IL_00bf: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_00c4: ldloca.s V_0
IL_00c6: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_00cb: call "Function Decimal.Compare(Decimal, Decimal) As Integer"
IL_00d0: ldc.i4.0
IL_00d1: cgt
IL_00d3: ldc.i4.0
IL_00d4: ceq
IL_00d6: brtrue IL_004d
IL_00db: ret
}
]]>)
End Sub
<Fact()>
Public Sub LiftedForCombinationsOneToThree()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Public Class MyClass1
Public Shared Sub Main()
' Step 1
For x As Integer? = One() To Three() Step One()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = One() To Null() Step One()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Null() To Three() Step One()
Console.Write(x)
Next
Console.WriteLine()
' Step -1
For x As Integer? = One() To Three() Step MOne()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = One() To Null() Step MOne()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Null() To Three() Step MOne()
Console.Write(x)
Next
Console.WriteLine()
' Step Null
For x As Integer? = One() To Three() Step Null()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = One() To Null() Step Null()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Null() To Three() Step Null()
Console.Write(x)
Next
Console.WriteLine()
End Sub
Private Shared Function One() As Integer?
Console.Write("one ")
Return 1
End Function
Private Shared Function MOne() As Integer?
Console.Write("-one ")
Return -1
End Function
Private Shared Function Three() As Integer?
Console.Write("three ")
Return 3
End Function
Private Shared Function Null() As Integer?
Console.Write("null ")
Return Nothing
End Function
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[one three one 123
one null one
null three one
one three -one
one null -one
null three -one
one three null
one null null
null three null
]]>)
End Sub
<Fact()>
Public Sub LiftedForCombinationsTreeToOne()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Public Class MyClass1
Public Shared Sub Main()
' Step 1
For x As Integer? = Three() To One() Step One()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Three() To Null() Step One()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Null() To One() Step One()
Console.Write(x)
Next
Console.WriteLine()
' Step -1
For x As Integer? = Three() To One() Step MOne()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Three() To Null() Step MOne()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Null() To One() Step MOne()
Console.Write(x)
Next
Console.WriteLine()
' Step Null
For x As Integer? = Three() To One() Step Null()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Three() To Null() Step Null()
Console.Write(x)
Next
Console.WriteLine()
For x As Integer? = Null() To One() Step Null()
Console.Write(x)
Next
Console.WriteLine()
End Sub
Private Shared Function One() As Integer?
Console.Write("one ")
Return 1
End Function
Private Shared Function MOne() As Integer?
Console.Write("-one ")
Return -1
End Function
Private Shared Function Three() As Integer?
Console.Write("three ")
Return 3
End Function
Private Shared Function Null() As Integer?
Console.Write("null ")
Return Nothing
End Function
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[three one one
three null one
null one one
three one -one 321
three null -one
null one -one
three one null 3
three null null
null one null
]]>)
End Sub
<Fact()>
Public Sub LiftedStringConversion()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class MyClass1
Shared Sub Main()
Dim x As SByte? = 42
Dim y As String = x
x = y
Console.Write(x)
End Sub
End Class
</file>
</compilation>, expectedOutput:="42").
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (SByte? V_0, //x
String V_1) //y
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: call "Sub SByte?..ctor(SByte)"
IL_0009: ldloca.s V_0
IL_000b: call "Function SByte?.get_Value() As SByte"
IL_0010: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String"
IL_0015: stloc.1
IL_0016: ldloca.s V_0
IL_0018: ldloc.1
IL_0019: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToSByte(String) As SByte"
IL_001e: call "Sub SByte?..ctor(SByte)"
IL_0023: ldloc.0
IL_0024: box "SByte?"
IL_0029: call "Sub System.Console.Write(Object)"
IL_002e: ret
}
]]>)
End Sub
#End Region
<Fact()>
Public Sub Regress14397()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Const a As Integer = If(True, 1, 2)
Sub Main()
Dim s As String
Dim inull As Integer? = Nothing
s = " :catenation right to integer?(null): " & inull
Console.WriteLine(s)
s = inull & " :catenation left to integer?(null): "
Console.WriteLine(s)
s = inull & inull
Console.WriteLine(" :catenation Integer?(null) & Integer?(null): " & s)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[:catenation right to integer?(null):
:catenation left to integer?(null):
:catenation Integer?(null) & Integer?(null): ]]>)
End Sub
''' <summary>
''' same as Dev11
''' implicit: int --> int?
''' explicit: int? --> int
''' </summary>
''' <remarks></remarks>
<Fact, WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")>
Public Sub Op_ExplicitImplicitOnNullable()
CompileAndVerify(
<compilation>
<file name="nullableOp.vb">
Imports System
Module MyClass1
Sub Main()
Dim x = (Integer?).op_Implicit(1)
x = (Integer?).op_Explicit(2)
Dim y = (Nullable(Of Integer)).op_Implicit(1)
y = (Nullable(Of Integer)).op_Explicit(2)
End Sub
End Module
</file>
</compilation>).
VerifyIL("MyClass1.Main",
<![CDATA[
{
// Code size 49 (0x31)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call "Function Integer?.op_Implicit(Integer) As Integer?"
IL_0006: pop
IL_0007: ldc.i4.2
IL_0008: newobj "Sub Integer?..ctor(Integer)"
IL_000d: call "Function Integer?.op_Explicit(Integer?) As Integer"
IL_0012: newobj "Sub Integer?..ctor(Integer)"
IL_0017: pop
IL_0018: ldc.i4.1
IL_0019: call "Function Integer?.op_Implicit(Integer) As Integer?"
IL_001e: pop
IL_001f: ldc.i4.2
IL_0020: newobj "Sub Integer?..ctor(Integer)"
IL_0025: call "Function Integer?.op_Explicit(Integer?) As Integer"
IL_002a: newobj "Sub Integer?..ctor(Integer)"
IL_002f: pop
IL_0030: ret
}
]]>)
End Sub
<Fact()>
Public Sub DecimalConst()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Public Class NullableTest
Shared NULL As Decimal? = Nothing
Public Shared Sub EqualEqual()
Test.Eval(CType(1D, Decimal?) is Nothing, False)
Test.Eval(CType(1D, Decimal?) = NULL, False)
Test.Eval(CType(0, Decimal?) = NULL, False)
End Sub
End Class
Public Class Test
Public Shared Sub Eval(obj1 As Object, obj2 As Object)
End Sub
End Class
</file>
</compilation>).
VerifyIL("NullableTest.EqualEqual",
<![CDATA[
{
// Code size 152 (0x98)
.maxstack 2
.locals init (Decimal? V_0,
Boolean? V_1)
IL_0000: ldc.i4.0
IL_0001: box "Boolean"
IL_0006: ldc.i4.0
IL_0007: box "Boolean"
IL_000c: call "Sub Test.Eval(Object, Object)"
IL_0011: ldsfld "NullableTest.NULL As Decimal?"
IL_0016: stloc.0
IL_0017: ldloca.s V_0
IL_0019: call "Function Decimal?.get_HasValue() As Boolean"
IL_001e: brtrue.s IL_002b
IL_0020: ldloca.s V_1
IL_0022: initobj "Boolean?"
IL_0028: ldloc.1
IL_0029: br.s IL_0044
IL_002b: ldsfld "Decimal.One As Decimal"
IL_0030: ldloca.s V_0
IL_0032: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_0037: call "Function Decimal.Compare(Decimal, Decimal) As Integer"
IL_003c: ldc.i4.0
IL_003d: ceq
IL_003f: newobj "Sub Boolean?..ctor(Boolean)"
IL_0044: box "Boolean?"
IL_0049: ldc.i4.0
IL_004a: box "Boolean"
IL_004f: call "Sub Test.Eval(Object, Object)"
IL_0054: ldsfld "NullableTest.NULL As Decimal?"
IL_0059: stloc.0
IL_005a: ldloca.s V_0
IL_005c: call "Function Decimal?.get_HasValue() As Boolean"
IL_0061: brtrue.s IL_006e
IL_0063: ldloca.s V_1
IL_0065: initobj "Boolean?"
IL_006b: ldloc.1
IL_006c: br.s IL_0087
IL_006e: ldsfld "Decimal.Zero As Decimal"
IL_0073: ldloca.s V_0
IL_0075: call "Function Decimal?.GetValueOrDefault() As Decimal"
IL_007a: call "Function Decimal.Compare(Decimal, Decimal) As Integer"
IL_007f: ldc.i4.0
IL_0080: ceq
IL_0082: newobj "Sub Boolean?..ctor(Boolean)"
IL_0087: box "Boolean?"
IL_008c: ldc.i4.0
IL_008d: box "Boolean"
IL_0092: call "Sub Test.Eval(Object, Object)"
IL_0097: ret
}
]]>)
End Sub
<Fact>
Public Sub LiftedToIntPtrConversion()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module M
Sub Main()
Console.WriteLine(CType(M(Nothing), IntPtr?))
Console.WriteLine(CType(M(42), IntPtr?))
End Sub
Function M(p as Integer?) As Integer?
Return p
End Function
End Module
</file>
</compilation>
Dim expectedOutput = "" + vbCrLf + "42"
CompileAndVerify(source, expectedOutput)
End Sub
<Fact()>
Public Sub SubtractFromZero()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim a As Integer? = 1
Dim b As Integer? = 0 - a
Console.WriteLine(String.Format("a: {0}, b: {1}", a, b))
Dim a1 As Integer? = 1
Dim b1 As Integer? = a - 0
Console.WriteLine(String.Format("a1: {0}, b1: {1}", a1, b1))
End Sub
End Module
</file>
</compilation>, expectedOutput:="a: 1, b: -1
a1: 1, b1: 1").
VerifyIL("Module1.Main",
<![CDATA[
{
// Code size 144 (0x90)
.maxstack 3
.locals init (Integer? V_0, //a
Integer? V_1, //b
Integer? V_2, //a1
Integer? V_3, //b1
Integer? V_4,
Integer? V_5)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call "Sub Integer?..ctor(Integer)"
IL_0008: ldloca.s V_0
IL_000a: call "Function Integer?.get_HasValue() As Boolean"
IL_000f: brtrue.s IL_001d
IL_0011: ldloca.s V_4
IL_0013: initobj "Integer?"
IL_0019: ldloc.s V_4
IL_001b: br.s IL_002b
IL_001d: ldc.i4.0
IL_001e: ldloca.s V_0
IL_0020: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0025: sub.ovf
IL_0026: newobj "Sub Integer?..ctor(Integer)"
IL_002b: stloc.1
IL_002c: ldstr "a: {0}, b: {1}"
IL_0031: ldloc.0
IL_0032: box "Integer?"
IL_0037: ldloc.1
IL_0038: box "Integer?"
IL_003d: call "Function String.Format(String, Object, Object) As String"
IL_0042: call "Sub System.Console.WriteLine(String)"
IL_0047: ldloca.s V_2
IL_0049: ldc.i4.1
IL_004a: call "Sub Integer?..ctor(Integer)"
IL_004f: ldloc.0
IL_0050: stloc.s V_4
IL_0052: ldloca.s V_4
IL_0054: call "Function Integer?.get_HasValue() As Boolean"
IL_0059: brtrue.s IL_0067
IL_005b: ldloca.s V_5
IL_005d: initobj "Integer?"
IL_0063: ldloc.s V_5
IL_0065: br.s IL_0073
IL_0067: ldloca.s V_4
IL_0069: call "Function Integer?.GetValueOrDefault() As Integer"
IL_006e: newobj "Sub Integer?..ctor(Integer)"
IL_0073: stloc.3
IL_0074: ldstr "a1: {0}, b1: {1}"
IL_0079: ldloc.2
IL_007a: box "Integer?"
IL_007f: ldloc.3
IL_0080: box "Integer?"
IL_0085: call "Function String.Format(String, Object, Object) As String"
IL_008a: call "Sub System.Console.WriteLine(String)"
IL_008f: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_01()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Class C
Public shared Sub Main()
Test1(Nothing, new C())
Test2(Nothing, new C())
Test3(Nothing, new C())
Test4(Nothing, new C())
Test5(Nothing, new C())
End Sub
Public Shared Sub Test1(x as C, y As C)
System.Console.WriteLine("->Test1")
If GetBool3(x) = True AndAlso y.GetBool2()
System.Console.WriteLine("In If")
End If
System.Console.WriteLine("<-Test1")
End Sub
Public Shared Sub Test2(x as C, y As C)
System.Console.WriteLine("->Test2")
If x?.GetBool1() = True AndAlso y.GetBool2()
System.Console.WriteLine("In If")
End If
System.Console.WriteLine("<-Test2")
End Sub
Public Shared Sub Test3(x as C, y As C)
System.Console.WriteLine("->Test3")
Dim z = GetBool3(x) = True AndAlso y.GetBool2()
If z
System.Console.WriteLine("In If")
End If
System.Console.WriteLine("<-Test3")
End Sub
Public Shared Sub Test4(x as C, y As C)
System.Console.WriteLine("->Test4")
Dim z = x?.GetBool1() = True AndAlso y.GetBool2()
If z
System.Console.WriteLine("In If")
End If
System.Console.WriteLine("<-Test4")
End Sub
Public Shared Sub Test5(x as C, y As C)
System.Console.WriteLine("->Test5")
If GetBool3(x) AndAlso y.GetBool2()
System.Console.WriteLine("In If")
End If
System.Console.WriteLine("<-Test5")
End Sub
Function GetBool1() As Boolean
Return True
End Function
Function GetBool2() As Boolean
System.Console.WriteLine("GetBool2")
Return True
End Function
Shared Function GetBool3(x as C) As Boolean?
if x Is Nothing
Return Nothing
End If
Return True
End Function
End Class
]]></file>
</compilation>, expectedOutput:=
<![CDATA[
->Test1
GetBool2
<-Test1
->Test2
GetBool2
<-Test2
->Test3
GetBool2
<-Test3
->Test4
GetBool2
<-Test4
->Test5
GetBool2
<-Test5
]]>
)
End Sub
<ConditionalFact(GetType(DesktopClrOnly))>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_02()
CompileAndVerify(
<compilation>
<file name="a.vb"><) As C
Return Me
End Function
Function Where(filter As System.Linq.Expressions.Expression(Of System.Func(Of C, Boolean))) As C
System.Console.WriteLine(filter.ToString())
Return Me
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Class
]]></file>
</compilation>, expectedOutput:=
<![CDATA[
y => (((y.GetBool3() == Convert(True)) AndAlso Convert(y.GetBool2())) ?? False)
y => (((y.GetBool3() == Convert(True)) OrElse Convert(y.GetBool2())) ?? False)
]]>
)
End Sub
<ConditionalFact(GetType(DesktopClrOnly))>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_03()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
Dim x As System.Linq.Expressions.Expression(Of System.Func(Of Boolean))
x = Function() If(GetBool3() = True AndAlso GetBool2(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() = True OrElse GetBool2(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(New Boolean?() AndAlso New Boolean?(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(New Boolean?() OrElse New Boolean?(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(New Boolean?() AndAlso GetBool2(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(New Boolean?() OrElse GetBool2(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(New Boolean?() AndAlso GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(New Boolean?() OrElse GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool2() AndAlso New Boolean?(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool2() OrElse New Boolean?(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() AndAlso New Boolean?(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() OrElse New Boolean?(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() AndAlso GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() OrElse GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() OrElse GetBool3() OrElse GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If((GetBool3() OrElse GetBool3()) OrElse GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() OrElse (GetBool3() OrElse GetBool3()), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If((GetBool3() OrElse GetBool3()) OrElse (GetBool3() OrElse GetBool3()), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If((GetBool3() OrElse GetBool3()) OrElse GetBool3() OrElse GetBool3(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If(GetBool3() AndAlso GetBool2() AndAlso GetBool2(), True, False)
System.Console.WriteLine(x.ToString())
x = Function() If((GetBool3() AndAlso GetBool2()) AndAlso GetBool2(), True, False)
System.Console.WriteLine(x.ToString())
End Sub
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>, expectedOutput:=
<![CDATA[
() => IIF((((GetBool3() == Convert(True)) AndAlso Convert(GetBool2())) ?? False), True, False)
() => IIF((((GetBool3() == Convert(True)) ?? False) OrElse GetBool2()), True, False)
() => IIF(((new Nullable`1() AndAlso new Nullable`1()) ?? False), True, False)
() => IIF(((new Nullable`1() ?? False) OrElse (new Nullable`1() ?? False)), True, False)
() => IIF(((new Nullable`1() AndAlso Convert(GetBool2())) ?? False), True, False)
() => IIF(((new Nullable`1() ?? False) OrElse GetBool2()), True, False)
() => IIF(((new Nullable`1() AndAlso GetBool3()) ?? False), True, False)
() => IIF(((new Nullable`1() ?? False) OrElse (GetBool3() ?? False)), True, False)
() => IIF((GetBool2() AndAlso (new Nullable`1() ?? False)), True, False)
() => IIF((GetBool2() OrElse (new Nullable`1() ?? False)), True, False)
() => IIF(((GetBool3() AndAlso new Nullable`1()) ?? False), True, False)
() => IIF(((GetBool3() ?? False) OrElse (new Nullable`1() ?? False)), True, False)
() => IIF(((GetBool3() AndAlso GetBool3()) ?? False), True, False)
() => IIF(((GetBool3() ?? False) OrElse (GetBool3() ?? False)), True, False)
() => IIF((((GetBool3() ?? False) OrElse (GetBool3() ?? False)) OrElse (GetBool3() ?? False)), True, False)
() => IIF((((GetBool3() ?? False) OrElse (GetBool3() ?? False)) OrElse (GetBool3() ?? False)), True, False)
() => IIF(((GetBool3() ?? False) OrElse ((GetBool3() ?? False) OrElse (GetBool3() ?? False))), True, False)
() => IIF((((GetBool3() ?? False) OrElse (GetBool3() ?? False)) OrElse ((GetBool3() ?? False) OrElse (GetBool3() ?? False))), True, False)
() => IIF(((((GetBool3() ?? False) OrElse (GetBool3() ?? False)) OrElse (GetBool3() ?? False)) OrElse (GetBool3() ?? False)), True, False)
() => IIF((((GetBool3() AndAlso Convert(GetBool2())) AndAlso Convert(GetBool2())) ?? False), True, False)
() => IIF((((GetBool3() AndAlso Convert(GetBool2())) AndAlso Convert(GetBool2())) ?? False), True, False)
]]>
)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_04()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() AndAlso GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 48 (0x30)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.get_HasValue() As Boolean"
IL_000d: brfalse.s IL_0018
IL_000f: ldloca.s V_1
IL_0011: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0016: brfalse.s IL_002c
IL_0018: call "Function Module1.GetBool2() As Boolean"
IL_001d: brfalse.s IL_002c
IL_001f: ldloca.s V_1
IL_0021: call "Function Boolean?.get_HasValue() As Boolean"
IL_0026: brfalse.s IL_002c
IL_0028: ldc.i4.2
IL_0029: stloc.0
IL_002a: br.s IL_002e
IL_002c: ldc.i4.3
IL_002d: stloc.0
IL_002e: ldloc.0
IL_002f: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_05()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() OrElse GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 30 (0x1e)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_0016
IL_000f: call "Function Module1.GetBool2() As Boolean"
IL_0014: brfalse.s IL_001a
IL_0016: ldc.i4.2
IL_0017: stloc.0
IL_0018: br.s IL_001c
IL_001a: ldc.i4.3
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_06()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool2() AndAlso GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 30 (0x1e)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: brfalse.s IL_001a
IL_0007: call "Function Module1.GetBool3() As Boolean?"
IL_000c: stloc.1
IL_000d: ldloca.s V_1
IL_000f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0014: brfalse.s IL_001a
IL_0016: ldc.i4.2
IL_0017: stloc.0
IL_0018: br.s IL_001c
IL_001a: ldc.i4.3
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_07()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool2() OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 30 (0x1e)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: brtrue.s IL_0016
IL_0007: call "Function Module1.GetBool3() As Boolean?"
IL_000c: stloc.1
IL_000d: ldloca.s V_1
IL_000f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0014: brfalse.s IL_001a
IL_0016: ldc.i4.2
IL_0017: stloc.0
IL_0018: br.s IL_001c
IL_001a: ldc.i4.3
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_08()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If New Boolean?() AndAlso GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: pop
IL_0006: ldc.i4.3
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_09()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If New Boolean?() OrElse GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 15 (0xf)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: brfalse.s IL_000b
IL_0007: ldc.i4.2
IL_0008: stloc.0
IL_0009: br.s IL_000d
IL_000b: ldc.i4.3
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_10()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If New Boolean?() AndAlso GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: pop
IL_0006: ldc.i4.3
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_11()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If New Boolean?() OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 23 (0x17)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brfalse.s IL_0013
IL_000f: ldc.i4.2
IL_0010: stloc.0
IL_0011: br.s IL_0015
IL_0013: ldc.i4.3
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_12()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() AndAlso New Boolean?() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: pop
IL_0006: ldc.i4.3
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_13()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() OrElse New Boolean?() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 23 (0x17)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brfalse.s IL_0013
IL_000f: ldc.i4.2
IL_0010: stloc.0
IL_0011: br.s IL_0015
IL_0013: ldc.i4.3
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_14()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool2() AndAlso New Boolean?() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: pop
IL_0006: ldc.i4.3
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_15()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool2() OrElse New Boolean?() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 15 (0xf)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: brfalse.s IL_000b
IL_0007: ldc.i4.2
IL_0008: stloc.0
IL_0009: br.s IL_000d
IL_000b: ldc.i4.3
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_16()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If New Boolean?() AndAlso New Boolean?() Then
Return 2
Else
Return 3
End If
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 4 (0x4)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_17()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If New Boolean?() OrElse New Boolean?() Then
Return 2
Else
Return 3
End If
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 4 (0x4)
.maxstack 1
.locals init (Integer V_0) //Test1
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_18()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() AndAlso GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 56 (0x38)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1,
Boolean? V_2)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.get_HasValue() As Boolean"
IL_000d: brfalse.s IL_0018
IL_000f: ldloca.s V_1
IL_0011: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0016: brfalse.s IL_0034
IL_0018: call "Function Module1.GetBool3() As Boolean?"
IL_001d: stloc.2
IL_001e: ldloca.s V_2
IL_0020: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0025: brfalse.s IL_0034
IL_0027: ldloca.s V_1
IL_0029: call "Function Boolean?.get_HasValue() As Boolean"
IL_002e: brfalse.s IL_0034
IL_0030: ldc.i4.2
IL_0031: stloc.0
IL_0032: br.s IL_0036
IL_0034: ldc.i4.3
IL_0035: stloc.0
IL_0036: ldloc.0
IL_0037: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_19()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 38 (0x26)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_001e
IL_000f: call "Function Module1.GetBool3() As Boolean?"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brfalse.s IL_0022
IL_001e: ldc.i4.2
IL_001f: stloc.0
IL_0020: br.s IL_0024
IL_0022: ldc.i4.3
IL_0023: stloc.0
IL_0024: ldloc.0
IL_0025: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_20()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool2() AndAlso (GetBool2() AndAlso GetBool3()) Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 37 (0x25)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool2() As Boolean"
IL_0005: brfalse.s IL_0021
IL_0007: call "Function Module1.GetBool2() As Boolean"
IL_000c: brfalse.s IL_0021
IL_000e: call "Function Module1.GetBool3() As Boolean?"
IL_0013: stloc.1
IL_0014: ldloca.s V_1
IL_0016: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001b: brfalse.s IL_0021
IL_001d: ldc.i4.2
IL_001e: stloc.0
IL_001f: br.s IL_0023
IL_0021: ldc.i4.3
IL_0022: stloc.0
IL_0023: ldloc.0
IL_0024: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_21()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() OrElse (GetBool3() OrElse GetBool3()) Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_002d
IL_000f: call "Function Module1.GetBool3() As Boolean?"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brtrue.s IL_002d
IL_001e: call "Function Module1.GetBool3() As Boolean?"
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_002b: brfalse.s IL_0031
IL_002d: ldc.i4.2
IL_002e: stloc.0
IL_002f: br.s IL_0033
IL_0031: ldc.i4.3
IL_0032: stloc.0
IL_0033: ldloc.0
IL_0034: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_22()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetBool3() OrElse GetBool3()) AndAlso GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 134 (0x86)
.maxstack 2
.locals init (Integer V_0, //Test1
Boolean? V_1,
Boolean? V_2,
Boolean? V_3,
Boolean? V_4)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: dup
IL_0006: stloc.2
IL_0007: stloc.s V_4
IL_0009: ldloca.s V_4
IL_000b: call "Function Boolean?.get_HasValue() As Boolean"
IL_0010: brfalse.s IL_001b
IL_0012: ldloca.s V_2
IL_0014: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0019: brtrue.s IL_004d
IL_001b: call "Function Module1.GetBool3() As Boolean?"
IL_0020: dup
IL_0021: stloc.3
IL_0022: stloc.s V_4
IL_0024: ldloca.s V_4
IL_0026: call "Function Boolean?.get_HasValue() As Boolean"
IL_002b: brtrue.s IL_0039
IL_002d: ldloca.s V_4
IL_002f: initobj "Boolean?"
IL_0035: ldloc.s V_4
IL_0037: br.s IL_0053
IL_0039: ldloca.s V_3
IL_003b: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0040: brtrue.s IL_0045
IL_0042: ldloc.2
IL_0043: br.s IL_0053
IL_0045: ldc.i4.1
IL_0046: newobj "Sub Boolean?..ctor(Boolean)"
IL_004b: br.s IL_0053
IL_004d: ldc.i4.1
IL_004e: newobj "Sub Boolean?..ctor(Boolean)"
IL_0053: stloc.1
IL_0054: ldloca.s V_1
IL_0056: call "Function Boolean?.get_HasValue() As Boolean"
IL_005b: brfalse.s IL_0066
IL_005d: ldloca.s V_1
IL_005f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0064: brfalse.s IL_0082
IL_0066: call "Function Module1.GetBool3() As Boolean?"
IL_006b: stloc.3
IL_006c: ldloca.s V_3
IL_006e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0073: brfalse.s IL_0082
IL_0075: ldloca.s V_1
IL_0077: call "Function Boolean?.get_HasValue() As Boolean"
IL_007c: brfalse.s IL_0082
IL_007e: ldc.i4.2
IL_007f: stloc.0
IL_0080: br.s IL_0084
IL_0082: ldc.i4.3
IL_0083: stloc.0
IL_0084: ldloc.0
IL_0085: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_23()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetBool3() OrElse GetBool3()) AndAlso GetBool3() OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 149 (0x95)
.maxstack 2
.locals init (Integer V_0, //Test1
Boolean? V_1,
Boolean? V_2,
Boolean? V_3,
Boolean? V_4)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: dup
IL_0006: stloc.2
IL_0007: stloc.s V_4
IL_0009: ldloca.s V_4
IL_000b: call "Function Boolean?.get_HasValue() As Boolean"
IL_0010: brfalse.s IL_001b
IL_0012: ldloca.s V_2
IL_0014: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0019: brtrue.s IL_004d
IL_001b: call "Function Module1.GetBool3() As Boolean?"
IL_0020: dup
IL_0021: stloc.3
IL_0022: stloc.s V_4
IL_0024: ldloca.s V_4
IL_0026: call "Function Boolean?.get_HasValue() As Boolean"
IL_002b: brtrue.s IL_0039
IL_002d: ldloca.s V_4
IL_002f: initobj "Boolean?"
IL_0035: ldloc.s V_4
IL_0037: br.s IL_0053
IL_0039: ldloca.s V_3
IL_003b: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0040: brtrue.s IL_0045
IL_0042: ldloc.2
IL_0043: br.s IL_0053
IL_0045: ldc.i4.1
IL_0046: newobj "Sub Boolean?..ctor(Boolean)"
IL_004b: br.s IL_0053
IL_004d: ldc.i4.1
IL_004e: newobj "Sub Boolean?..ctor(Boolean)"
IL_0053: stloc.1
IL_0054: ldloca.s V_1
IL_0056: call "Function Boolean?.get_HasValue() As Boolean"
IL_005b: brfalse.s IL_0066
IL_005d: ldloca.s V_1
IL_005f: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0064: brfalse.s IL_007e
IL_0066: call "Function Module1.GetBool3() As Boolean?"
IL_006b: stloc.3
IL_006c: ldloca.s V_3
IL_006e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0073: brfalse.s IL_007e
IL_0075: ldloca.s V_1
IL_0077: call "Function Boolean?.get_HasValue() As Boolean"
IL_007c: brtrue.s IL_008d
IL_007e: call "Function Module1.GetBool3() As Boolean?"
IL_0083: stloc.1
IL_0084: ldloca.s V_1
IL_0086: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_008b: brfalse.s IL_0091
IL_008d: ldc.i4.2
IL_008e: stloc.0
IL_008f: br.s IL_0093
IL_0091: ldc.i4.3
IL_0092: stloc.0
IL_0093: ldloc.0
IL_0094: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_24()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetBool3() OrElse GetBool3()) OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_002d
IL_000f: call "Function Module1.GetBool3() As Boolean?"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brtrue.s IL_002d
IL_001e: call "Function Module1.GetBool3() As Boolean?"
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_002b: brfalse.s IL_0031
IL_002d: ldc.i4.2
IL_002e: stloc.0
IL_002f: br.s IL_0033
IL_0031: ldc.i4.3
IL_0032: stloc.0
IL_0033: ldloc.0
IL_0034: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_25()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() OrElse GetBool3() OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_002d
IL_000f: call "Function Module1.GetBool3() As Boolean?"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brtrue.s IL_002d
IL_001e: call "Function Module1.GetBool3() As Boolean?"
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_002b: brfalse.s IL_0031
IL_002d: ldc.i4.2
IL_002e: stloc.0
IL_002f: br.s IL_0033
IL_0031: ldc.i4.3
IL_0032: stloc.0
IL_0033: ldloc.0
IL_0034: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_26()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetBool3() AndAlso GetBool2()) AndAlso GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 93 (0x5d)
.maxstack 2
.locals init (Integer V_0, //Test1
Boolean? V_1,
Boolean? V_2,
Boolean? V_3)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: dup
IL_0006: stloc.2
IL_0007: stloc.3
IL_0008: ldloca.s V_3
IL_000a: call "Function Boolean?.get_HasValue() As Boolean"
IL_000f: brfalse.s IL_001a
IL_0011: ldloca.s V_2
IL_0013: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0018: brfalse.s IL_002c
IL_001a: call "Function Module1.GetBool2() As Boolean"
IL_001f: brtrue.s IL_0029
IL_0021: ldc.i4.0
IL_0022: newobj "Sub Boolean?..ctor(Boolean)"
IL_0027: br.s IL_0032
IL_0029: ldloc.2
IL_002a: br.s IL_0032
IL_002c: ldc.i4.0
IL_002d: newobj "Sub Boolean?..ctor(Boolean)"
IL_0032: stloc.1
IL_0033: ldloca.s V_1
IL_0035: call "Function Boolean?.get_HasValue() As Boolean"
IL_003a: brfalse.s IL_0045
IL_003c: ldloca.s V_1
IL_003e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0043: brfalse.s IL_0059
IL_0045: call "Function Module1.GetBool2() As Boolean"
IL_004a: brfalse.s IL_0059
IL_004c: ldloca.s V_1
IL_004e: call "Function Boolean?.get_HasValue() As Boolean"
IL_0053: brfalse.s IL_0059
IL_0055: ldc.i4.2
IL_0056: stloc.0
IL_0057: br.s IL_005b
IL_0059: ldc.i4.3
IL_005a: stloc.0
IL_005b: ldloc.0
IL_005c: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_27()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool3() AndAlso GetBool2() AndAlso GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool2() As Boolean
Return True
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 93 (0x5d)
.maxstack 2
.locals init (Integer V_0, //Test1
Boolean? V_1,
Boolean? V_2,
Boolean? V_3)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: dup
IL_0006: stloc.2
IL_0007: stloc.3
IL_0008: ldloca.s V_3
IL_000a: call "Function Boolean?.get_HasValue() As Boolean"
IL_000f: brfalse.s IL_001a
IL_0011: ldloca.s V_2
IL_0013: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0018: brfalse.s IL_002c
IL_001a: call "Function Module1.GetBool2() As Boolean"
IL_001f: brtrue.s IL_0029
IL_0021: ldc.i4.0
IL_0022: newobj "Sub Boolean?..ctor(Boolean)"
IL_0027: br.s IL_0032
IL_0029: ldloc.2
IL_002a: br.s IL_0032
IL_002c: ldc.i4.0
IL_002d: newobj "Sub Boolean?..ctor(Boolean)"
IL_0032: stloc.1
IL_0033: ldloca.s V_1
IL_0035: call "Function Boolean?.get_HasValue() As Boolean"
IL_003a: brfalse.s IL_0045
IL_003c: ldloca.s V_1
IL_003e: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0043: brfalse.s IL_0059
IL_0045: call "Function Module1.GetBool2() As Boolean"
IL_004a: brfalse.s IL_0059
IL_004c: ldloca.s V_1
IL_004e: call "Function Boolean?.get_HasValue() As Boolean"
IL_0053: brfalse.s IL_0059
IL_0055: ldc.i4.2
IL_0056: stloc.0
IL_0057: br.s IL_005b
IL_0059: ldc.i4.3
IL_005a: stloc.0
IL_005b: ldloc.0
IL_005c: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_28()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetBool3() OrElse GetBool3()) OrElse (GetBool3() OrElse GetBool3()) Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 68 (0x44)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_003c
IL_000f: call "Function Module1.GetBool3() As Boolean?"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brtrue.s IL_003c
IL_001e: call "Function Module1.GetBool3() As Boolean?"
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_002b: brtrue.s IL_003c
IL_002d: call "Function Module1.GetBool3() As Boolean?"
IL_0032: stloc.1
IL_0033: ldloca.s V_1
IL_0035: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_003a: brfalse.s IL_0040
IL_003c: ldc.i4.2
IL_003d: stloc.0
IL_003e: br.s IL_0042
IL_0040: ldc.i4.3
IL_0041: stloc.0
IL_0042: ldloc.0
IL_0043: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_29()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetBool3() OrElse GetBool3()) OrElse GetBool3() OrElse GetBool3() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool3() As Boolean?
Return True
End Function
End Module
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 68 (0x44)
.maxstack 1
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetBool3() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_000d: brtrue.s IL_003c
IL_000f: call "Function Module1.GetBool3() As Boolean?"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_001c: brtrue.s IL_003c
IL_001e: call "Function Module1.GetBool3() As Boolean?"
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_002b: brtrue.s IL_003c
IL_002d: call "Function Module1.GetBool3() As Boolean?"
IL_0032: stloc.1
IL_0033: ldloca.s V_1
IL_0035: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_003a: brfalse.s IL_0040
IL_003c: ldc.i4.2
IL_003d: stloc.0
IL_003e: br.s IL_0042
IL_0040: ldc.i4.3
IL_0041: stloc.0
IL_0042: ldloc.0
IL_0043: ret
}
]]>)
End Sub
<Fact>
<WorkItem(38305, "https://github.com/dotnet/roslyn/issues/38305")>
Public Sub BooleanExpression_30()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System.Text
Module Test
Dim builder As New StringBuilder()
Sub Main()
Test()
System.Console.WriteLine("Done")
End Sub
Sub Test()
Dim condition = placeholder
Dim s1 As String = GetResultString(If(condition, " => True", " => False"))
Dim d As System.Linq.Expressions.Expression(Of System.Func(Of String)) = Function() If(placeholder, " => True", " => False")
Dim s2 = GetResultString(d.Compile()())
Dim s3 = GetResultString(If(placeholder, " => True", " => False"))
Verify(d, s1, s2, s3)
End Sub
Private Function GetResultString(result As String) As String
builder.Append(result)
Dim s1 = builder.ToString()
builder.Clear()
Return s1
End Function
Private Sub Verify(d As System.Linq.Expressions.Expression(Of System.Func(Of String)), s1 As String, s2 As String, s3 As String)
If s1 <> s3 Then
System.Console.WriteLine("1 => ")
System.Console.WriteLine(d.ToString())
System.Console.WriteLine(s1)
System.Console.WriteLine(s3)
End If
If s2 <> s3 Then
System.Console.WriteLine("2 => ")
System.Console.WriteLine(d.ToString())
System.Console.WriteLine(s2)
System.Console.WriteLine(s3)
End If
End Sub
Function BooleanTrue(i As Integer) As Boolean
builder.AppendFormat(" BooleanTrue({0})", i)
Return True
End Function
Function BooleanFalse(i As Integer) As Boolean
builder.AppendFormat(" BooleanFalse({0})", i)
Return False
End Function
Function NullableTrue(i As Integer) As Boolean?
builder.AppendFormat(" NullableTrue({0})", i)
Return True
End Function
Function NullableFalse(i As Integer) As Boolean?
builder.AppendFormat(" NullableFalse({0})", i)
Return False
End Function
Function NullableNull(i As Integer) As Boolean?
builder.AppendFormat(" NullableNull({0})", i)
Return Nothing
End Function
End Module
]]></file>
</compilation>
Dim compilation1 = CreateCompilation(source, options:=TestOptions.ReleaseExe)
Dim tree1 = compilation1.SyntaxTrees.Single()
Dim placeholders = tree1.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "placeholder").ToArray()
Assert.Equal(3, placeholders.Length)
Dim nameInInvocation = tree1.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "Test").Single()
Dim invocation = nameInInvocation.Ancestors().OfType(Of ExpressionStatementSyntax)().Single()
Dim testMethod = tree1.GetRoot().DescendantNodes().OfType(Of MethodBlockSyntax)().Where(Function(block) block.SubOrFunctionStatement.Identifier.ValueText = "Test").Single()
Assert.Equal("Test()", invocation.ToString())
Dim enumerator = BooleanExpression_30_Helpers.BuildConditions(2, 2).GetEnumerator()
Const batchSize As Integer = 250
Dim newBlocks = ArrayBuilder(Of MethodBlockSyntax).GetInstance(batchSize)
While enumerator.MoveNext
newBlocks.Clear()
Do
Dim replacement = enumerator.Current
Dim newBlock = testMethod.ReplaceNodes(placeholders, Function(n1, n2) replacement)
newBlock = newBlock.ReplaceToken(newBlock.SubOrFunctionStatement.Identifier, SyntaxFactory.Identifier("Test" + (newBlocks.Count + 1).ToString()))
newBlocks.Add(newBlock)
Loop While newBlocks.Count < batchSize AndAlso enumerator.MoveNext()
Dim newRoot = tree1.GetRoot().ReplaceNode(invocation, Enumerable.Range(1, newBlocks.Count).
Select(Function(i) invocation.ReplaceToken(nameInInvocation.Identifier,
SyntaxFactory.Identifier("Test" + i.ToString()))))
Dim oldBlock = newRoot.DescendantNodes().OfType(Of MethodBlockSyntax)().Where(Function(block) block.SubOrFunctionStatement.Identifier.ValueText = "Test").Single()
newRoot = newRoot.ReplaceNode(oldBlock, newBlocks)
Dim tree2 = newRoot.SyntaxTree
Dim compilation2 = compilation1.ReplaceSyntaxTree(tree1, tree2)
CompileAndVerify(compilation2, expectedOutput:="Done")
End While
newBlocks.Free()
End Sub
Private Class BooleanExpression_30_Helpers
Class TreeNode
Public Left As TreeNode
Public Right As TreeNode
End Class
Public Shared Iterator Function BuildConditions(fromOperators As Integer, toOperators As Integer) As IEnumerable(Of ExpressionSyntax)
For operatorCount = fromOperators To toOperators
For Each shape In Shapes(operatorCount)
For Each operators In OperatorSets(operatorCount)
For Each operands In OperandSets(operatorCount + 1)
Yield BuildCondition(shape, operators, operands)
Next
Next
Next
Next
End Function
Public Shared Function BuildCondition(shape As TreeNode, operators As ImmutableList(Of SyntaxKind), operands As ImmutableList(Of ExpressionSyntax)) As ExpressionSyntax
Dim result = BuildConditionWorker(shape, operators, operands)
Assert.Empty(operators)
Assert.Empty(operands)
Return result
End Function
Private Shared Function BuildConditionWorker(shape As TreeNode, ByRef operators As ImmutableList(Of SyntaxKind), ByRef operands As ImmutableList(Of ExpressionSyntax)) As ExpressionSyntax
If shape Is Nothing Then
Dim result = operands(0)
operands = operands.RemoveAt(0)
Return result
End If
Dim left = BuildConditionWorker(shape.Left, operators, operands)
Dim opKind = operators(0)
operators = operators.RemoveAt(0)
Dim right = BuildConditionWorker(shape.Right, operators, operands)
Return SyntaxFactory.BinaryExpression(
If(opKind = SyntaxKind.OrElseKeyword, SyntaxKind.OrElseExpression, SyntaxKind.AndAlsoExpression),
left, SyntaxFactory.Token(opKind), right)
End Function
''' <summary>
''' Enumerate all possible shapes of binary trees with given amount of nodes in it.
''' </summary>
''' <param name="count"></param>
''' <returns></returns>
Public Shared Iterator Function Shapes(count As Integer) As IEnumerable(Of TreeNode)
Select Case (count)
Case 0
Yield Nothing
Case 1
Yield New TreeNode()
Case Else
For i = 0 To count - 1
For Each leftTree In Shapes(count - 1 - i)
For Each rightTree In Shapes(i)
Yield New TreeNode() With {.Left = leftTree, .Right = rightTree}
Next
Next
Next
End Select
End Function
Shared Iterator Function OperatorSets(count As Integer) As IEnumerable(Of ImmutableList(Of SyntaxKind))
Select Case (count)
Case 0
Yield ImmutableList(Of SyntaxKind).Empty
Case Else
For Each s In OperatorSets(count - 1)
Yield s.Add(SyntaxKind.AndAlsoKeyword)
Yield s.Add(SyntaxKind.OrElseKeyword)
Next
End Select
End Function
Shared Iterator Function OperandSets(count As Integer) As IEnumerable(Of ImmutableList(Of ExpressionSyntax))
Select Case (count)
Case 0
Yield ImmutableList(Of ExpressionSyntax).Empty
Case Else
For Each s In OperandSets(count - 1)
' New Boolean?()
Yield s.Add(SyntaxFactory.ObjectCreationExpression(SyntaxFactory.NullableType(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BooleanKeyword)))))
For Each name In {"BooleanTrue", "BooleanFalse", "NullableTrue", "NullableFalse", "NullableNull"}
Yield s.Add(SyntaxFactory.InvocationExpression(
SyntaxFactory.IdentifierName(name),
SyntaxFactory.ArgumentList(
SyntaxFactory.SeparatedList(Of ArgumentSyntax)(
New ArgumentSyntax() {SyntaxFactory.SimpleArgument(
SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression,
SyntaxFactory.IntegerLiteralToken(count.ToString(),
LiteralBase.Decimal,
TypeCharacter.None,
CType(count, ULong))))}))))
Next
Next
End Select
End Function
End Class
<Fact()>
Public Sub BooleanExpression_31()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetC()?.F Then
Return 2
Else
Return 3
End If
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetC() As C"
IL_0005: dup
IL_0006: brtrue.s IL_000c
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: br.s IL_0011
IL_000c: ldfld "C.F As Boolean"
IL_0011: brfalse.s IL_0017
IL_0013: ldc.i4.2
IL_0014: stloc.0
IL_0015: br.s IL_0019
IL_0017: ldc.i4.3
IL_0018: stloc.0
IL_0019: ldloc.0
IL_001a: ret
}
]]>)
End Sub
<Fact()>
Public Sub BooleanExpression_32()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool1() AndAlso GetC()?.F Then
Return 2
Else
Return 3
End If
End Function
Function GetBool1() As Boolean
Return Nothing
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 34 (0x22)
.maxstack 2
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool1() As Boolean"
IL_0005: brfalse.s IL_001e
IL_0007: call "Function Module1.GetC() As C"
IL_000c: dup
IL_000d: brtrue.s IL_0013
IL_000f: pop
IL_0010: ldc.i4.0
IL_0011: br.s IL_0018
IL_0013: ldfld "C.F As Boolean"
IL_0018: brfalse.s IL_001e
IL_001a: ldc.i4.2
IL_001b: stloc.0
IL_001c: br.s IL_0020
IL_001e: ldc.i4.3
IL_001f: stloc.0
IL_0020: ldloc.0
IL_0021: ret
}
]]>)
End Sub
<Fact()>
Public Sub BooleanExpression_33()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetC()?.F OrElse GetBool1() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool1() As Boolean
Return Nothing
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 34 (0x22)
.maxstack 2
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetC() As C"
IL_0005: dup
IL_0006: brtrue.s IL_000c
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: br.s IL_0011
IL_000c: ldfld "C.F As Boolean"
IL_0011: brtrue.s IL_001a
IL_0013: call "Function Module1.GetBool1() As Boolean"
IL_0018: brfalse.s IL_001e
IL_001a: ldc.i4.2
IL_001b: stloc.0
IL_001c: br.s IL_0020
IL_001e: ldc.i4.3
IL_001f: stloc.0
IL_0020: ldloc.0
IL_0021: ret
}
]]>)
End Sub
<Fact()>
Public Sub BooleanExpression_34()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetBool1() AndAlso GetC()?.F OrElse GetBool2() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool1() As Boolean
Return Nothing
End Function
Function GetBool2() As Boolean
Return Nothing
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 41 (0x29)
.maxstack 2
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetBool1() As Boolean"
IL_0005: brfalse.s IL_001a
IL_0007: call "Function Module1.GetC() As C"
IL_000c: dup
IL_000d: brtrue.s IL_0013
IL_000f: pop
IL_0010: ldc.i4.0
IL_0011: br.s IL_0018
IL_0013: ldfld "C.F As Boolean"
IL_0018: brtrue.s IL_0021
IL_001a: call "Function Module1.GetBool2() As Boolean"
IL_001f: brfalse.s IL_0025
IL_0021: ldc.i4.2
IL_0022: stloc.0
IL_0023: br.s IL_0027
IL_0025: ldc.i4.3
IL_0026: stloc.0
IL_0027: ldloc.0
IL_0028: ret
}
]]>)
End Sub
<Fact()>
Public Sub BooleanExpression_35()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If GetNullable() AndAlso GetC()?.F Then
Return 2
Else
Return 3
End If
End Function
Function GetNullable() As Boolean?
Return Nothing
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetNullable() As Boolean?"
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call "Function Boolean?.get_HasValue() As Boolean"
IL_000d: brfalse.s IL_0018
IL_000f: ldloca.s V_1
IL_0011: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0016: brfalse.s IL_0038
IL_0018: call "Function Module1.GetC() As C"
IL_001d: dup
IL_001e: brtrue.s IL_0024
IL_0020: pop
IL_0021: ldc.i4.0
IL_0022: br.s IL_0029
IL_0024: ldfld "C.F As Boolean"
IL_0029: brfalse.s IL_0038
IL_002b: ldloca.s V_1
IL_002d: call "Function Boolean?.get_HasValue() As Boolean"
IL_0032: brfalse.s IL_0038
IL_0034: ldc.i4.2
IL_0035: stloc.0
IL_0036: br.s IL_003a
IL_0038: ldc.i4.3
IL_0039: stloc.0
IL_003a: ldloc.0
IL_003b: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38306, "https://github.com/dotnet/roslyn/issues/38306")>
Public Sub BooleanExpression_36()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If (GetC()?.F).GetValueOrDefault() AndAlso GetBool1() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool1() As Boolean
Return Nothing
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 55 (0x37)
.maxstack 2
.locals init (Integer V_0, //Test1
Boolean? V_1)
IL_0000: call "Function Module1.GetC() As C"
IL_0005: dup
IL_0006: brtrue.s IL_0014
IL_0008: pop
IL_0009: ldloca.s V_1
IL_000b: initobj "Boolean?"
IL_0011: ldloc.1
IL_0012: br.s IL_001e
IL_0014: ldfld "C.F As Boolean"
IL_0019: newobj "Sub Boolean?..ctor(Boolean)"
IL_001e: stloc.1
IL_001f: ldloca.s V_1
IL_0021: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_0026: brfalse.s IL_0033
IL_0028: call "Function Module1.GetBool1() As Boolean"
IL_002d: brfalse.s IL_0033
IL_002f: ldc.i4.2
IL_0030: stloc.0
IL_0031: br.s IL_0035
IL_0033: ldc.i4.3
IL_0034: stloc.0
IL_0035: ldloc.0
IL_0036: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(38306, "https://github.com/dotnet/roslyn/issues/38306")>
Public Sub BooleanExpression_37()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Module Module1
Sub Main()
End Sub
Function Test1() As Integer
If If(GetC()?.F, False) AndAlso GetBool1() Then
Return 2
Else
Return 3
End If
End Function
Function GetBool1() As Boolean
Return Nothing
End Function
Function GetC() As C
Return Nothing
End Function
End Module
Class C
Public F As Boolean
End Class
]]></file>
</compilation>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 34 (0x22)
.maxstack 2
.locals init (Integer V_0) //Test1
IL_0000: call "Function Module1.GetC() As C"
IL_0005: dup
IL_0006: brtrue.s IL_000c
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: br.s IL_0011
IL_000c: ldfld "C.F As Boolean"
IL_0011: brfalse.s IL_001e
IL_0013: call "Function Module1.GetBool1() As Boolean"
IL_0018: brfalse.s IL_001e
IL_001a: ldc.i4.2
IL_001b: stloc.0
IL_001c: br.s IL_0020
IL_001e: ldc.i4.3
IL_001f: stloc.0
IL_0020: ldloc.0
IL_0021: ret
}
]]>)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Workspaces/Core/Portable/Workspace/Host/Documentation/IDocumentationProviderService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Host
{
internal interface IDocumentationProviderService : IWorkspaceService
{
DocumentationProvider GetDocumentationProvider(string assemblyFullPath);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Host
{
internal interface IDocumentationProviderService : IWorkspaceService
{
DocumentationProvider GetDocumentationProvider(string assemblyFullPath);
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/VisualBasic/Portable/Lowering/StateMachineRewriter/SynthesizedStateMachineMethod.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' This class represents a type symbol for compiler generated implementation methods,
''' the method being implemented is passed as a parameter and is used to build
''' implementation method's parameters, return value type, etc...
''' </summary>
Friend MustInherit Class SynthesizedStateMachineMethod
Inherits SynthesizedMethod
Implements ISynthesizedMethodBodyImplementationSymbol
Private ReadOnly _interfaceMethod As MethodSymbol
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
Private ReadOnly _locations As ImmutableArray(Of Location)
Private ReadOnly _accessibility As Accessibility
Private ReadOnly _generateDebugInfo As Boolean
Private ReadOnly _hasMethodBodyDependency As Boolean
Private ReadOnly _associatedProperty As PropertySymbol
Protected Sub New(stateMachineType As StateMachineTypeSymbol,
name As String,
interfaceMethod As MethodSymbol,
syntax As SyntaxNode,
declaredAccessibility As Accessibility,
generateDebugInfo As Boolean,
hasMethodBodyDependency As Boolean,
Optional associatedProperty As PropertySymbol = Nothing)
MyBase.New(syntax, stateMachineType, name, isShared:=False)
Me._locations = ImmutableArray.Create(syntax.GetLocation())
Me._accessibility = declaredAccessibility
Me._generateDebugInfo = generateDebugInfo
Me._hasMethodBodyDependency = hasMethodBodyDependency
Debug.Assert(Not interfaceMethod.IsGenericMethod)
Me._interfaceMethod = interfaceMethod
Dim params(Me._interfaceMethod.ParameterCount - 1) As ParameterSymbol
For i = 0 To params.Length - 1
Dim curParam = Me._interfaceMethod.Parameters(i)
Debug.Assert(Not curParam.IsOptional)
Debug.Assert(Not curParam.HasExplicitDefaultValue)
params(i) = SynthesizedMethod.WithNewContainerAndType(Me, curParam.Type, curParam)
Next
Me._parameters = params.AsImmutableOrNull()
Me._associatedProperty = associatedProperty
End Sub
Public ReadOnly Property StateMachineType As StateMachineTypeSymbol
Get
Return DirectCast(ContainingSymbol, StateMachineTypeSymbol)
End Get
End Property
Friend Overrides ReadOnly Property TypeMap As TypeSubstitution
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
Return ImmutableArray(Of TypeSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return Me._locations
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return Me._parameters
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return Me._interfaceMethod.ReturnType
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return Me._interfaceMethod.IsSub
End Get
End Property
Public Overrides ReadOnly Property IsVararg As Boolean
Get
Return Me._interfaceMethod.IsVararg
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Me._accessibility
End Get
End Property
Friend Overrides ReadOnly Property ParameterCount As Integer
Get
Return Me._parameters.Length
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
Get
Return ImmutableArray.Create(Me._interfaceMethod)
End Get
End Property
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return Me._associatedProperty
End Get
End Property
Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean
Return True
End Function
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return Me._generateDebugInfo
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Return Me.StateMachineType.KickoffMethod.CalculateLocalSyntaxOffset(localPosition, localTree)
End Function
Public ReadOnly Property HasMethodBodyDependency As Boolean Implements ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency
Get
Return _hasMethodBodyDependency
End Get
End Property
Public ReadOnly Property Method As IMethodSymbolInternal Implements ISynthesizedMethodBodyImplementationSymbol.Method
Get
Return StateMachineType.KickoffMethod
End Get
End Property
End Class
''' <summary>
''' Represents a state machine MoveNext method.
''' Handles special behavior around inheriting some attributes from the original async/iterator method.
''' </summary>
Friend NotInheritable Class SynthesizedStateMachineMoveNextMethod
Inherits SynthesizedStateMachineMethod
Private _attributes As ImmutableArray(Of VisualBasicAttributeData)
Friend Sub New(stateMachineType As StateMachineTypeSymbol,
interfaceMethod As MethodSymbol,
syntax As SyntaxNode,
declaredAccessibility As Accessibility)
MyBase.New(stateMachineType, WellKnownMemberNames.MoveNextMethodName, interfaceMethod, syntax, declaredAccessibility, generateDebugInfo:=True, hasMethodBodyDependency:=True)
End Sub
Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor))
Dim compilation = Me.DeclaringCompilation
AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor))
End Sub
Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
If _attributes.IsDefault Then
Debug.Assert(MyBase.GetAttributes().Length = 0)
Dim builder As ArrayBuilder(Of VisualBasicAttributeData) = Nothing
' Inherit some attributes from the kickoff method
Dim kickoffMethod = StateMachineType.KickoffMethod
For Each attribute In kickoffMethod.GetAttributes()
If attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerHiddenAttribute) OrElse
attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerNonUserCodeAttribute) OrElse
attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerStepperBoundaryAttribute) OrElse
attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerStepThroughAttribute) Then
If builder Is Nothing Then
builder = ArrayBuilder(Of VisualBasicAttributeData).GetInstance(4) ' only 4 different attributes are inherited at the moment
End If
builder.Add(attribute)
End If
Next
ImmutableInterlocked.InterlockedCompareExchange(_attributes,
If(builder Is Nothing, ImmutableArray(Of VisualBasicAttributeData).Empty, builder.ToImmutableAndFree()),
Nothing)
End If
Return _attributes
End Function
End Class
''' <summary>
''' Represents a state machine method other than a MoveNext method.
''' All such methods are considered non-user code.
''' </summary>
Friend NotInheritable Class SynthesizedStateMachineDebuggerNonUserCodeMethod
Inherits SynthesizedStateMachineMethod
Friend Sub New(stateMachineType As StateMachineTypeSymbol,
name As String,
interfaceMethod As MethodSymbol,
syntax As SyntaxNode,
declaredAccessibility As Accessibility,
hasMethodBodyDependency As Boolean,
Optional associatedProperty As PropertySymbol = Nothing)
MyBase.New(stateMachineType, name, interfaceMethod, syntax, declaredAccessibility, generateDebugInfo:=False,
hasMethodBodyDependency:=hasMethodBodyDependency, associatedProperty:=associatedProperty)
End Sub
Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor))
Dim compilation = Me.DeclaringCompilation
AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerNonUserCodeAttribute())
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' This class represents a type symbol for compiler generated implementation methods,
''' the method being implemented is passed as a parameter and is used to build
''' implementation method's parameters, return value type, etc...
''' </summary>
Friend MustInherit Class SynthesizedStateMachineMethod
Inherits SynthesizedMethod
Implements ISynthesizedMethodBodyImplementationSymbol
Private ReadOnly _interfaceMethod As MethodSymbol
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
Private ReadOnly _locations As ImmutableArray(Of Location)
Private ReadOnly _accessibility As Accessibility
Private ReadOnly _generateDebugInfo As Boolean
Private ReadOnly _hasMethodBodyDependency As Boolean
Private ReadOnly _associatedProperty As PropertySymbol
Protected Sub New(stateMachineType As StateMachineTypeSymbol,
name As String,
interfaceMethod As MethodSymbol,
syntax As SyntaxNode,
declaredAccessibility As Accessibility,
generateDebugInfo As Boolean,
hasMethodBodyDependency As Boolean,
Optional associatedProperty As PropertySymbol = Nothing)
MyBase.New(syntax, stateMachineType, name, isShared:=False)
Me._locations = ImmutableArray.Create(syntax.GetLocation())
Me._accessibility = declaredAccessibility
Me._generateDebugInfo = generateDebugInfo
Me._hasMethodBodyDependency = hasMethodBodyDependency
Debug.Assert(Not interfaceMethod.IsGenericMethod)
Me._interfaceMethod = interfaceMethod
Dim params(Me._interfaceMethod.ParameterCount - 1) As ParameterSymbol
For i = 0 To params.Length - 1
Dim curParam = Me._interfaceMethod.Parameters(i)
Debug.Assert(Not curParam.IsOptional)
Debug.Assert(Not curParam.HasExplicitDefaultValue)
params(i) = SynthesizedMethod.WithNewContainerAndType(Me, curParam.Type, curParam)
Next
Me._parameters = params.AsImmutableOrNull()
Me._associatedProperty = associatedProperty
End Sub
Public ReadOnly Property StateMachineType As StateMachineTypeSymbol
Get
Return DirectCast(ContainingSymbol, StateMachineTypeSymbol)
End Get
End Property
Friend Overrides ReadOnly Property TypeMap As TypeSubstitution
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
Return ImmutableArray(Of TypeSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return Me._locations
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return Me._parameters
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return Me._interfaceMethod.ReturnType
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return Me._interfaceMethod.IsSub
End Get
End Property
Public Overrides ReadOnly Property IsVararg As Boolean
Get
Return Me._interfaceMethod.IsVararg
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Me._accessibility
End Get
End Property
Friend Overrides ReadOnly Property ParameterCount As Integer
Get
Return Me._parameters.Length
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
Get
Return ImmutableArray.Create(Me._interfaceMethod)
End Get
End Property
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return Me._associatedProperty
End Get
End Property
Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean
Return True
End Function
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return Me._generateDebugInfo
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Return Me.StateMachineType.KickoffMethod.CalculateLocalSyntaxOffset(localPosition, localTree)
End Function
Public ReadOnly Property HasMethodBodyDependency As Boolean Implements ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency
Get
Return _hasMethodBodyDependency
End Get
End Property
Public ReadOnly Property Method As IMethodSymbolInternal Implements ISynthesizedMethodBodyImplementationSymbol.Method
Get
Return StateMachineType.KickoffMethod
End Get
End Property
End Class
''' <summary>
''' Represents a state machine MoveNext method.
''' Handles special behavior around inheriting some attributes from the original async/iterator method.
''' </summary>
Friend NotInheritable Class SynthesizedStateMachineMoveNextMethod
Inherits SynthesizedStateMachineMethod
Private _attributes As ImmutableArray(Of VisualBasicAttributeData)
Friend Sub New(stateMachineType As StateMachineTypeSymbol,
interfaceMethod As MethodSymbol,
syntax As SyntaxNode,
declaredAccessibility As Accessibility)
MyBase.New(stateMachineType, WellKnownMemberNames.MoveNextMethodName, interfaceMethod, syntax, declaredAccessibility, generateDebugInfo:=True, hasMethodBodyDependency:=True)
End Sub
Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor))
Dim compilation = Me.DeclaringCompilation
AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor))
End Sub
Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
If _attributes.IsDefault Then
Debug.Assert(MyBase.GetAttributes().Length = 0)
Dim builder As ArrayBuilder(Of VisualBasicAttributeData) = Nothing
' Inherit some attributes from the kickoff method
Dim kickoffMethod = StateMachineType.KickoffMethod
For Each attribute In kickoffMethod.GetAttributes()
If attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerHiddenAttribute) OrElse
attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerNonUserCodeAttribute) OrElse
attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerStepperBoundaryAttribute) OrElse
attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerStepThroughAttribute) Then
If builder Is Nothing Then
builder = ArrayBuilder(Of VisualBasicAttributeData).GetInstance(4) ' only 4 different attributes are inherited at the moment
End If
builder.Add(attribute)
End If
Next
ImmutableInterlocked.InterlockedCompareExchange(_attributes,
If(builder Is Nothing, ImmutableArray(Of VisualBasicAttributeData).Empty, builder.ToImmutableAndFree()),
Nothing)
End If
Return _attributes
End Function
End Class
''' <summary>
''' Represents a state machine method other than a MoveNext method.
''' All such methods are considered non-user code.
''' </summary>
Friend NotInheritable Class SynthesizedStateMachineDebuggerNonUserCodeMethod
Inherits SynthesizedStateMachineMethod
Friend Sub New(stateMachineType As StateMachineTypeSymbol,
name As String,
interfaceMethod As MethodSymbol,
syntax As SyntaxNode,
declaredAccessibility As Accessibility,
hasMethodBodyDependency As Boolean,
Optional associatedProperty As PropertySymbol = Nothing)
MyBase.New(stateMachineType, name, interfaceMethod, syntax, declaredAccessibility, generateDebugInfo:=False,
hasMethodBodyDependency:=hasMethodBodyDependency, associatedProperty:=associatedProperty)
End Sub
Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor))
Dim compilation = Me.DeclaringCompilation
AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerNonUserCodeAttribute())
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Features/CSharp/Portable/Completion/CompletionProviders/XmlDocCommentCompletionProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
using static DocumentationCommentXmlNames;
[ExportCompletionProvider(nameof(XmlDocCommentCompletionProvider), LanguageNames.CSharp)]
[ExtensionOrder(After = nameof(PartialTypeCompletionProvider))]
[Shared]
internal partial class XmlDocCommentCompletionProvider : AbstractDocCommentCompletionProvider<DocumentationCommentTriviaSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlDocCommentCompletionProvider() : base(s_defaultRules)
{
}
public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options)
{
var c = text[characterPosition];
return c == '<' || c == '"' || CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options);
}
public override ImmutableHashSet<char> TriggerCharacters { get; } = ImmutableHashSet.Create('<', '"', ' ');
protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(
Document document, int position,
CompletionTrigger trigger, CancellationToken cancellationToken)
{
try
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken);
var parentTrivia = token.GetAncestor<DocumentationCommentTriviaSyntax>();
if (parentTrivia == null)
{
return null;
}
var attachedToken = parentTrivia.ParentTrivia.Token;
if (attachedToken.Kind() == SyntaxKind.None)
{
return null;
}
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(false);
ISymbol declaredSymbol = null;
var memberDeclaration = attachedToken.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null)
{
declaredSymbol = semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken);
}
else
{
var typeDeclaration = attachedToken.GetAncestor<TypeDeclarationSyntax>();
if (typeDeclaration != null)
{
declaredSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken);
}
}
if (IsAttributeNameContext(token, position, out var elementName, out var existingAttributes))
{
return GetAttributeItems(elementName, existingAttributes);
}
var wasTriggeredAfterSpace = trigger.Kind == CompletionTriggerKind.Insertion && trigger.Character == ' ';
if (wasTriggeredAfterSpace)
{
// Nothing below this point should triggered by a space character
// (only attribute names should be triggered by <SPACE>)
return null;
}
if (IsAttributeValueContext(token, out elementName, out var attributeName))
{
return GetAttributeValueItems(declaredSymbol, elementName, attributeName);
}
if (trigger.Kind == CompletionTriggerKind.Insertion && trigger.Character != '<')
{
// With the use of IsTriggerAfterSpaceOrStartOfWordCharacter, the code below is much
// too aggressive at suggesting tags, so exit early before degrading the experience
return null;
}
var items = new List<CompletionItem>();
if (token.Parent.Kind() == SyntaxKind.XmlEmptyElement || token.Parent.Kind() == SyntaxKind.XmlText ||
(token.Parent.IsKind(SyntaxKind.XmlElementEndTag) && token.IsKind(SyntaxKind.GreaterThanToken)) ||
(token.Parent.IsKind(SyntaxKind.XmlName) && token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement)))
{
// The user is typing inside an XmlElement
if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement ||
token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement))
{
// Avoid including language keywords when following < or <text, since these cases should only be
// attempting to complete the XML name (which for language keywords is 'see'). While the parser
// treats the 'name' in '< name' as an XML name, we don't treat it like that here so the completion
// experience is consistent for '< ' and '< n'.
var xmlNameOnly = token.IsKind(SyntaxKind.LessThanToken)
|| (token.Parent.IsKind(SyntaxKind.XmlName) && !token.HasLeadingTrivia);
var includeKeywords = !xmlNameOnly;
items.AddRange(GetNestedItems(declaredSymbol, includeKeywords));
}
if (token.Parent.Parent is XmlElementSyntax xmlElement)
{
AddXmlElementItems(items, xmlElement.StartTag);
}
if (token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement) &&
token.Parent.Parent.Parent is XmlElementSyntax nestedXmlElement)
{
AddXmlElementItems(items, nestedXmlElement.StartTag);
}
if (token.Parent.Parent is DocumentationCommentTriviaSyntax ||
(token.Parent.Parent.IsKind(SyntaxKind.XmlEmptyElement) && token.Parent.Parent.Parent is DocumentationCommentTriviaSyntax))
{
items.AddRange(GetTopLevelItems(declaredSymbol, parentTrivia));
}
}
if (token.Parent is XmlElementStartTagSyntax startTag &&
token == startTag.GreaterThanToken)
{
AddXmlElementItems(items, startTag);
}
items.AddRange(GetAlwaysVisibleItems());
return items;
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return SpecializedCollections.EmptyEnumerable<CompletionItem>();
}
}
private void AddXmlElementItems(List<CompletionItem> items, XmlElementStartTagSyntax startTag)
{
var xmlElementName = startTag.Name.LocalName.ValueText;
if (xmlElementName == ListElementName)
{
items.AddRange(GetListItems());
}
else if (xmlElementName == ListHeaderElementName)
{
items.AddRange(GetListHeaderItems());
}
else if (xmlElementName == ItemElementName)
{
items.AddRange(GetItemTagItems());
}
}
private bool IsAttributeNameContext(SyntaxToken token, int position, out string elementName, out ISet<string> attributeNames)
{
elementName = null;
if (token.IsKind(SyntaxKind.XmlTextLiteralToken) && string.IsNullOrWhiteSpace(token.Text))
{
// Unlike VB, the C# lexer has a preference for leading trivia. In the following example...
//
// /// <exception $$
//
// ...the trailing whitespace will not be attached as trivia to any node. Instead it will
// be treated as an independent XmlTextLiteralToken, so skip backwards by one token.
token = token.GetPreviousToken();
}
// Handle the <elem$$ case by going back one token (the subsequent checks need to account for this)
token = token.GetPreviousTokenIfTouchingWord(position);
var attributes = default(SyntaxList<XmlAttributeSyntax>);
if (token.IsKind(SyntaxKind.IdentifierToken) && token.Parent.IsKind(SyntaxKind.XmlName))
{
// <elem $$
// <elem attr$$
(elementName, attributes) = GetElementNameAndAttributes(token.Parent.Parent);
}
else if (token.Parent.IsKind(SyntaxKind.XmlCrefAttribute, out XmlAttributeSyntax attributeSyntax) ||
token.Parent.IsKind(SyntaxKind.XmlNameAttribute, out attributeSyntax) ||
token.Parent.IsKind(SyntaxKind.XmlTextAttribute, out attributeSyntax))
{
// In the following, 'attr1' may be a regular text attribute, or one of the special 'cref' or 'name' attributes
// <elem attr1="" $$
// <elem attr1="" $$attr2
// <elem attr1="" attr2$$
if (token == attributeSyntax.EndQuoteToken)
{
(elementName, attributes) = GetElementNameAndAttributes(attributeSyntax.Parent);
}
}
attributeNames = attributes.Select(GetAttributeName).ToSet();
return elementName != null;
}
private (string name, SyntaxList<XmlAttributeSyntax> attributes) GetElementNameAndAttributes(SyntaxNode node)
{
XmlNameSyntax nameSyntax;
SyntaxList<XmlAttributeSyntax> attributes;
switch (node)
{
// Self contained empty element <tag />
case XmlEmptyElementSyntax emptyElementSyntax:
nameSyntax = emptyElementSyntax.Name;
attributes = emptyElementSyntax.Attributes;
break;
// Parent node of a non-empty element: <tag></tag>
case XmlElementSyntax elementSyntax:
// Defer to the start-tag logic
return GetElementNameAndAttributes(elementSyntax.StartTag);
// Start tag of a non-empty element: <tag>
case XmlElementStartTagSyntax startTagSyntax:
nameSyntax = startTagSyntax.Name;
attributes = startTagSyntax.Attributes;
break;
default:
nameSyntax = null;
attributes = default;
break;
}
return (name: nameSyntax?.LocalName.ValueText, attributes);
}
private static bool IsAttributeValueContext(SyntaxToken token, out string tagName, out string attributeName)
{
XmlAttributeSyntax attributeSyntax;
if (token.Parent.IsKind(SyntaxKind.IdentifierName) &&
token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute, out XmlNameAttributeSyntax xmlName))
{
// Handle the special 'name' attributes: name="bar$$
attributeSyntax = xmlName;
}
else if (token.IsKind(SyntaxKind.XmlTextLiteralToken) &&
token.Parent.IsKind(SyntaxKind.XmlTextAttribute, out XmlTextAttributeSyntax xmlText))
{
// Handle the other general text attributes: foo="bar$$
attributeSyntax = xmlText;
}
else if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute, out attributeSyntax) ||
token.Parent.IsKind(SyntaxKind.XmlTextAttribute, out attributeSyntax))
{
// When there's no attribute value yet, the parent attribute is returned:
// name="$$
// foo="$$
if (token != attributeSyntax.StartQuoteToken)
{
attributeSyntax = null;
}
}
if (attributeSyntax != null)
{
attributeName = attributeSyntax.Name.LocalName.ValueText;
var emptyElement = attributeSyntax.GetAncestor<XmlEmptyElementSyntax>();
if (emptyElement != null)
{
// Empty element tags: <tag attr=... />
tagName = emptyElement.Name.LocalName.Text;
return true;
}
var startTagSyntax = token.GetAncestor<XmlElementStartTagSyntax>();
if (startTagSyntax != null)
{
// Non-empty element start tags: <tag attr=... >
tagName = startTagSyntax.Name.LocalName.Text;
return true;
}
}
attributeName = null;
tagName = null;
return false;
}
protected override IEnumerable<string> GetKeywordNames()
{
yield return SyntaxFacts.GetText(SyntaxKind.NullKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.StaticKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.VirtualKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.TrueKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.FalseKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.AbstractKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.SealedKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.AsyncKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.AwaitKeyword);
}
protected override IEnumerable<string> GetExistingTopLevelElementNames(DocumentationCommentTriviaSyntax syntax) =>
syntax.Content.Select(GetElementName).WhereNotNull();
protected override IEnumerable<string> GetExistingTopLevelAttributeValues(DocumentationCommentTriviaSyntax syntax, string elementName, string attributeName)
{
var attributeValues = SpecializedCollections.EmptyEnumerable<string>();
foreach (var node in syntax.Content)
{
(var name, var attributes) = GetElementNameAndAttributes(node);
if (name == elementName)
{
attributeValues = attributeValues.Concat(
attributes.Where(attribute => GetAttributeName(attribute) == attributeName)
.Select(GetAttributeValue));
}
}
return attributeValues;
}
private string GetElementName(XmlNodeSyntax node) => GetElementNameAndAttributes(node).name;
private string GetAttributeName(XmlAttributeSyntax attribute) => attribute.Name.LocalName.ValueText;
private string GetAttributeValue(XmlAttributeSyntax attribute)
{
switch (attribute)
{
case XmlTextAttributeSyntax textAttribute:
// Decode any XML enities and concatentate the results
return textAttribute.TextTokens.GetValueText();
case XmlNameAttributeSyntax nameAttribute:
return nameAttribute.Identifier.Identifier.ValueText;
default:
return null;
}
}
protected override ImmutableArray<IParameterSymbol> GetParameters(ISymbol declarationSymbol)
{
var declaredParameters = declarationSymbol.GetParameters();
if (declarationSymbol is INamedTypeSymbol namedTypeSymbol &&
namedTypeSymbol.TryGetRecordPrimaryConstructor(out var primaryConstructor))
{
declaredParameters = primaryConstructor.Parameters;
}
return declaredParameters;
}
private static readonly CompletionItemRules s_defaultRules =
CompletionItemRules.Create(
filterCharacterRules: FilterRules,
commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Add, '>', '\t')),
enterKeyRule: EnterKeyRule.Never);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
using static DocumentationCommentXmlNames;
[ExportCompletionProvider(nameof(XmlDocCommentCompletionProvider), LanguageNames.CSharp)]
[ExtensionOrder(After = nameof(PartialTypeCompletionProvider))]
[Shared]
internal partial class XmlDocCommentCompletionProvider : AbstractDocCommentCompletionProvider<DocumentationCommentTriviaSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlDocCommentCompletionProvider() : base(s_defaultRules)
{
}
public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options)
{
var c = text[characterPosition];
return c == '<' || c == '"' || CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options);
}
public override ImmutableHashSet<char> TriggerCharacters { get; } = ImmutableHashSet.Create('<', '"', ' ');
protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(
Document document, int position,
CompletionTrigger trigger, CancellationToken cancellationToken)
{
try
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken);
var parentTrivia = token.GetAncestor<DocumentationCommentTriviaSyntax>();
if (parentTrivia == null)
{
return null;
}
var attachedToken = parentTrivia.ParentTrivia.Token;
if (attachedToken.Kind() == SyntaxKind.None)
{
return null;
}
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(false);
ISymbol declaredSymbol = null;
var memberDeclaration = attachedToken.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null)
{
declaredSymbol = semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken);
}
else
{
var typeDeclaration = attachedToken.GetAncestor<TypeDeclarationSyntax>();
if (typeDeclaration != null)
{
declaredSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken);
}
}
if (IsAttributeNameContext(token, position, out var elementName, out var existingAttributes))
{
return GetAttributeItems(elementName, existingAttributes);
}
var wasTriggeredAfterSpace = trigger.Kind == CompletionTriggerKind.Insertion && trigger.Character == ' ';
if (wasTriggeredAfterSpace)
{
// Nothing below this point should triggered by a space character
// (only attribute names should be triggered by <SPACE>)
return null;
}
if (IsAttributeValueContext(token, out elementName, out var attributeName))
{
return GetAttributeValueItems(declaredSymbol, elementName, attributeName);
}
if (trigger.Kind == CompletionTriggerKind.Insertion && trigger.Character != '<')
{
// With the use of IsTriggerAfterSpaceOrStartOfWordCharacter, the code below is much
// too aggressive at suggesting tags, so exit early before degrading the experience
return null;
}
var items = new List<CompletionItem>();
if (token.Parent.Kind() == SyntaxKind.XmlEmptyElement || token.Parent.Kind() == SyntaxKind.XmlText ||
(token.Parent.IsKind(SyntaxKind.XmlElementEndTag) && token.IsKind(SyntaxKind.GreaterThanToken)) ||
(token.Parent.IsKind(SyntaxKind.XmlName) && token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement)))
{
// The user is typing inside an XmlElement
if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement ||
token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement))
{
// Avoid including language keywords when following < or <text, since these cases should only be
// attempting to complete the XML name (which for language keywords is 'see'). While the parser
// treats the 'name' in '< name' as an XML name, we don't treat it like that here so the completion
// experience is consistent for '< ' and '< n'.
var xmlNameOnly = token.IsKind(SyntaxKind.LessThanToken)
|| (token.Parent.IsKind(SyntaxKind.XmlName) && !token.HasLeadingTrivia);
var includeKeywords = !xmlNameOnly;
items.AddRange(GetNestedItems(declaredSymbol, includeKeywords));
}
if (token.Parent.Parent is XmlElementSyntax xmlElement)
{
AddXmlElementItems(items, xmlElement.StartTag);
}
if (token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement) &&
token.Parent.Parent.Parent is XmlElementSyntax nestedXmlElement)
{
AddXmlElementItems(items, nestedXmlElement.StartTag);
}
if (token.Parent.Parent is DocumentationCommentTriviaSyntax ||
(token.Parent.Parent.IsKind(SyntaxKind.XmlEmptyElement) && token.Parent.Parent.Parent is DocumentationCommentTriviaSyntax))
{
items.AddRange(GetTopLevelItems(declaredSymbol, parentTrivia));
}
}
if (token.Parent is XmlElementStartTagSyntax startTag &&
token == startTag.GreaterThanToken)
{
AddXmlElementItems(items, startTag);
}
items.AddRange(GetAlwaysVisibleItems());
return items;
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return SpecializedCollections.EmptyEnumerable<CompletionItem>();
}
}
private void AddXmlElementItems(List<CompletionItem> items, XmlElementStartTagSyntax startTag)
{
var xmlElementName = startTag.Name.LocalName.ValueText;
if (xmlElementName == ListElementName)
{
items.AddRange(GetListItems());
}
else if (xmlElementName == ListHeaderElementName)
{
items.AddRange(GetListHeaderItems());
}
else if (xmlElementName == ItemElementName)
{
items.AddRange(GetItemTagItems());
}
}
private bool IsAttributeNameContext(SyntaxToken token, int position, out string elementName, out ISet<string> attributeNames)
{
elementName = null;
if (token.IsKind(SyntaxKind.XmlTextLiteralToken) && string.IsNullOrWhiteSpace(token.Text))
{
// Unlike VB, the C# lexer has a preference for leading trivia. In the following example...
//
// /// <exception $$
//
// ...the trailing whitespace will not be attached as trivia to any node. Instead it will
// be treated as an independent XmlTextLiteralToken, so skip backwards by one token.
token = token.GetPreviousToken();
}
// Handle the <elem$$ case by going back one token (the subsequent checks need to account for this)
token = token.GetPreviousTokenIfTouchingWord(position);
var attributes = default(SyntaxList<XmlAttributeSyntax>);
if (token.IsKind(SyntaxKind.IdentifierToken) && token.Parent.IsKind(SyntaxKind.XmlName))
{
// <elem $$
// <elem attr$$
(elementName, attributes) = GetElementNameAndAttributes(token.Parent.Parent);
}
else if (token.Parent.IsKind(SyntaxKind.XmlCrefAttribute, out XmlAttributeSyntax attributeSyntax) ||
token.Parent.IsKind(SyntaxKind.XmlNameAttribute, out attributeSyntax) ||
token.Parent.IsKind(SyntaxKind.XmlTextAttribute, out attributeSyntax))
{
// In the following, 'attr1' may be a regular text attribute, or one of the special 'cref' or 'name' attributes
// <elem attr1="" $$
// <elem attr1="" $$attr2
// <elem attr1="" attr2$$
if (token == attributeSyntax.EndQuoteToken)
{
(elementName, attributes) = GetElementNameAndAttributes(attributeSyntax.Parent);
}
}
attributeNames = attributes.Select(GetAttributeName).ToSet();
return elementName != null;
}
private (string name, SyntaxList<XmlAttributeSyntax> attributes) GetElementNameAndAttributes(SyntaxNode node)
{
XmlNameSyntax nameSyntax;
SyntaxList<XmlAttributeSyntax> attributes;
switch (node)
{
// Self contained empty element <tag />
case XmlEmptyElementSyntax emptyElementSyntax:
nameSyntax = emptyElementSyntax.Name;
attributes = emptyElementSyntax.Attributes;
break;
// Parent node of a non-empty element: <tag></tag>
case XmlElementSyntax elementSyntax:
// Defer to the start-tag logic
return GetElementNameAndAttributes(elementSyntax.StartTag);
// Start tag of a non-empty element: <tag>
case XmlElementStartTagSyntax startTagSyntax:
nameSyntax = startTagSyntax.Name;
attributes = startTagSyntax.Attributes;
break;
default:
nameSyntax = null;
attributes = default;
break;
}
return (name: nameSyntax?.LocalName.ValueText, attributes);
}
private static bool IsAttributeValueContext(SyntaxToken token, out string tagName, out string attributeName)
{
XmlAttributeSyntax attributeSyntax;
if (token.Parent.IsKind(SyntaxKind.IdentifierName) &&
token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute, out XmlNameAttributeSyntax xmlName))
{
// Handle the special 'name' attributes: name="bar$$
attributeSyntax = xmlName;
}
else if (token.IsKind(SyntaxKind.XmlTextLiteralToken) &&
token.Parent.IsKind(SyntaxKind.XmlTextAttribute, out XmlTextAttributeSyntax xmlText))
{
// Handle the other general text attributes: foo="bar$$
attributeSyntax = xmlText;
}
else if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute, out attributeSyntax) ||
token.Parent.IsKind(SyntaxKind.XmlTextAttribute, out attributeSyntax))
{
// When there's no attribute value yet, the parent attribute is returned:
// name="$$
// foo="$$
if (token != attributeSyntax.StartQuoteToken)
{
attributeSyntax = null;
}
}
if (attributeSyntax != null)
{
attributeName = attributeSyntax.Name.LocalName.ValueText;
var emptyElement = attributeSyntax.GetAncestor<XmlEmptyElementSyntax>();
if (emptyElement != null)
{
// Empty element tags: <tag attr=... />
tagName = emptyElement.Name.LocalName.Text;
return true;
}
var startTagSyntax = token.GetAncestor<XmlElementStartTagSyntax>();
if (startTagSyntax != null)
{
// Non-empty element start tags: <tag attr=... >
tagName = startTagSyntax.Name.LocalName.Text;
return true;
}
}
attributeName = null;
tagName = null;
return false;
}
protected override IEnumerable<string> GetKeywordNames()
{
yield return SyntaxFacts.GetText(SyntaxKind.NullKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.StaticKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.VirtualKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.TrueKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.FalseKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.AbstractKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.SealedKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.AsyncKeyword);
yield return SyntaxFacts.GetText(SyntaxKind.AwaitKeyword);
}
protected override IEnumerable<string> GetExistingTopLevelElementNames(DocumentationCommentTriviaSyntax syntax) =>
syntax.Content.Select(GetElementName).WhereNotNull();
protected override IEnumerable<string> GetExistingTopLevelAttributeValues(DocumentationCommentTriviaSyntax syntax, string elementName, string attributeName)
{
var attributeValues = SpecializedCollections.EmptyEnumerable<string>();
foreach (var node in syntax.Content)
{
(var name, var attributes) = GetElementNameAndAttributes(node);
if (name == elementName)
{
attributeValues = attributeValues.Concat(
attributes.Where(attribute => GetAttributeName(attribute) == attributeName)
.Select(GetAttributeValue));
}
}
return attributeValues;
}
private string GetElementName(XmlNodeSyntax node) => GetElementNameAndAttributes(node).name;
private string GetAttributeName(XmlAttributeSyntax attribute) => attribute.Name.LocalName.ValueText;
private string GetAttributeValue(XmlAttributeSyntax attribute)
{
switch (attribute)
{
case XmlTextAttributeSyntax textAttribute:
// Decode any XML enities and concatentate the results
return textAttribute.TextTokens.GetValueText();
case XmlNameAttributeSyntax nameAttribute:
return nameAttribute.Identifier.Identifier.ValueText;
default:
return null;
}
}
protected override ImmutableArray<IParameterSymbol> GetParameters(ISymbol declarationSymbol)
{
var declaredParameters = declarationSymbol.GetParameters();
if (declarationSymbol is INamedTypeSymbol namedTypeSymbol &&
namedTypeSymbol.TryGetRecordPrimaryConstructor(out var primaryConstructor))
{
declaredParameters = primaryConstructor.Parameters;
}
return declaredParameters;
}
private static readonly CompletionItemRules s_defaultRules =
CompletionItemRules.Create(
filterCharacterRules: FilterRules,
commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Add, '>', '\t')),
enterKeyRule: EnterKeyRule.Never);
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/Core/Portable/DiagnosticAnalyzer/ShadowCopyAnalyzerAssemblyLoader.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis
{
internal sealed class ShadowCopyAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader
{
/// <summary>
/// The base directory for shadow copies. Each instance of
/// <see cref="ShadowCopyAnalyzerAssemblyLoader"/> gets its own
/// subdirectory under this directory. This is also the starting point
/// for scavenge operations.
/// </summary>
private readonly string _baseDirectory;
internal readonly Task DeleteLeftoverDirectoriesTask;
/// <summary>
/// The directory where this instance of <see cref="ShadowCopyAnalyzerAssemblyLoader"/>
/// will shadow-copy assemblies, and the mutex created to mark that the owner of it is still active.
/// </summary>
private readonly Lazy<(string directory, Mutex)> _shadowCopyDirectoryAndMutex;
/// <summary>
/// Used to generate unique names for per-assembly directories. Should be updated with <see cref="Interlocked.Increment(ref int)"/>.
/// </summary>
private int _assemblyDirectoryId;
public ShadowCopyAnalyzerAssemblyLoader(string baseDirectory = null)
{
if (baseDirectory != null)
{
_baseDirectory = baseDirectory;
}
else
{
_baseDirectory = Path.Combine(Path.GetTempPath(), "CodeAnalysis", "AnalyzerShadowCopies");
}
_shadowCopyDirectoryAndMutex = new Lazy<(string directory, Mutex)>(
() => CreateUniqueDirectoryForProcess(), LazyThreadSafetyMode.ExecutionAndPublication);
DeleteLeftoverDirectoriesTask = Task.Run((Action)DeleteLeftoverDirectories);
}
private void DeleteLeftoverDirectories()
{
// Avoid first chance exception
if (!Directory.Exists(_baseDirectory))
return;
IEnumerable<string> subDirectories;
try
{
subDirectories = Directory.EnumerateDirectories(_baseDirectory);
}
catch (DirectoryNotFoundException)
{
return;
}
foreach (var subDirectory in subDirectories)
{
string name = Path.GetFileName(subDirectory).ToLowerInvariant();
Mutex mutex = null;
try
{
// We only want to try deleting the directory if no-one else is currently
// using it. That is, if there is no corresponding mutex.
if (!Mutex.TryOpenExisting(name, out mutex))
{
ClearReadOnlyFlagOnFiles(subDirectory);
Directory.Delete(subDirectory, recursive: true);
}
}
catch
{
// If something goes wrong we will leave it to the next run to clean up.
// Just swallow the exception and move on.
}
finally
{
if (mutex != null)
{
mutex.Dispose();
}
}
}
}
protected override Assembly LoadImpl(string fullPath)
{
string assemblyDirectory = CreateUniqueDirectoryForAssembly();
string shadowCopyPath = CopyFileAndResources(fullPath, assemblyDirectory);
return base.LoadImpl(shadowCopyPath);
}
private static string CopyFileAndResources(string fullPath, string assemblyDirectory)
{
string fileNameWithExtension = Path.GetFileName(fullPath);
string shadowCopyPath = Path.Combine(assemblyDirectory, fileNameWithExtension);
CopyFile(fullPath, shadowCopyPath);
string originalDirectory = Path.GetDirectoryName(fullPath);
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithExtension);
string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources";
string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll";
foreach (var directory in Directory.EnumerateDirectories(originalDirectory))
{
string directoryName = Path.GetFileName(directory);
string resourcesPath = Path.Combine(directory, resourcesNameWithExtension);
if (File.Exists(resourcesPath))
{
string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithExtension);
CopyFile(resourcesPath, resourcesShadowCopyPath);
}
resourcesPath = Path.Combine(directory, resourcesNameWithoutExtension, resourcesNameWithExtension);
if (File.Exists(resourcesPath))
{
string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithoutExtension, resourcesNameWithExtension);
CopyFile(resourcesPath, resourcesShadowCopyPath);
}
}
return shadowCopyPath;
}
private static void CopyFile(string originalPath, string shadowCopyPath)
{
var directory = Path.GetDirectoryName(shadowCopyPath);
Directory.CreateDirectory(directory);
File.Copy(originalPath, shadowCopyPath);
ClearReadOnlyFlagOnFile(new FileInfo(shadowCopyPath));
}
private static void ClearReadOnlyFlagOnFiles(string directoryPath)
{
DirectoryInfo directory = new DirectoryInfo(directoryPath);
foreach (var file in directory.EnumerateFiles(searchPattern: "*", searchOption: SearchOption.AllDirectories))
{
ClearReadOnlyFlagOnFile(file);
}
}
private static void ClearReadOnlyFlagOnFile(FileInfo fileInfo)
{
try
{
if (fileInfo.IsReadOnly)
{
fileInfo.IsReadOnly = false;
}
}
catch
{
// There are many reasons this could fail. Ignore it and keep going.
}
}
private string CreateUniqueDirectoryForAssembly()
{
int directoryId = Interlocked.Increment(ref _assemblyDirectoryId);
string directory = Path.Combine(_shadowCopyDirectoryAndMutex.Value.directory, directoryId.ToString());
Directory.CreateDirectory(directory);
return directory;
}
private (string directory, Mutex mutex) CreateUniqueDirectoryForProcess()
{
string guid = Guid.NewGuid().ToString("N").ToLowerInvariant();
string directory = Path.Combine(_baseDirectory, guid);
var mutex = new Mutex(initiallyOwned: false, name: guid);
Directory.CreateDirectory(directory);
return (directory, mutex);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis
{
internal sealed class ShadowCopyAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader
{
/// <summary>
/// The base directory for shadow copies. Each instance of
/// <see cref="ShadowCopyAnalyzerAssemblyLoader"/> gets its own
/// subdirectory under this directory. This is also the starting point
/// for scavenge operations.
/// </summary>
private readonly string _baseDirectory;
internal readonly Task DeleteLeftoverDirectoriesTask;
/// <summary>
/// The directory where this instance of <see cref="ShadowCopyAnalyzerAssemblyLoader"/>
/// will shadow-copy assemblies, and the mutex created to mark that the owner of it is still active.
/// </summary>
private readonly Lazy<(string directory, Mutex)> _shadowCopyDirectoryAndMutex;
/// <summary>
/// Used to generate unique names for per-assembly directories. Should be updated with <see cref="Interlocked.Increment(ref int)"/>.
/// </summary>
private int _assemblyDirectoryId;
public ShadowCopyAnalyzerAssemblyLoader(string baseDirectory = null)
{
if (baseDirectory != null)
{
_baseDirectory = baseDirectory;
}
else
{
_baseDirectory = Path.Combine(Path.GetTempPath(), "CodeAnalysis", "AnalyzerShadowCopies");
}
_shadowCopyDirectoryAndMutex = new Lazy<(string directory, Mutex)>(
() => CreateUniqueDirectoryForProcess(), LazyThreadSafetyMode.ExecutionAndPublication);
DeleteLeftoverDirectoriesTask = Task.Run((Action)DeleteLeftoverDirectories);
}
private void DeleteLeftoverDirectories()
{
// Avoid first chance exception
if (!Directory.Exists(_baseDirectory))
return;
IEnumerable<string> subDirectories;
try
{
subDirectories = Directory.EnumerateDirectories(_baseDirectory);
}
catch (DirectoryNotFoundException)
{
return;
}
foreach (var subDirectory in subDirectories)
{
string name = Path.GetFileName(subDirectory).ToLowerInvariant();
Mutex mutex = null;
try
{
// We only want to try deleting the directory if no-one else is currently
// using it. That is, if there is no corresponding mutex.
if (!Mutex.TryOpenExisting(name, out mutex))
{
ClearReadOnlyFlagOnFiles(subDirectory);
Directory.Delete(subDirectory, recursive: true);
}
}
catch
{
// If something goes wrong we will leave it to the next run to clean up.
// Just swallow the exception and move on.
}
finally
{
if (mutex != null)
{
mutex.Dispose();
}
}
}
}
protected override Assembly LoadImpl(string fullPath)
{
string assemblyDirectory = CreateUniqueDirectoryForAssembly();
string shadowCopyPath = CopyFileAndResources(fullPath, assemblyDirectory);
return base.LoadImpl(shadowCopyPath);
}
private static string CopyFileAndResources(string fullPath, string assemblyDirectory)
{
string fileNameWithExtension = Path.GetFileName(fullPath);
string shadowCopyPath = Path.Combine(assemblyDirectory, fileNameWithExtension);
CopyFile(fullPath, shadowCopyPath);
string originalDirectory = Path.GetDirectoryName(fullPath);
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithExtension);
string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources";
string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll";
foreach (var directory in Directory.EnumerateDirectories(originalDirectory))
{
string directoryName = Path.GetFileName(directory);
string resourcesPath = Path.Combine(directory, resourcesNameWithExtension);
if (File.Exists(resourcesPath))
{
string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithExtension);
CopyFile(resourcesPath, resourcesShadowCopyPath);
}
resourcesPath = Path.Combine(directory, resourcesNameWithoutExtension, resourcesNameWithExtension);
if (File.Exists(resourcesPath))
{
string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithoutExtension, resourcesNameWithExtension);
CopyFile(resourcesPath, resourcesShadowCopyPath);
}
}
return shadowCopyPath;
}
private static void CopyFile(string originalPath, string shadowCopyPath)
{
var directory = Path.GetDirectoryName(shadowCopyPath);
Directory.CreateDirectory(directory);
File.Copy(originalPath, shadowCopyPath);
ClearReadOnlyFlagOnFile(new FileInfo(shadowCopyPath));
}
private static void ClearReadOnlyFlagOnFiles(string directoryPath)
{
DirectoryInfo directory = new DirectoryInfo(directoryPath);
foreach (var file in directory.EnumerateFiles(searchPattern: "*", searchOption: SearchOption.AllDirectories))
{
ClearReadOnlyFlagOnFile(file);
}
}
private static void ClearReadOnlyFlagOnFile(FileInfo fileInfo)
{
try
{
if (fileInfo.IsReadOnly)
{
fileInfo.IsReadOnly = false;
}
}
catch
{
// There are many reasons this could fail. Ignore it and keep going.
}
}
private string CreateUniqueDirectoryForAssembly()
{
int directoryId = Interlocked.Increment(ref _assemblyDirectoryId);
string directory = Path.Combine(_shadowCopyDirectoryAndMutex.Value.directory, directoryId.ToString());
Directory.CreateDirectory(directory);
return directory;
}
private (string directory, Mutex mutex) CreateUniqueDirectoryForProcess()
{
string guid = Guid.NewGuid().ToString("N").ToLowerInvariant();
string directory = Path.Combine(_baseDirectory, guid);
var mutex = new Mutex(initiallyOwned: false, name: guid);
Directory.CreateDirectory(directory);
return (directory, mutex);
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/VisualStudio/Core/Def/ID.InteractiveCommands.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.VisualStudio.LanguageServices
{
internal static partial class ID
{
internal static class InteractiveCommands
{
public const int InteractiveToolWindow = 0x0001;
public const int ResetInteractiveFromProject = 0x0002;
// TODO: Remove pending https://github.com/dotnet/roslyn/issues/8927 .
public const int ExecuteInInteractiveWindow = 0x0010C;
public const string CSharpInteractiveCommandSetIdString = "1492DB0A-85A2-4E43-BF0D-CE55B89A8CC6";
public static readonly Guid CSharpInteractiveCommandSetId = new(CSharpInteractiveCommandSetIdString);
public const string VisualBasicInteractiveCommandSetIdString = "93DF185E-D75B-4FDB-9D47-E90F111971C5";
public static readonly Guid VisualBasicInteractiveCommandSetId = new(VisualBasicInteractiveCommandSetIdString);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.VisualStudio.LanguageServices
{
internal static partial class ID
{
internal static class InteractiveCommands
{
public const int InteractiveToolWindow = 0x0001;
public const int ResetInteractiveFromProject = 0x0002;
// TODO: Remove pending https://github.com/dotnet/roslyn/issues/8927 .
public const int ExecuteInInteractiveWindow = 0x0010C;
public const string CSharpInteractiveCommandSetIdString = "1492DB0A-85A2-4E43-BF0D-CE55B89A8CC6";
public static readonly Guid CSharpInteractiveCommandSetId = new(CSharpInteractiveCommandSetIdString);
public const string VisualBasicInteractiveCommandSetIdString = "93DF185E-D75B-4FDB-9D47-E90F111971C5";
public static readonly Guid VisualBasicInteractiveCommandSetId = new(VisualBasicInteractiveCommandSetIdString);
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/VisualStudio/Core/Def/Implementation/LanguageClient/VisualStudioLspWorkspaceRegistrationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServer;
using Logger = Microsoft.CodeAnalysis.Internal.Log.Logger;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient
{
[Export(typeof(ILspWorkspaceRegistrationService)), Shared]
internal class VisualStudioLspWorkspaceRegistrationService : ILspWorkspaceRegistrationService
{
private readonly object _gate = new();
private ImmutableArray<Workspace> _registrations = ImmutableArray.Create<Workspace>();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioLspWorkspaceRegistrationService()
{
}
public ImmutableArray<Workspace> GetAllRegistrations() => _registrations;
public void Register(Workspace workspace)
{
lock (_gate)
{
Logger.Log(FunctionId.RegisterWorkspace, KeyValueLogMessage.Create(LogType.Trace, m =>
{
m["WorkspaceKind"] = workspace.Kind;
m["WorkspaceCanOpenDocuments"] = workspace.CanOpenDocuments;
m["WorkspaceCanChangeActiveContextDocument"] = workspace.CanChangeActiveContextDocument;
m["WorkspacePartialSemanticsEnabled"] = workspace.PartialSemanticsEnabled;
}));
_registrations = _registrations.Add(workspace);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServer;
using Logger = Microsoft.CodeAnalysis.Internal.Log.Logger;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient
{
[Export(typeof(ILspWorkspaceRegistrationService)), Shared]
internal class VisualStudioLspWorkspaceRegistrationService : ILspWorkspaceRegistrationService
{
private readonly object _gate = new();
private ImmutableArray<Workspace> _registrations = ImmutableArray.Create<Workspace>();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioLspWorkspaceRegistrationService()
{
}
public ImmutableArray<Workspace> GetAllRegistrations() => _registrations;
public void Register(Workspace workspace)
{
lock (_gate)
{
Logger.Log(FunctionId.RegisterWorkspace, KeyValueLogMessage.Create(LogType.Trace, m =>
{
m["WorkspaceKind"] = workspace.Kind;
m["WorkspaceCanOpenDocuments"] = workspace.CanOpenDocuments;
m["WorkspaceCanChangeActiveContextDocument"] = workspace.CanChangeActiveContextDocument;
m["WorkspacePartialSemanticsEnabled"] = workspace.PartialSemanticsEnabled;
}));
_registrations = _registrations.Add(workspace);
}
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.Analyzer.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.ExtractMethod
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
Partial Friend Class VisualBasicMethodExtractor
Inherits MethodExtractor
Private Class VisualBasicAnalyzer
Inherits Analyzer
Private Shared ReadOnly s_nonNoisySyntaxKindSet As HashSet(Of Integer) = New HashSet(Of Integer) From {SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia}
Public Shared Function AnalyzeResultAsync(currentSelectionResult As SelectionResult, cancellationToken As CancellationToken) As Task(Of AnalyzerResult)
Dim analyzer = New VisualBasicAnalyzer(currentSelectionResult, cancellationToken)
Return analyzer.AnalyzeAsync()
End Function
Public Sub New(currentSelectionResult As SelectionResult, cancellationToken As CancellationToken)
MyBase.New(currentSelectionResult, localFunction:=False, cancellationToken)
End Sub
Protected Overrides Function CreateFromSymbol(
compilation As Compilation, symbol As ISymbol,
type As ITypeSymbol, style As VariableStyle, requiresDeclarationExpressionRewrite As Boolean) As VariableInfo
If symbol.IsFunctionValue() AndAlso style.ParameterStyle.DeclarationBehavior <> DeclarationBehavior.None Then
Contract.ThrowIfFalse(style.ParameterStyle.DeclarationBehavior = DeclarationBehavior.MoveIn OrElse style.ParameterStyle.DeclarationBehavior = DeclarationBehavior.SplitIn)
style = AlwaysReturn(style)
End If
Return CreateFromSymbolCommon(Of LocalDeclarationStatementSyntax)(compilation, symbol, type, style, s_nonNoisySyntaxKindSet)
End Function
Protected Overrides Function GetIndexOfVariableInfoToUseAsReturnValue(variableInfo As IList(Of VariableInfo)) As Integer
' in VB, only byRef exist, not out or ref distinction like C#
Dim numberOfByRefParameters = 0
Dim byRefSymbolIndex As Integer = -1
For i As Integer = 0 To variableInfo.Count - 1
Dim variable = variableInfo(i)
' there should be no-one set as return value yet
Contract.ThrowIfTrue(variable.UseAsReturnValue)
If Not variable.CanBeUsedAsReturnValue Then
Continue For
End If
' check modifier
If variable.ParameterModifier = ParameterBehavior.Ref OrElse
variable.ParameterModifier = ParameterBehavior.Out Then
numberOfByRefParameters += 1
byRefSymbolIndex = i
End If
Next i
' if there is only one "byRef", that will be converted to return statement.
If numberOfByRefParameters = 1 Then
Return byRefSymbolIndex
End If
Return -1
End Function
Protected Overrides Function GetRangeVariableType(semanticModel As SemanticModel, symbol As IRangeVariableSymbol) As ITypeSymbol
Dim info = semanticModel.GetSpeculativeTypeInfo(Me.SelectionResult.FinalSpan.Start, SyntaxFactory.ParseName(symbol.Name), SpeculativeBindingOption.BindAsExpression)
If info.Type.IsErrorType() Then
Return Nothing
End If
Return If(info.ConvertedType.IsObjectType(), info.ConvertedType, info.Type)
End Function
Protected Overrides Function GetFlowAnalysisNodeRange() As Tuple(Of SyntaxNode, SyntaxNode)
Dim vbSelectionResult = DirectCast(Me.SelectionResult, VisualBasicSelectionResult)
Dim firstStatement = vbSelectionResult.GetFirstStatement()
Dim lastStatement = vbSelectionResult.GetLastStatement()
' single statement case
If firstStatement Is lastStatement OrElse
firstStatement.Span.Contains(lastStatement.Span) Then
Return New Tuple(Of SyntaxNode, SyntaxNode)(firstStatement, firstStatement)
End If
' multiple statement case
Dim firstUnderContainer = vbSelectionResult.GetFirstStatementUnderContainer()
Dim lastUnderContainer = vbSelectionResult.GetLastStatementUnderContainer()
Return New Tuple(Of SyntaxNode, SyntaxNode)(firstUnderContainer, lastUnderContainer)
End Function
Protected Overrides Function ContainsReturnStatementInSelectedCode(jumpOutOfRegionStatements As IEnumerable(Of SyntaxNode)) As Boolean
Return jumpOutOfRegionStatements.Where(Function(n) TypeOf n Is ReturnStatementSyntax OrElse TypeOf n Is ExitStatementSyntax).Any()
End Function
Protected Overrides Function ReadOnlyFieldAllowed() As Boolean
Dim methodBlock = Me.SelectionResult.GetContainingScopeOf(Of MethodBlockBaseSyntax)()
If methodBlock Is Nothing Then
Return True
End If
Return Not TypeOf methodBlock.BlockStatement Is SubNewStatementSyntax
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
Partial Friend Class VisualBasicMethodExtractor
Inherits MethodExtractor
Private Class VisualBasicAnalyzer
Inherits Analyzer
Private Shared ReadOnly s_nonNoisySyntaxKindSet As HashSet(Of Integer) = New HashSet(Of Integer) From {SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia}
Public Shared Function AnalyzeResultAsync(currentSelectionResult As SelectionResult, cancellationToken As CancellationToken) As Task(Of AnalyzerResult)
Dim analyzer = New VisualBasicAnalyzer(currentSelectionResult, cancellationToken)
Return analyzer.AnalyzeAsync()
End Function
Public Sub New(currentSelectionResult As SelectionResult, cancellationToken As CancellationToken)
MyBase.New(currentSelectionResult, localFunction:=False, cancellationToken)
End Sub
Protected Overrides Function CreateFromSymbol(
compilation As Compilation, symbol As ISymbol,
type As ITypeSymbol, style As VariableStyle, requiresDeclarationExpressionRewrite As Boolean) As VariableInfo
If symbol.IsFunctionValue() AndAlso style.ParameterStyle.DeclarationBehavior <> DeclarationBehavior.None Then
Contract.ThrowIfFalse(style.ParameterStyle.DeclarationBehavior = DeclarationBehavior.MoveIn OrElse style.ParameterStyle.DeclarationBehavior = DeclarationBehavior.SplitIn)
style = AlwaysReturn(style)
End If
Return CreateFromSymbolCommon(Of LocalDeclarationStatementSyntax)(compilation, symbol, type, style, s_nonNoisySyntaxKindSet)
End Function
Protected Overrides Function GetIndexOfVariableInfoToUseAsReturnValue(variableInfo As IList(Of VariableInfo)) As Integer
' in VB, only byRef exist, not out or ref distinction like C#
Dim numberOfByRefParameters = 0
Dim byRefSymbolIndex As Integer = -1
For i As Integer = 0 To variableInfo.Count - 1
Dim variable = variableInfo(i)
' there should be no-one set as return value yet
Contract.ThrowIfTrue(variable.UseAsReturnValue)
If Not variable.CanBeUsedAsReturnValue Then
Continue For
End If
' check modifier
If variable.ParameterModifier = ParameterBehavior.Ref OrElse
variable.ParameterModifier = ParameterBehavior.Out Then
numberOfByRefParameters += 1
byRefSymbolIndex = i
End If
Next i
' if there is only one "byRef", that will be converted to return statement.
If numberOfByRefParameters = 1 Then
Return byRefSymbolIndex
End If
Return -1
End Function
Protected Overrides Function GetRangeVariableType(semanticModel As SemanticModel, symbol As IRangeVariableSymbol) As ITypeSymbol
Dim info = semanticModel.GetSpeculativeTypeInfo(Me.SelectionResult.FinalSpan.Start, SyntaxFactory.ParseName(symbol.Name), SpeculativeBindingOption.BindAsExpression)
If info.Type.IsErrorType() Then
Return Nothing
End If
Return If(info.ConvertedType.IsObjectType(), info.ConvertedType, info.Type)
End Function
Protected Overrides Function GetFlowAnalysisNodeRange() As Tuple(Of SyntaxNode, SyntaxNode)
Dim vbSelectionResult = DirectCast(Me.SelectionResult, VisualBasicSelectionResult)
Dim firstStatement = vbSelectionResult.GetFirstStatement()
Dim lastStatement = vbSelectionResult.GetLastStatement()
' single statement case
If firstStatement Is lastStatement OrElse
firstStatement.Span.Contains(lastStatement.Span) Then
Return New Tuple(Of SyntaxNode, SyntaxNode)(firstStatement, firstStatement)
End If
' multiple statement case
Dim firstUnderContainer = vbSelectionResult.GetFirstStatementUnderContainer()
Dim lastUnderContainer = vbSelectionResult.GetLastStatementUnderContainer()
Return New Tuple(Of SyntaxNode, SyntaxNode)(firstUnderContainer, lastUnderContainer)
End Function
Protected Overrides Function ContainsReturnStatementInSelectedCode(jumpOutOfRegionStatements As IEnumerable(Of SyntaxNode)) As Boolean
Return jumpOutOfRegionStatements.Where(Function(n) TypeOf n Is ReturnStatementSyntax OrElse TypeOf n Is ExitStatementSyntax).Any()
End Function
Protected Overrides Function ReadOnlyFieldAllowed() As Boolean
Dim methodBlock = Me.SelectionResult.GetContainingScopeOf(Of MethodBlockBaseSyntax)()
If methodBlock Is Nothing Then
Return True
End If
Return Not TypeOf methodBlock.BlockStatement Is SubNewStatementSyntax
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_StructLayout.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.Reflection
Imports System.Reflection.Metadata
Imports System.Reflection.Metadata.Ecma335
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class AttributeTests_StructLayout
Inherits BasicTestBase
<Fact>
Public Sub Pack()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=0)>
Class Pack0
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=1)>
Class Pack1
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=2)>
Class Pack2
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=4)>
Class Pack4
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=8)>
Class Pack8
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=16)>
Class Pack16
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=32)>
Class Pack32
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=64)>
Class Pack64
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=128)>
Class Pack128
End Class
]]>
</file>
</compilation>
Const typeDefMask As TypeAttributes = TypeAttributes.StringFormatMask Or TypeAttributes.LayoutMask
CompileAndVerify(source, validator:=
Sub(assembly)
Dim reader = assembly.GetMetadataReader()
Assert.Equal(9, reader.GetTableRowCount(TableIndex.ClassLayout))
For Each typeHandle In reader.TypeDefinitions
Dim type = reader.GetTypeDefinition(typeHandle)
If type.GetLayout().IsDefault Then
Continue For
End If
Assert.Equal(TypeAttributes.SequentialLayout, type.Attributes And typeDefMask)
Dim typeName As String = reader.GetString(type.Name)
Dim expectedAlignment As Integer = Integer.Parse(typeName.Substring("Pack".Length))
Assert.Equal(expectedAlignment, type.GetLayout().PackingSize)
Assert.Equal(1, type.GetLayout().Size)
Next
End Sub)
End Sub
<Fact>
Public Sub SizeAndPack()
Dim verifiable =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Class Classes
<StructLayout(LayoutKind.Explicit)>
Class E
End Class
<StructLayout(LayoutKind.Explicit, Size:=0)>
Class E_S0
End Class
<StructLayout(LayoutKind.Explicit, Size:=1)>
Class E_S1
End Class
<StructLayout(LayoutKind.Explicit, Pack:=0)>
Class E_P0
End Class
<StructLayout(LayoutKind.Explicit, Pack:=1)>
Class E_P1
End Class
<StructLayout(LayoutKind.Explicit, Pack:=0, Size:=0)>
Class E_P0_S0
End Class
<StructLayout(LayoutKind.Explicit, Pack:=1, Size:=10)>
Class E_P1_S10
End Class
<StructLayout(LayoutKind.Sequential)>
Class Q
End Class
<StructLayout(LayoutKind.Sequential, Size:=0)>
Class Q_S0
End Class
<StructLayout(LayoutKind.Sequential, Size:=1)>
Class Q_S1
End Class
<StructLayout(LayoutKind.Sequential, Pack:=0)>
Class Q_P0
End Class
<StructLayout(LayoutKind.Sequential, Pack:=1)>
Class Q_P1
End Class
<StructLayout(LayoutKind.Sequential, Pack:=0, Size:=0)>
Class Q_P0_S0
End Class
<StructLayout(LayoutKind.Sequential, Pack:=1, Size:=10)>
Class Q_P1_S10
End Class
<StructLayout(LayoutKind.Auto)>
Class A
End Class
End Class
Class Structs
<StructLayout(LayoutKind.Explicit)>
Structure E
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Explicit, Size:=0)>
Structure E_S0
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Explicit, Size:=1)>
Structure E_S1
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Explicit, Pack:=0)>
Structure E_P0
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Explicit, Pack:=1)>
Structure E_P1
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Explicit, Pack:=0, Size:=0)>
Structure E_P0_S0
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Explicit, Pack:=1, Size:=10)>
Structure E_P1_S10
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential)>
Structure Q
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential, Size:=0)>
Structure Q_S0
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential, Size:=1)>
Structure Q_S1
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=0)>
Structure Q_P0
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1)>
Structure Q_P1
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=0, Size:=0)>
Structure Q_P0_S0
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1, Size:=10)>
Structure Q_P1_S10
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Auto)>
Structure A
Dim a As Integer
End Structure
End Class
]]>
</file>
</compilation>
' peverify reports errors, but the types can be loaded and used:
Dim unverifiable =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Class Classes
<StructLayout(LayoutKind.Auto, Size:=0)>
Class A_S0
End Class
<StructLayout(LayoutKind.Auto, Size:=1)>
Class A_S1
End Class
<StructLayout(LayoutKind.Auto, Pack:=0)>
Class A_P0
End Class
<StructLayout(LayoutKind.Auto, Pack:=1)>
Class A_P1
End Class
<StructLayout(LayoutKind.Auto, Pack:=0, Size:=0)>
Class A_P0_S0
End Class
<StructLayout(LayoutKind.Auto, Pack:=1, Size:=10)>
Class A_P1_S10
End Class
End Class
Class Structs
<StructLayout(LayoutKind.Auto, Size:=0)>
Structure A_S0
End Structure
<StructLayout(LayoutKind.Auto, Size:=1)>
Structure A_S1
End Structure
<StructLayout(LayoutKind.Auto, Pack:=0)>
Structure A_P0_S1 ' this is different from C#, which emits size = 0
End Structure
<StructLayout(LayoutKind.Auto, Pack:=1)>
Structure A_P1_S1 ' this is different from C#, which emits size = 0
End Structure
<StructLayout(LayoutKind.Auto, Pack:=0, Size:=0)>
Structure A_P0_S0
End Structure
<StructLayout(LayoutKind.Auto, Pack:=1, Size:=10)>
Structure A_P1_S10
End Structure
End Class
]]>
</file>
</compilation>
' types can't be loaded as they are too big:
Dim unloadable =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Class Classes
<StructLayout(LayoutKind.Auto, Pack:=1, Size:=Int32.MaxValue)>
Class A_P1_S2147483647
End Class
<StructLayout(LayoutKind.Sequential, Pack:=1, Size:=Int32.MaxValue)>
Class Q_P1_S2147483647
End Class
<StructLayout(LayoutKind.Explicit, Pack:=1, Size:=Int32.MaxValue)>
Class E_P1_S2147483647
End Class
End Class
Class Structs
<StructLayout(LayoutKind.Auto, Pack:=1, Size:=Int32.MaxValue)>
Structure A_P1_S2147483647
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1, Size:=Int32.MaxValue)>
Structure Q_P1_S2147483647
End Structure
<StructLayout(LayoutKind.Explicit, Pack:=1, Size:=Int32.MaxValue)>
Structure E_P1_S2147483647
End Structure
End Class
]]>
</file>
</compilation>
Dim validator As Action(Of PEAssembly) =
Sub(assembly)
Dim reader = assembly.GetMetadataReader()
For Each typeHandle In reader.TypeDefinitions
Dim type = reader.GetTypeDefinition(typeHandle)
Dim layout = type.GetLayout()
If layout.IsDefault Then
Continue For
End If
Dim isValueType As Boolean = (type.Attributes And TypeAttributes.Sealed) <> 0
Dim typeName As String = reader.GetString(type.Name)
Dim expectedSize As UInteger = 0
Dim expectedPack As UShort = 0
Dim expectedKind As TypeAttributes = TypeAttributes.AutoLayout
If typeName <> "Structs" AndAlso typeName <> "Classes" Then
For Each part In typeName.Split("_"c)
Select Case part(0)
Case "A"c
expectedKind = TypeAttributes.AutoLayout
Case "E"c
expectedKind = TypeAttributes.ExplicitLayout
Case "Q"c
expectedKind = TypeAttributes.SequentialLayout
Case "P"c
expectedPack = UShort.Parse(part.Substring(1))
Case "S"c
expectedSize = UInteger.Parse(part.Substring(1))
End Select
Next
End If
Assert.False(expectedPack = 0 AndAlso expectedSize = 0, "Either expectedPack or expectedSize should be non-zero")
Assert.Equal(CInt(expectedPack), layout.PackingSize)
Assert.Equal(CInt(expectedSize), layout.Size)
Assert.Equal(expectedKind, type.Attributes And TypeAttributes.LayoutMask)
Next
End Sub
CompileAndVerify(verifiable, validator:=validator)
CompileAndVerify(unverifiable, validator:=validator, verify:=Verification.Fails)
CompileAndVerify(unloadable, validator:=validator, verify:=Verification.Fails)
End Sub
<Fact>
Public Sub Pack_Errors()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=-1)>
Class PM1
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=3)>
Class P3
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=5)>
Class P5
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=6)>
Class P6
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=256)>
Class P256
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=512)>
Class P512
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=Int32.MaxValue)>
Class PMax
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<![CDATA[
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=-1)>
~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=3)>
~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=5)>
~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=6)>
~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=256)>
~~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=512)>
~~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=Int32.MaxValue)>
~~~~~~~~~~~~~~~~~~~~
]]>)
End Sub
<Fact>
Public Sub Size_Errors()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Sequential, Size:=-1)>
Class S
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<![CDATA[
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=-1)>
~~~~~~~~
]]>)
End Sub
<Fact>
Public Sub LayoutAndCharSet_Errors()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(DirectCast((-1), LayoutKind), CharSet:=CharSet.Ansi)>
Public Class C1
End Class
<StructLayout(DirectCast(4, LayoutKind), CharSet:=CharSet.Ansi)>
Public Class C2
End Class
<StructLayout(LayoutKind.Sequential, CharSet:=DirectCast((-1), CharSet))>
Public Class C3
End Class
<StructLayout(LayoutKind.Sequential, CharSet:=DirectCast(5, CharSet))>
Public Class C4
End Class
<StructLayout(LayoutKind.Sequential, CharSet:=DirectCast(Int32.MaxValue, CharSet))>
Public Class C5
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<![CDATA[
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(DirectCast((-1), LayoutKind), CharSet:=CharSet.Ansi)>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(DirectCast(4, LayoutKind), CharSet:=CharSet.Ansi)>
~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, CharSet:=DirectCast((-1), CharSet))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, CharSet:=DirectCast(5, CharSet))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, CharSet:=DirectCast(Int32.MaxValue, CharSet))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>)
End Sub
''' <summary>
''' CLI spec (22.8 ClassLayout):
''' "A type has layout if it is marked SequentialLayout or ExplicitLayout.
''' If any type within an inheritance chain has layout, then so shall all its base classes,
''' up to the one that descends immediately from System.ValueType (if it exists in the type's hierarchy);
''' otherwise, from System.Object."
'''
''' But this rule is only enforced by the loader, not by the compiler.
''' TODO: should we report an error?
''' </summary>
<Fact>
Public Sub Inheritance()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Sequential)>
Public Class A
Public a As Integer, b As Integer
End Class
Public Class B
Inherits A
Public c As Integer, d As Integer
End Class
<StructLayout(LayoutKind.Sequential)>
Public Class C
Inherits B
Public e As Integer, f As Integer
End Class
]]>
</file>
</compilation>
' type C can't be loaded
CompileAndVerify(source, verify:=Verification.Fails)
End Sub
<Fact>
Public Sub ExplicitFieldLayout()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Explicit)>
Public Class A
<FieldOffset(4)>
Dim a As Integer
<FieldOffset(8)>
WithEvents b As A
' FieldOffset can't be applied on Property or Event backing fields
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, validator:=
Sub(assembly)
Dim reader = assembly.GetMetadataReader()
Assert.Equal(2, reader.GetTableRowCount(TableIndex.FieldLayout))
For Each fieldHandle In reader.FieldDefinitions
Dim field = reader.GetFieldDefinition(fieldHandle)
Dim name = reader.GetString(field.Name)
Dim expectedOffset As Integer
Select Case name
Case "a"
expectedOffset = 4
Case "_b"
expectedOffset = 8
Case Else
Throw TestExceptionUtilities.UnexpectedValue(name)
End Select
Assert.Equal(expectedOffset, field.GetOffset())
Next
End Sub)
End Sub
''' <summary>
''' CLI spec (22.16 FieldLayout):
''' - Offset shall be zero or more.
''' - The Type whose Fields are described by each row of the FieldLayout table shall have Flags.ExplicitLayout.
''' - Flags.Static for the row in the Field table indexed by Field shall be non-static
''' - Every Field of an ExplicitLayout Type shall be given an offset; that is, it shall have a row in the FieldLayout table
'''
''' Dev11 VB checks only the first rule.
''' </summary>
<Fact>
Public Sub ExplicitFieldLayout_Errors()
Dim source =
<compilation>
<file><![CDATA[
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Auto)>
Public Class A
<FieldOffset(4)>
Dim a As Integer
End Class
<StructLayout(LayoutKind.Sequential)>
Public Class S
<FieldOffset(4)>
Dim a As Integer
<FieldOffset(-1)>
Dim b As Integer
End Class
<StructLayout(LayoutKind.Explicit)>
Public Class E
<FieldOffset(-1)>
Dim a As Integer
<FieldOffset(5)>
Shared b As Integer
Dim c1 As Integer, c2 As Integer
Shared d As Integer
Const e As Integer = 3
<FieldOffset(10)>
Dim f As Object
<FieldOffset(-1)>
Shared g As Integer
<FieldOffset(5)>
Const h As Integer = 1
End Class
Enum En
<FieldOffset(5)>
A = 1
End Enum
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<![CDATA[
BC30127: Attribute 'FieldOffsetAttribute' is not valid: Incorrect argument value.
<FieldOffset(-1)>
~~
BC30127: Attribute 'FieldOffsetAttribute' is not valid: Incorrect argument value.
<FieldOffset(-1)>
~~
BC30127: Attribute 'FieldOffsetAttribute' is not valid: Incorrect argument value.
<FieldOffset(-1)>
~~
]]>)
End Sub
<Fact>
Public Sub ReadingFromMetadata()
Using [module] = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.Invalid.ClassLayout)
Dim reader = [module].Module.GetMetadataReader()
For Each typeHandle In reader.TypeDefinitions
Dim type = reader.GetTypeDefinition(typeHandle)
Dim name = reader.GetString(type.Name)
Dim classSize As UInteger = 0, packingSize As UInteger = 0
Dim badLayout = False
Dim mdLayout As System.Reflection.Metadata.TypeLayout
Try
mdLayout = type.GetLayout()
Catch ex As BadImageFormatException
badLayout = True
mdLayout = Nothing
End Try
Dim hasClassLayout = Not mdLayout.IsDefault
Dim layout As TypeLayout = [module].Module.GetTypeLayout(typeHandle)
Select Case name
Case "<Module>"
Assert.False(hasClassLayout)
Assert.Equal(Nothing, layout)
Assert.False(badLayout)
Case "S1"
Case "S2"
' invalid size/pack value
Assert.False(hasClassLayout)
Assert.True(badLayout)
Case "S3"
Assert.True(hasClassLayout)
Assert.Equal(1, mdLayout.Size)
Assert.Equal(2, mdLayout.PackingSize)
Assert.Equal(New TypeLayout(LayoutKind.Sequential, size:=1, alignment:=2), layout)
Assert.False(badLayout)
Case "S4"
Assert.True(hasClassLayout)
Assert.Equal(&H12345678, mdLayout.Size)
Assert.Equal(0, mdLayout.PackingSize)
Assert.Equal(New TypeLayout(LayoutKind.Sequential, size:=&H12345678, alignment:=0), layout)
Assert.False(badLayout)
Case "S5"
' doesn't have layout
Assert.False(hasClassLayout)
Assert.Equal(New TypeLayout(LayoutKind.Sequential, size:=0, alignment:=0), layout)
Assert.False(badLayout)
Case Else
Throw TestExceptionUtilities.UnexpectedValue(name)
End Select
Next
End Using
End Sub
Private Sub VerifyStructLayout(source As System.Xml.Linq.XElement, hasInstanceFields As Boolean)
CompileAndVerify(source, validator:=
Sub(assembly)
Dim reader = assembly.GetMetadataReader()
Dim type = reader.TypeDefinitions _
.Select(Function(handle) reader.GetTypeDefinition(handle)) _
.Where(Function(typeDef) reader.GetString(typeDef.Name) = "S") _
.Single()
Dim layout = type.GetLayout()
If Not hasInstanceFields Then
Const typeDefMask As TypeAttributes = TypeAttributes.StringFormatMask Or TypeAttributes.LayoutMask
Assert.False(layout.IsDefault)
Assert.Equal(TypeAttributes.SequentialLayout, type.Attributes And typeDefMask)
Assert.Equal(0, layout.PackingSize)
Assert.Equal(1, layout.Size)
Else
Assert.True(layout.IsDefault)
End If
End Sub)
End Sub
<Fact>
Public Sub Bug1075326()
' no instance fields
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
End Structure
]]></file></compilation>, hasInstanceFields:=False)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Shared f As Integer
End Structure
]]></file></compilation>, hasInstanceFields:=False)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Shared Property P As Integer
End Structure
]]></file></compilation>, hasInstanceFields:=False)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
ReadOnly Property P As Integer
Get
Return 0
End Get
End Property
End Structure
]]></file></compilation>, hasInstanceFields:=False)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Shared ReadOnly Property P As Integer
Get
Return 0
End Get
End Property
End Structure
]]></file></compilation>, hasInstanceFields:=False)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Shared Event D()
End Structure
]]></file></compilation>, hasInstanceFields:=False)
' instance fields
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Private f As Integer
End Structure
]]></file></compilation>, hasInstanceFields:=True)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Property P As Integer
End Structure
]]></file></compilation>, hasInstanceFields:=True)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Event D()
End Structure
]]></file></compilation>, hasInstanceFields:=True)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Reflection
Imports System.Reflection.Metadata
Imports System.Reflection.Metadata.Ecma335
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class AttributeTests_StructLayout
Inherits BasicTestBase
<Fact>
Public Sub Pack()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=0)>
Class Pack0
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=1)>
Class Pack1
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=2)>
Class Pack2
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=4)>
Class Pack4
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=8)>
Class Pack8
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=16)>
Class Pack16
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=32)>
Class Pack32
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=64)>
Class Pack64
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=128)>
Class Pack128
End Class
]]>
</file>
</compilation>
Const typeDefMask As TypeAttributes = TypeAttributes.StringFormatMask Or TypeAttributes.LayoutMask
CompileAndVerify(source, validator:=
Sub(assembly)
Dim reader = assembly.GetMetadataReader()
Assert.Equal(9, reader.GetTableRowCount(TableIndex.ClassLayout))
For Each typeHandle In reader.TypeDefinitions
Dim type = reader.GetTypeDefinition(typeHandle)
If type.GetLayout().IsDefault Then
Continue For
End If
Assert.Equal(TypeAttributes.SequentialLayout, type.Attributes And typeDefMask)
Dim typeName As String = reader.GetString(type.Name)
Dim expectedAlignment As Integer = Integer.Parse(typeName.Substring("Pack".Length))
Assert.Equal(expectedAlignment, type.GetLayout().PackingSize)
Assert.Equal(1, type.GetLayout().Size)
Next
End Sub)
End Sub
<Fact>
Public Sub SizeAndPack()
Dim verifiable =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Class Classes
<StructLayout(LayoutKind.Explicit)>
Class E
End Class
<StructLayout(LayoutKind.Explicit, Size:=0)>
Class E_S0
End Class
<StructLayout(LayoutKind.Explicit, Size:=1)>
Class E_S1
End Class
<StructLayout(LayoutKind.Explicit, Pack:=0)>
Class E_P0
End Class
<StructLayout(LayoutKind.Explicit, Pack:=1)>
Class E_P1
End Class
<StructLayout(LayoutKind.Explicit, Pack:=0, Size:=0)>
Class E_P0_S0
End Class
<StructLayout(LayoutKind.Explicit, Pack:=1, Size:=10)>
Class E_P1_S10
End Class
<StructLayout(LayoutKind.Sequential)>
Class Q
End Class
<StructLayout(LayoutKind.Sequential, Size:=0)>
Class Q_S0
End Class
<StructLayout(LayoutKind.Sequential, Size:=1)>
Class Q_S1
End Class
<StructLayout(LayoutKind.Sequential, Pack:=0)>
Class Q_P0
End Class
<StructLayout(LayoutKind.Sequential, Pack:=1)>
Class Q_P1
End Class
<StructLayout(LayoutKind.Sequential, Pack:=0, Size:=0)>
Class Q_P0_S0
End Class
<StructLayout(LayoutKind.Sequential, Pack:=1, Size:=10)>
Class Q_P1_S10
End Class
<StructLayout(LayoutKind.Auto)>
Class A
End Class
End Class
Class Structs
<StructLayout(LayoutKind.Explicit)>
Structure E
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Explicit, Size:=0)>
Structure E_S0
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Explicit, Size:=1)>
Structure E_S1
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Explicit, Pack:=0)>
Structure E_P0
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Explicit, Pack:=1)>
Structure E_P1
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Explicit, Pack:=0, Size:=0)>
Structure E_P0_S0
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Explicit, Pack:=1, Size:=10)>
Structure E_P1_S10
<FieldOffset(0)>
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential)>
Structure Q
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential, Size:=0)>
Structure Q_S0
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential, Size:=1)>
Structure Q_S1
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=0)>
Structure Q_P0
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1)>
Structure Q_P1
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=0, Size:=0)>
Structure Q_P0_S0
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1, Size:=10)>
Structure Q_P1_S10
Dim a As Integer
End Structure
<StructLayout(LayoutKind.Auto)>
Structure A
Dim a As Integer
End Structure
End Class
]]>
</file>
</compilation>
' peverify reports errors, but the types can be loaded and used:
Dim unverifiable =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Class Classes
<StructLayout(LayoutKind.Auto, Size:=0)>
Class A_S0
End Class
<StructLayout(LayoutKind.Auto, Size:=1)>
Class A_S1
End Class
<StructLayout(LayoutKind.Auto, Pack:=0)>
Class A_P0
End Class
<StructLayout(LayoutKind.Auto, Pack:=1)>
Class A_P1
End Class
<StructLayout(LayoutKind.Auto, Pack:=0, Size:=0)>
Class A_P0_S0
End Class
<StructLayout(LayoutKind.Auto, Pack:=1, Size:=10)>
Class A_P1_S10
End Class
End Class
Class Structs
<StructLayout(LayoutKind.Auto, Size:=0)>
Structure A_S0
End Structure
<StructLayout(LayoutKind.Auto, Size:=1)>
Structure A_S1
End Structure
<StructLayout(LayoutKind.Auto, Pack:=0)>
Structure A_P0_S1 ' this is different from C#, which emits size = 0
End Structure
<StructLayout(LayoutKind.Auto, Pack:=1)>
Structure A_P1_S1 ' this is different from C#, which emits size = 0
End Structure
<StructLayout(LayoutKind.Auto, Pack:=0, Size:=0)>
Structure A_P0_S0
End Structure
<StructLayout(LayoutKind.Auto, Pack:=1, Size:=10)>
Structure A_P1_S10
End Structure
End Class
]]>
</file>
</compilation>
' types can't be loaded as they are too big:
Dim unloadable =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Class Classes
<StructLayout(LayoutKind.Auto, Pack:=1, Size:=Int32.MaxValue)>
Class A_P1_S2147483647
End Class
<StructLayout(LayoutKind.Sequential, Pack:=1, Size:=Int32.MaxValue)>
Class Q_P1_S2147483647
End Class
<StructLayout(LayoutKind.Explicit, Pack:=1, Size:=Int32.MaxValue)>
Class E_P1_S2147483647
End Class
End Class
Class Structs
<StructLayout(LayoutKind.Auto, Pack:=1, Size:=Int32.MaxValue)>
Structure A_P1_S2147483647
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1, Size:=Int32.MaxValue)>
Structure Q_P1_S2147483647
End Structure
<StructLayout(LayoutKind.Explicit, Pack:=1, Size:=Int32.MaxValue)>
Structure E_P1_S2147483647
End Structure
End Class
]]>
</file>
</compilation>
Dim validator As Action(Of PEAssembly) =
Sub(assembly)
Dim reader = assembly.GetMetadataReader()
For Each typeHandle In reader.TypeDefinitions
Dim type = reader.GetTypeDefinition(typeHandle)
Dim layout = type.GetLayout()
If layout.IsDefault Then
Continue For
End If
Dim isValueType As Boolean = (type.Attributes And TypeAttributes.Sealed) <> 0
Dim typeName As String = reader.GetString(type.Name)
Dim expectedSize As UInteger = 0
Dim expectedPack As UShort = 0
Dim expectedKind As TypeAttributes = TypeAttributes.AutoLayout
If typeName <> "Structs" AndAlso typeName <> "Classes" Then
For Each part In typeName.Split("_"c)
Select Case part(0)
Case "A"c
expectedKind = TypeAttributes.AutoLayout
Case "E"c
expectedKind = TypeAttributes.ExplicitLayout
Case "Q"c
expectedKind = TypeAttributes.SequentialLayout
Case "P"c
expectedPack = UShort.Parse(part.Substring(1))
Case "S"c
expectedSize = UInteger.Parse(part.Substring(1))
End Select
Next
End If
Assert.False(expectedPack = 0 AndAlso expectedSize = 0, "Either expectedPack or expectedSize should be non-zero")
Assert.Equal(CInt(expectedPack), layout.PackingSize)
Assert.Equal(CInt(expectedSize), layout.Size)
Assert.Equal(expectedKind, type.Attributes And TypeAttributes.LayoutMask)
Next
End Sub
CompileAndVerify(verifiable, validator:=validator)
CompileAndVerify(unverifiable, validator:=validator, verify:=Verification.Fails)
CompileAndVerify(unloadable, validator:=validator, verify:=Verification.Fails)
End Sub
<Fact>
Public Sub Pack_Errors()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=-1)>
Class PM1
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=3)>
Class P3
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=5)>
Class P5
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=6)>
Class P6
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=256)>
Class P256
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=512)>
Class P512
End Class
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=Int32.MaxValue)>
Class PMax
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<![CDATA[
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=-1)>
~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=3)>
~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=5)>
~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=6)>
~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=256)>
~~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=512)>
~~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=1, Pack:=Int32.MaxValue)>
~~~~~~~~~~~~~~~~~~~~
]]>)
End Sub
<Fact>
Public Sub Size_Errors()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Sequential, Size:=-1)>
Class S
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<![CDATA[
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, Size:=-1)>
~~~~~~~~
]]>)
End Sub
<Fact>
Public Sub LayoutAndCharSet_Errors()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(DirectCast((-1), LayoutKind), CharSet:=CharSet.Ansi)>
Public Class C1
End Class
<StructLayout(DirectCast(4, LayoutKind), CharSet:=CharSet.Ansi)>
Public Class C2
End Class
<StructLayout(LayoutKind.Sequential, CharSet:=DirectCast((-1), CharSet))>
Public Class C3
End Class
<StructLayout(LayoutKind.Sequential, CharSet:=DirectCast(5, CharSet))>
Public Class C4
End Class
<StructLayout(LayoutKind.Sequential, CharSet:=DirectCast(Int32.MaxValue, CharSet))>
Public Class C5
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<![CDATA[
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(DirectCast((-1), LayoutKind), CharSet:=CharSet.Ansi)>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(DirectCast(4, LayoutKind), CharSet:=CharSet.Ansi)>
~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, CharSet:=DirectCast((-1), CharSet))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, CharSet:=DirectCast(5, CharSet))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'StructLayoutAttribute' is not valid: Incorrect argument value.
<StructLayout(LayoutKind.Sequential, CharSet:=DirectCast(Int32.MaxValue, CharSet))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>)
End Sub
''' <summary>
''' CLI spec (22.8 ClassLayout):
''' "A type has layout if it is marked SequentialLayout or ExplicitLayout.
''' If any type within an inheritance chain has layout, then so shall all its base classes,
''' up to the one that descends immediately from System.ValueType (if it exists in the type's hierarchy);
''' otherwise, from System.Object."
'''
''' But this rule is only enforced by the loader, not by the compiler.
''' TODO: should we report an error?
''' </summary>
<Fact>
Public Sub Inheritance()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Sequential)>
Public Class A
Public a As Integer, b As Integer
End Class
Public Class B
Inherits A
Public c As Integer, d As Integer
End Class
<StructLayout(LayoutKind.Sequential)>
Public Class C
Inherits B
Public e As Integer, f As Integer
End Class
]]>
</file>
</compilation>
' type C can't be loaded
CompileAndVerify(source, verify:=Verification.Fails)
End Sub
<Fact>
Public Sub ExplicitFieldLayout()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Explicit)>
Public Class A
<FieldOffset(4)>
Dim a As Integer
<FieldOffset(8)>
WithEvents b As A
' FieldOffset can't be applied on Property or Event backing fields
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, validator:=
Sub(assembly)
Dim reader = assembly.GetMetadataReader()
Assert.Equal(2, reader.GetTableRowCount(TableIndex.FieldLayout))
For Each fieldHandle In reader.FieldDefinitions
Dim field = reader.GetFieldDefinition(fieldHandle)
Dim name = reader.GetString(field.Name)
Dim expectedOffset As Integer
Select Case name
Case "a"
expectedOffset = 4
Case "_b"
expectedOffset = 8
Case Else
Throw TestExceptionUtilities.UnexpectedValue(name)
End Select
Assert.Equal(expectedOffset, field.GetOffset())
Next
End Sub)
End Sub
''' <summary>
''' CLI spec (22.16 FieldLayout):
''' - Offset shall be zero or more.
''' - The Type whose Fields are described by each row of the FieldLayout table shall have Flags.ExplicitLayout.
''' - Flags.Static for the row in the Field table indexed by Field shall be non-static
''' - Every Field of an ExplicitLayout Type shall be given an offset; that is, it shall have a row in the FieldLayout table
'''
''' Dev11 VB checks only the first rule.
''' </summary>
<Fact>
Public Sub ExplicitFieldLayout_Errors()
Dim source =
<compilation>
<file><![CDATA[
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Auto)>
Public Class A
<FieldOffset(4)>
Dim a As Integer
End Class
<StructLayout(LayoutKind.Sequential)>
Public Class S
<FieldOffset(4)>
Dim a As Integer
<FieldOffset(-1)>
Dim b As Integer
End Class
<StructLayout(LayoutKind.Explicit)>
Public Class E
<FieldOffset(-1)>
Dim a As Integer
<FieldOffset(5)>
Shared b As Integer
Dim c1 As Integer, c2 As Integer
Shared d As Integer
Const e As Integer = 3
<FieldOffset(10)>
Dim f As Object
<FieldOffset(-1)>
Shared g As Integer
<FieldOffset(5)>
Const h As Integer = 1
End Class
Enum En
<FieldOffset(5)>
A = 1
End Enum
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<![CDATA[
BC30127: Attribute 'FieldOffsetAttribute' is not valid: Incorrect argument value.
<FieldOffset(-1)>
~~
BC30127: Attribute 'FieldOffsetAttribute' is not valid: Incorrect argument value.
<FieldOffset(-1)>
~~
BC30127: Attribute 'FieldOffsetAttribute' is not valid: Incorrect argument value.
<FieldOffset(-1)>
~~
]]>)
End Sub
<Fact>
Public Sub ReadingFromMetadata()
Using [module] = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.Invalid.ClassLayout)
Dim reader = [module].Module.GetMetadataReader()
For Each typeHandle In reader.TypeDefinitions
Dim type = reader.GetTypeDefinition(typeHandle)
Dim name = reader.GetString(type.Name)
Dim classSize As UInteger = 0, packingSize As UInteger = 0
Dim badLayout = False
Dim mdLayout As System.Reflection.Metadata.TypeLayout
Try
mdLayout = type.GetLayout()
Catch ex As BadImageFormatException
badLayout = True
mdLayout = Nothing
End Try
Dim hasClassLayout = Not mdLayout.IsDefault
Dim layout As TypeLayout = [module].Module.GetTypeLayout(typeHandle)
Select Case name
Case "<Module>"
Assert.False(hasClassLayout)
Assert.Equal(Nothing, layout)
Assert.False(badLayout)
Case "S1"
Case "S2"
' invalid size/pack value
Assert.False(hasClassLayout)
Assert.True(badLayout)
Case "S3"
Assert.True(hasClassLayout)
Assert.Equal(1, mdLayout.Size)
Assert.Equal(2, mdLayout.PackingSize)
Assert.Equal(New TypeLayout(LayoutKind.Sequential, size:=1, alignment:=2), layout)
Assert.False(badLayout)
Case "S4"
Assert.True(hasClassLayout)
Assert.Equal(&H12345678, mdLayout.Size)
Assert.Equal(0, mdLayout.PackingSize)
Assert.Equal(New TypeLayout(LayoutKind.Sequential, size:=&H12345678, alignment:=0), layout)
Assert.False(badLayout)
Case "S5"
' doesn't have layout
Assert.False(hasClassLayout)
Assert.Equal(New TypeLayout(LayoutKind.Sequential, size:=0, alignment:=0), layout)
Assert.False(badLayout)
Case Else
Throw TestExceptionUtilities.UnexpectedValue(name)
End Select
Next
End Using
End Sub
Private Sub VerifyStructLayout(source As System.Xml.Linq.XElement, hasInstanceFields As Boolean)
CompileAndVerify(source, validator:=
Sub(assembly)
Dim reader = assembly.GetMetadataReader()
Dim type = reader.TypeDefinitions _
.Select(Function(handle) reader.GetTypeDefinition(handle)) _
.Where(Function(typeDef) reader.GetString(typeDef.Name) = "S") _
.Single()
Dim layout = type.GetLayout()
If Not hasInstanceFields Then
Const typeDefMask As TypeAttributes = TypeAttributes.StringFormatMask Or TypeAttributes.LayoutMask
Assert.False(layout.IsDefault)
Assert.Equal(TypeAttributes.SequentialLayout, type.Attributes And typeDefMask)
Assert.Equal(0, layout.PackingSize)
Assert.Equal(1, layout.Size)
Else
Assert.True(layout.IsDefault)
End If
End Sub)
End Sub
<Fact>
Public Sub Bug1075326()
' no instance fields
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
End Structure
]]></file></compilation>, hasInstanceFields:=False)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Shared f As Integer
End Structure
]]></file></compilation>, hasInstanceFields:=False)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Shared Property P As Integer
End Structure
]]></file></compilation>, hasInstanceFields:=False)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
ReadOnly Property P As Integer
Get
Return 0
End Get
End Property
End Structure
]]></file></compilation>, hasInstanceFields:=False)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Shared ReadOnly Property P As Integer
Get
Return 0
End Get
End Property
End Structure
]]></file></compilation>, hasInstanceFields:=False)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Shared Event D()
End Structure
]]></file></compilation>, hasInstanceFields:=False)
' instance fields
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Private f As Integer
End Structure
]]></file></compilation>, hasInstanceFields:=True)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Property P As Integer
End Structure
]]></file></compilation>, hasInstanceFields:=True)
VerifyStructLayout(<compilation><file><![CDATA[
Structure S
Event D()
End Structure
]]></file></compilation>, hasInstanceFields:=True)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ja.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ja" original="../CSharpEditorResources.resx">
<body>
<trans-unit id="Add_Missing_Usings_on_Paste">
<source>Add Missing Usings on Paste</source>
<target state="translated">貼り付け時に欠落している usings を追加する</target>
<note>"usings" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Adding_missing_usings">
<source>Adding missing usings...</source>
<target state="translated">欠落している usings を追加しています...</target>
<note>Shown in a thread await dialog. "usings" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value">
<source>Avoid expression statements that implicitly ignore value</source>
<target state="translated">値を暗黙的に無視する式ステートメントを指定しないでください</target>
<note />
</trans-unit>
<trans-unit id="Avoid_unused_value_assignments">
<source>Avoid unused value assignments</source>
<target state="translated">使用されない値の代入を指定しないでください</target>
<note />
</trans-unit>
<trans-unit id="Chosen_version_0">
<source>Chosen version: '{0}'</source>
<target state="translated">選択されたバージョン: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Complete_statement_on_semicolon">
<source>Complete statement on ;</source>
<target state="translated">ステートメントを ; で完了させてください</target>
<note />
</trans-unit>
<trans-unit id="Could_not_find_by_name_0">
<source>Could not find by name: '{0}'</source>
<target state="translated">名前 '{0}' で見つけることができませんでした</target>
<note />
</trans-unit>
<trans-unit id="Decompilation_log">
<source>Decompilation log</source>
<target state="translated">逆コンパイルのログ</target>
<note />
</trans-unit>
<trans-unit id="Discard">
<source>Discard</source>
<target state="translated">破棄</target>
<note />
</trans-unit>
<trans-unit id="Elsewhere">
<source>Elsewhere</source>
<target state="translated">その他の場所</target>
<note />
</trans-unit>
<trans-unit id="Fix_interpolated_verbatim_string">
<source>Fix interpolated verbatim string</source>
<target state="translated">挿入された逐語的文字列を修正します</target>
<note />
</trans-unit>
<trans-unit id="For_built_in_types">
<source>For built-in types</source>
<target state="translated">ビルトイン型の場合</target>
<note />
</trans-unit>
<trans-unit id="Found_0_assemblies_for_1">
<source>Found '{0}' assemblies for '{1}':</source>
<target state="translated">'{1}' の '{0}' 個のアセンブリが見つかりました:</target>
<note />
</trans-unit>
<trans-unit id="Found_exact_match_0">
<source>Found exact match: '{0}'</source>
<target state="translated">完全一致が見つかりました: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Found_higher_version_match_0">
<source>Found higher version match: '{0}'</source>
<target state="translated">新しいバージョンの一致が見つかりました: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Found_single_assembly_0">
<source>Found single assembly: '{0}'</source>
<target state="translated">1 つのアセンブリが見つかりました: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Generate_Event_Subscription">
<source>Generate Event Subscription</source>
<target state="translated">イベント サブスクリプションの生成</target>
<note />
</trans-unit>
<trans-unit id="Ignore_spaces_in_declaration_statements">
<source>Ignore spaces in declaration statements</source>
<target state="translated">宣言ステートメント内のスペースを無視する</target>
<note />
</trans-unit>
<trans-unit id="Indent_block_contents">
<source>Indent block contents</source>
<target state="translated">ブロックの内容をインデントする</target>
<note />
</trans-unit>
<trans-unit id="Indent_case_contents">
<source>Indent case contents</source>
<target state="translated">case の内容をインデントする</target>
<note />
</trans-unit>
<trans-unit id="Indent_case_contents_when_block">
<source>Indent case contents (when block)</source>
<target state="translated">case の内容をインデントします (ブロックする場合)</target>
<note />
</trans-unit>
<trans-unit id="Indent_case_labels">
<source>Indent case labels</source>
<target state="translated">case ラベルをインデントする</target>
<note />
</trans-unit>
<trans-unit id="Indent_open_and_close_braces">
<source>Indent open and close braces</source>
<target state="translated">始めと終わりのかっこをインデントする</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_cast">
<source>Insert space after cast</source>
<target state="translated">キャストの後にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration">
<source>Insert space after colon for base or interface in type declaration</source>
<target state="translated">型宣言で、基本またはインターフェイス用のコロンの後にスペースを配置する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_comma">
<source>Insert space after comma</source>
<target state="translated">コンマの後にスペースを追加する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_dot">
<source>Insert space after dot</source>
<target state="translated">ピリオドの後にスペースを追加する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_keywords_in_control_flow_statements">
<source>Insert space after keywords in control flow statements</source>
<target state="translated">制御フロー ステートメント内のキーワードの後にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_semicolon_in_for_statement">
<source>Insert space after semicolon in "for" statement</source>
<target state="translated">"for" ステートメントでセミコロンの後にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration">
<source>Insert space before colon for base or interface in type declaration</source>
<target state="translated">型宣言で、基本またはインターフェイス用のコロンの前にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_comma">
<source>Insert space before comma</source>
<target state="translated">コンマの前にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_dot">
<source>Insert space before dot</source>
<target state="translated">ピリオドの前にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_open_square_bracket">
<source>Insert space before open square bracket</source>
<target state="translated">始め角かっこの前にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_semicolon_in_for_statement">
<source>Insert space before semicolon in "for" statement</source>
<target state="translated">"for" ステートメントの前にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1">
<source>Insert space between method name and its opening parenthesis</source>
<target state="translated">メソッド名と始めかっこの間にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2">
<source>Insert space between method name and its opening parenthesis</source>
<target state="translated">メソッド名と始めかっこの間にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_argument_list_parentheses">
<source>Insert space within argument list parentheses</source>
<target state="translated">引数リストのかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_empty_argument_list_parentheses">
<source>Insert space within empty argument list parentheses</source>
<target state="translated">空の引数リストのかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_empty_parameter_list_parentheses">
<source>Insert space within empty parameter list parentheses</source>
<target state="translated">空のパラメーター リストのかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_empty_square_brackets">
<source>Insert space within empty square brackets</source>
<target state="translated">空の角かっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_parameter_list_parentheses">
<source>Insert space within parameter list parentheses</source>
<target state="translated">パラメーター リストのかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_parentheses_of_expressions">
<source>Insert space within parentheses of expressions</source>
<target state="translated">式のかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_parentheses_of_type_casts">
<source>Insert space within parentheses of type casts</source>
<target state="translated">型キャストのかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements">
<source>Insert spaces within parentheses of control flow statements</source>
<target state="translated">制御フロー ステートメントのかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_spaces_within_square_brackets">
<source>Insert spaces within square brackets</source>
<target state="translated">角かっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Inside_namespace">
<source>Inside namespace</source>
<target state="translated">namespace 内</target>
<note />
</trans-unit>
<trans-unit id="Label_Indentation">
<source>Label Indentation</source>
<target state="translated">ラベル インデント</target>
<note />
</trans-unit>
<trans-unit id="Leave_block_on_single_line">
<source>Leave block on single line</source>
<target state="translated">ブロックを単一行に配置する</target>
<note />
</trans-unit>
<trans-unit id="Leave_statements_and_member_declarations_on_the_same_line">
<source>Leave statements and member declarations on the same line</source>
<target state="translated">1 行に複数のステートメントとメンバー宣言を表示する</target>
<note />
</trans-unit>
<trans-unit id="Load_from_0">
<source>Load from: '{0}'</source>
<target state="translated">読み込み元: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Module_not_found">
<source>Module not found!</source>
<target state="translated">モジュールが見つかりません</target>
<note />
</trans-unit>
<trans-unit id="Never">
<source>Never</source>
<target state="translated">行わない</target>
<note />
</trans-unit>
<trans-unit id="Outside_namespace">
<source>Outside namespace</source>
<target state="translated">namespace 外</target>
<note />
</trans-unit>
<trans-unit id="Place_catch_on_new_line">
<source>Place "catch" on new line</source>
<target state="translated">新しい行に "catch" を配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_else_on_new_line">
<source>Place "else" on new line</source>
<target state="translated">新しい行に "else" を配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_finally_on_new_line">
<source>Place "finally" on new line</source>
<target state="translated">新しい行に "finally" を配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_members_in_anonymous_types_on_new_line">
<source>Place members in anonymous types on new line</source>
<target state="translated">新しい行に匿名型のメンバーを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_members_in_object_initializers_on_new_line">
<source>Place members in object initializers on new line</source>
<target state="translated">新しい行にオブジェクト初期化子のメンバーを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods">
<source>Place open brace on new line for anonymous methods</source>
<target state="translated">新しい行に匿名メソッドの始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_anonymous_types">
<source>Place open brace on new line for anonymous types</source>
<target state="translated">新しい行に匿名型の始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_control_blocks">
<source>Place open brace on new line for control blocks</source>
<target state="translated">新しい行にコントロール ブロック用の始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_lambda_expression">
<source>Place open brace on new line for lambda expression</source>
<target state="translated">新しい行にラムダ式の始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions">
<source>Place open brace on new line for methods and local functions</source>
<target state="translated">新しい行にメソッドとローカル関数の始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers">
<source>Place open brace on new line for object, collection, array, and with initializers</source>
<target state="translated">新しい行にオブジェクト、コレクション、配列、with 初期化子用の始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events">
<source>Place open brace on new line for properties, indexers, and events</source>
<target state="translated">プロパティ、インデクサー、イベントの新しい行に始めかっこを配置します</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors">
<source>Place open brace on new line for property, indexer, and event accessors</source>
<target state="translated">プロパティ、インデクサー、イベント アクセサーの新しい行に始めかっこを配置します</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_types">
<source>Place open brace on new line for types</source>
<target state="translated">新しい行に型の始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_query_expression_clauses_on_new_line">
<source>Place query expression clauses on new line</source>
<target state="translated">新しい行にクエリ式の句を配置する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_conditional_delegate_call">
<source>Prefer conditional delegate call</source>
<target state="translated">条件付きの代理呼び出しを優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_deconstructed_variable_declaration">
<source>Prefer deconstructed variable declaration</source>
<target state="translated">分解された変数宣言を優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_explicit_type">
<source>Prefer explicit type</source>
<target state="translated">明示的な型を優先してください</target>
<note />
</trans-unit>
<trans-unit id="Prefer_index_operator">
<source>Prefer index operator</source>
<target state="translated">インデックス演算子を優先</target>
<note />
</trans-unit>
<trans-unit id="Prefer_inlined_variable_declaration">
<source>Prefer inlined variable declaration</source>
<target state="translated">インライン変数宣言を優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_local_function_over_anonymous_function">
<source>Prefer local function over anonymous function</source>
<target state="translated">匿名関数よりローカル関数を優先します</target>
<note />
</trans-unit>
<trans-unit id="Prefer_null_check_over_type_check">
<source>Prefer 'null' check over type check</source>
<target state="new">Prefer 'null' check over type check</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching">
<source>Prefer pattern matching</source>
<target state="translated">パターン マッチングを優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching_over_as_with_null_check">
<source>Prefer pattern matching over 'as' with 'null' check</source>
<target state="translated">as' を 'null' チェックで使用するよりもパターン マッチングを優先します</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching_over_is_with_cast_check">
<source>Prefer pattern matching over 'is' with 'cast' check</source>
<target state="translated">is' を 'cast' チェックで使用するよりもパターン マッチングを優先します</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching_over_mixed_type_check">
<source>Prefer pattern matching over mixed type check</source>
<target state="translated">混合型チェックよりパターン マッチングを優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_range_operator">
<source>Prefer range operator</source>
<target state="translated">範囲演算子を優先</target>
<note />
</trans-unit>
<trans-unit id="Prefer_simple_default_expression">
<source>Prefer simple 'default' expression</source>
<target state="translated">単純な 'default' 式を優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_simple_using_statement">
<source>Prefer simple 'using' statement</source>
<target state="translated">単純な 'using' ステートメントを優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_static_local_functions">
<source>Prefer static local functions</source>
<target state="translated">静的ローカル関数を優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_switch_expression">
<source>Prefer switch expression</source>
<target state="translated">switch 式を優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_throw_expression">
<source>Prefer throw-expression</source>
<target state="translated">スロー式を優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_var">
<source>Prefer 'var'</source>
<target state="translated">var' を優先してください</target>
<note />
</trans-unit>
<trans-unit id="Preferred_using_directive_placement">
<source>Preferred 'using' directive placement</source>
<target state="translated">優先する 'using' ディレクティブの配置</target>
<note />
</trans-unit>
<trans-unit id="Press_TAB_to_insert">
<source> (Press TAB to insert)</source>
<target state="translated">(Tab キーを押して挿入)</target>
<note />
</trans-unit>
<trans-unit id="Resolve_0">
<source>Resolve: '{0}'</source>
<target state="translated">解決: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Resolve_module_0_of_1">
<source>Resolve module: '{0}' of '{1}'</source>
<target state="translated">モジュールの解決: '{1}' の '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Set_spacing_for_operators">
<source>Set spacing for operators</source>
<target state="translated">演算子のスペースを設定する</target>
<note />
</trans-unit>
<trans-unit id="Smart_Indenting">
<source>Smart Indenting</source>
<target state="translated">スマート インデント</target>
<note />
</trans-unit>
<trans-unit id="Split_string">
<source>Split string</source>
<target state="translated">文字列を分割します</target>
<note />
</trans-unit>
<trans-unit id="Unused_local">
<source>Unused local</source>
<target state="translated">未使用のローカル</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_accessors">
<source>Use expression body for accessors</source>
<target state="translated">アクセサーに式本体を使用する</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_constructors">
<source>Use expression body for constructors</source>
<target state="translated">コンストラクターに式本体を使用する</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_indexers">
<source>Use expression body for indexers</source>
<target state="translated">インデクサーに式本体を使用する</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_lambdas">
<source>Use expression body for lambdas</source>
<target state="translated">ラムダに式本体を使用します</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_local_functions">
<source>Use expression body for local functions</source>
<target state="translated">ローカル関数に式本体を使用します</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_methods">
<source>Use expression body for methods</source>
<target state="translated">メソッドに式本体を使用する</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_operators">
<source>Use expression body for operators</source>
<target state="translated">オペレーターに式本体を使用する</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_properties">
<source>Use expression body for properties</source>
<target state="translated">プロパティに式本体を使用する</target>
<note />
</trans-unit>
<trans-unit id="WARN_Version_mismatch_Expected_0_Got_1">
<source>WARN: Version mismatch. Expected: '{0}', Got: '{1}'</source>
<target state="translated">警告: バージョンが一致しません。必要なバージョン: '{0}'、現在のバージョン: '{1}'</target>
<note />
</trans-unit>
<trans-unit id="When_on_single_line">
<source>When on single line</source>
<target state="translated">1 行の場合</target>
<note />
</trans-unit>
<trans-unit id="When_possible">
<source>When possible</source>
<target state="translated">可能な場合</target>
<note />
</trans-unit>
<trans-unit id="When_variable_type_is_apparent">
<source>When variable type is apparent</source>
<target state="translated">変数の型が明らかな場合</target>
<note />
</trans-unit>
<trans-unit id="_0_items_in_cache">
<source>'{0}' items in cache</source>
<target state="translated">キャッシュ内の '{0}' 個の項目</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ja" original="../CSharpEditorResources.resx">
<body>
<trans-unit id="Add_Missing_Usings_on_Paste">
<source>Add Missing Usings on Paste</source>
<target state="translated">貼り付け時に欠落している usings を追加する</target>
<note>"usings" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Adding_missing_usings">
<source>Adding missing usings...</source>
<target state="translated">欠落している usings を追加しています...</target>
<note>Shown in a thread await dialog. "usings" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value">
<source>Avoid expression statements that implicitly ignore value</source>
<target state="translated">値を暗黙的に無視する式ステートメントを指定しないでください</target>
<note />
</trans-unit>
<trans-unit id="Avoid_unused_value_assignments">
<source>Avoid unused value assignments</source>
<target state="translated">使用されない値の代入を指定しないでください</target>
<note />
</trans-unit>
<trans-unit id="Chosen_version_0">
<source>Chosen version: '{0}'</source>
<target state="translated">選択されたバージョン: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Complete_statement_on_semicolon">
<source>Complete statement on ;</source>
<target state="translated">ステートメントを ; で完了させてください</target>
<note />
</trans-unit>
<trans-unit id="Could_not_find_by_name_0">
<source>Could not find by name: '{0}'</source>
<target state="translated">名前 '{0}' で見つけることができませんでした</target>
<note />
</trans-unit>
<trans-unit id="Decompilation_log">
<source>Decompilation log</source>
<target state="translated">逆コンパイルのログ</target>
<note />
</trans-unit>
<trans-unit id="Discard">
<source>Discard</source>
<target state="translated">破棄</target>
<note />
</trans-unit>
<trans-unit id="Elsewhere">
<source>Elsewhere</source>
<target state="translated">その他の場所</target>
<note />
</trans-unit>
<trans-unit id="Fix_interpolated_verbatim_string">
<source>Fix interpolated verbatim string</source>
<target state="translated">挿入された逐語的文字列を修正します</target>
<note />
</trans-unit>
<trans-unit id="For_built_in_types">
<source>For built-in types</source>
<target state="translated">ビルトイン型の場合</target>
<note />
</trans-unit>
<trans-unit id="Found_0_assemblies_for_1">
<source>Found '{0}' assemblies for '{1}':</source>
<target state="translated">'{1}' の '{0}' 個のアセンブリが見つかりました:</target>
<note />
</trans-unit>
<trans-unit id="Found_exact_match_0">
<source>Found exact match: '{0}'</source>
<target state="translated">完全一致が見つかりました: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Found_higher_version_match_0">
<source>Found higher version match: '{0}'</source>
<target state="translated">新しいバージョンの一致が見つかりました: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Found_single_assembly_0">
<source>Found single assembly: '{0}'</source>
<target state="translated">1 つのアセンブリが見つかりました: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Generate_Event_Subscription">
<source>Generate Event Subscription</source>
<target state="translated">イベント サブスクリプションの生成</target>
<note />
</trans-unit>
<trans-unit id="Ignore_spaces_in_declaration_statements">
<source>Ignore spaces in declaration statements</source>
<target state="translated">宣言ステートメント内のスペースを無視する</target>
<note />
</trans-unit>
<trans-unit id="Indent_block_contents">
<source>Indent block contents</source>
<target state="translated">ブロックの内容をインデントする</target>
<note />
</trans-unit>
<trans-unit id="Indent_case_contents">
<source>Indent case contents</source>
<target state="translated">case の内容をインデントする</target>
<note />
</trans-unit>
<trans-unit id="Indent_case_contents_when_block">
<source>Indent case contents (when block)</source>
<target state="translated">case の内容をインデントします (ブロックする場合)</target>
<note />
</trans-unit>
<trans-unit id="Indent_case_labels">
<source>Indent case labels</source>
<target state="translated">case ラベルをインデントする</target>
<note />
</trans-unit>
<trans-unit id="Indent_open_and_close_braces">
<source>Indent open and close braces</source>
<target state="translated">始めと終わりのかっこをインデントする</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_cast">
<source>Insert space after cast</source>
<target state="translated">キャストの後にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration">
<source>Insert space after colon for base or interface in type declaration</source>
<target state="translated">型宣言で、基本またはインターフェイス用のコロンの後にスペースを配置する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_comma">
<source>Insert space after comma</source>
<target state="translated">コンマの後にスペースを追加する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_dot">
<source>Insert space after dot</source>
<target state="translated">ピリオドの後にスペースを追加する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_keywords_in_control_flow_statements">
<source>Insert space after keywords in control flow statements</source>
<target state="translated">制御フロー ステートメント内のキーワードの後にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_semicolon_in_for_statement">
<source>Insert space after semicolon in "for" statement</source>
<target state="translated">"for" ステートメントでセミコロンの後にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration">
<source>Insert space before colon for base or interface in type declaration</source>
<target state="translated">型宣言で、基本またはインターフェイス用のコロンの前にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_comma">
<source>Insert space before comma</source>
<target state="translated">コンマの前にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_dot">
<source>Insert space before dot</source>
<target state="translated">ピリオドの前にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_open_square_bracket">
<source>Insert space before open square bracket</source>
<target state="translated">始め角かっこの前にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_semicolon_in_for_statement">
<source>Insert space before semicolon in "for" statement</source>
<target state="translated">"for" ステートメントの前にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1">
<source>Insert space between method name and its opening parenthesis</source>
<target state="translated">メソッド名と始めかっこの間にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2">
<source>Insert space between method name and its opening parenthesis</source>
<target state="translated">メソッド名と始めかっこの間にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_argument_list_parentheses">
<source>Insert space within argument list parentheses</source>
<target state="translated">引数リストのかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_empty_argument_list_parentheses">
<source>Insert space within empty argument list parentheses</source>
<target state="translated">空の引数リストのかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_empty_parameter_list_parentheses">
<source>Insert space within empty parameter list parentheses</source>
<target state="translated">空のパラメーター リストのかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_empty_square_brackets">
<source>Insert space within empty square brackets</source>
<target state="translated">空の角かっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_parameter_list_parentheses">
<source>Insert space within parameter list parentheses</source>
<target state="translated">パラメーター リストのかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_parentheses_of_expressions">
<source>Insert space within parentheses of expressions</source>
<target state="translated">式のかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_parentheses_of_type_casts">
<source>Insert space within parentheses of type casts</source>
<target state="translated">型キャストのかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements">
<source>Insert spaces within parentheses of control flow statements</source>
<target state="translated">制御フロー ステートメントのかっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Insert_spaces_within_square_brackets">
<source>Insert spaces within square brackets</source>
<target state="translated">角かっこ内にスペースを挿入する</target>
<note />
</trans-unit>
<trans-unit id="Inside_namespace">
<source>Inside namespace</source>
<target state="translated">namespace 内</target>
<note />
</trans-unit>
<trans-unit id="Label_Indentation">
<source>Label Indentation</source>
<target state="translated">ラベル インデント</target>
<note />
</trans-unit>
<trans-unit id="Leave_block_on_single_line">
<source>Leave block on single line</source>
<target state="translated">ブロックを単一行に配置する</target>
<note />
</trans-unit>
<trans-unit id="Leave_statements_and_member_declarations_on_the_same_line">
<source>Leave statements and member declarations on the same line</source>
<target state="translated">1 行に複数のステートメントとメンバー宣言を表示する</target>
<note />
</trans-unit>
<trans-unit id="Load_from_0">
<source>Load from: '{0}'</source>
<target state="translated">読み込み元: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Module_not_found">
<source>Module not found!</source>
<target state="translated">モジュールが見つかりません</target>
<note />
</trans-unit>
<trans-unit id="Never">
<source>Never</source>
<target state="translated">行わない</target>
<note />
</trans-unit>
<trans-unit id="Outside_namespace">
<source>Outside namespace</source>
<target state="translated">namespace 外</target>
<note />
</trans-unit>
<trans-unit id="Place_catch_on_new_line">
<source>Place "catch" on new line</source>
<target state="translated">新しい行に "catch" を配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_else_on_new_line">
<source>Place "else" on new line</source>
<target state="translated">新しい行に "else" を配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_finally_on_new_line">
<source>Place "finally" on new line</source>
<target state="translated">新しい行に "finally" を配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_members_in_anonymous_types_on_new_line">
<source>Place members in anonymous types on new line</source>
<target state="translated">新しい行に匿名型のメンバーを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_members_in_object_initializers_on_new_line">
<source>Place members in object initializers on new line</source>
<target state="translated">新しい行にオブジェクト初期化子のメンバーを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods">
<source>Place open brace on new line for anonymous methods</source>
<target state="translated">新しい行に匿名メソッドの始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_anonymous_types">
<source>Place open brace on new line for anonymous types</source>
<target state="translated">新しい行に匿名型の始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_control_blocks">
<source>Place open brace on new line for control blocks</source>
<target state="translated">新しい行にコントロール ブロック用の始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_lambda_expression">
<source>Place open brace on new line for lambda expression</source>
<target state="translated">新しい行にラムダ式の始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions">
<source>Place open brace on new line for methods and local functions</source>
<target state="translated">新しい行にメソッドとローカル関数の始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers">
<source>Place open brace on new line for object, collection, array, and with initializers</source>
<target state="translated">新しい行にオブジェクト、コレクション、配列、with 初期化子用の始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events">
<source>Place open brace on new line for properties, indexers, and events</source>
<target state="translated">プロパティ、インデクサー、イベントの新しい行に始めかっこを配置します</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors">
<source>Place open brace on new line for property, indexer, and event accessors</source>
<target state="translated">プロパティ、インデクサー、イベント アクセサーの新しい行に始めかっこを配置します</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_types">
<source>Place open brace on new line for types</source>
<target state="translated">新しい行に型の始めかっこを配置する</target>
<note />
</trans-unit>
<trans-unit id="Place_query_expression_clauses_on_new_line">
<source>Place query expression clauses on new line</source>
<target state="translated">新しい行にクエリ式の句を配置する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_conditional_delegate_call">
<source>Prefer conditional delegate call</source>
<target state="translated">条件付きの代理呼び出しを優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_deconstructed_variable_declaration">
<source>Prefer deconstructed variable declaration</source>
<target state="translated">分解された変数宣言を優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_explicit_type">
<source>Prefer explicit type</source>
<target state="translated">明示的な型を優先してください</target>
<note />
</trans-unit>
<trans-unit id="Prefer_index_operator">
<source>Prefer index operator</source>
<target state="translated">インデックス演算子を優先</target>
<note />
</trans-unit>
<trans-unit id="Prefer_inlined_variable_declaration">
<source>Prefer inlined variable declaration</source>
<target state="translated">インライン変数宣言を優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_local_function_over_anonymous_function">
<source>Prefer local function over anonymous function</source>
<target state="translated">匿名関数よりローカル関数を優先します</target>
<note />
</trans-unit>
<trans-unit id="Prefer_null_check_over_type_check">
<source>Prefer 'null' check over type check</source>
<target state="new">Prefer 'null' check over type check</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching">
<source>Prefer pattern matching</source>
<target state="translated">パターン マッチングを優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching_over_as_with_null_check">
<source>Prefer pattern matching over 'as' with 'null' check</source>
<target state="translated">as' を 'null' チェックで使用するよりもパターン マッチングを優先します</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching_over_is_with_cast_check">
<source>Prefer pattern matching over 'is' with 'cast' check</source>
<target state="translated">is' を 'cast' チェックで使用するよりもパターン マッチングを優先します</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching_over_mixed_type_check">
<source>Prefer pattern matching over mixed type check</source>
<target state="translated">混合型チェックよりパターン マッチングを優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_range_operator">
<source>Prefer range operator</source>
<target state="translated">範囲演算子を優先</target>
<note />
</trans-unit>
<trans-unit id="Prefer_simple_default_expression">
<source>Prefer simple 'default' expression</source>
<target state="translated">単純な 'default' 式を優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_simple_using_statement">
<source>Prefer simple 'using' statement</source>
<target state="translated">単純な 'using' ステートメントを優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_static_local_functions">
<source>Prefer static local functions</source>
<target state="translated">静的ローカル関数を優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_switch_expression">
<source>Prefer switch expression</source>
<target state="translated">switch 式を優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_throw_expression">
<source>Prefer throw-expression</source>
<target state="translated">スロー式を優先する</target>
<note />
</trans-unit>
<trans-unit id="Prefer_var">
<source>Prefer 'var'</source>
<target state="translated">var' を優先してください</target>
<note />
</trans-unit>
<trans-unit id="Preferred_using_directive_placement">
<source>Preferred 'using' directive placement</source>
<target state="translated">優先する 'using' ディレクティブの配置</target>
<note />
</trans-unit>
<trans-unit id="Press_TAB_to_insert">
<source> (Press TAB to insert)</source>
<target state="translated">(Tab キーを押して挿入)</target>
<note />
</trans-unit>
<trans-unit id="Resolve_0">
<source>Resolve: '{0}'</source>
<target state="translated">解決: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Resolve_module_0_of_1">
<source>Resolve module: '{0}' of '{1}'</source>
<target state="translated">モジュールの解決: '{1}' の '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Set_spacing_for_operators">
<source>Set spacing for operators</source>
<target state="translated">演算子のスペースを設定する</target>
<note />
</trans-unit>
<trans-unit id="Smart_Indenting">
<source>Smart Indenting</source>
<target state="translated">スマート インデント</target>
<note />
</trans-unit>
<trans-unit id="Split_string">
<source>Split string</source>
<target state="translated">文字列を分割します</target>
<note />
</trans-unit>
<trans-unit id="Unused_local">
<source>Unused local</source>
<target state="translated">未使用のローカル</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_accessors">
<source>Use expression body for accessors</source>
<target state="translated">アクセサーに式本体を使用する</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_constructors">
<source>Use expression body for constructors</source>
<target state="translated">コンストラクターに式本体を使用する</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_indexers">
<source>Use expression body for indexers</source>
<target state="translated">インデクサーに式本体を使用する</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_lambdas">
<source>Use expression body for lambdas</source>
<target state="translated">ラムダに式本体を使用します</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_local_functions">
<source>Use expression body for local functions</source>
<target state="translated">ローカル関数に式本体を使用します</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_methods">
<source>Use expression body for methods</source>
<target state="translated">メソッドに式本体を使用する</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_operators">
<source>Use expression body for operators</source>
<target state="translated">オペレーターに式本体を使用する</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_properties">
<source>Use expression body for properties</source>
<target state="translated">プロパティに式本体を使用する</target>
<note />
</trans-unit>
<trans-unit id="WARN_Version_mismatch_Expected_0_Got_1">
<source>WARN: Version mismatch. Expected: '{0}', Got: '{1}'</source>
<target state="translated">警告: バージョンが一致しません。必要なバージョン: '{0}'、現在のバージョン: '{1}'</target>
<note />
</trans-unit>
<trans-unit id="When_on_single_line">
<source>When on single line</source>
<target state="translated">1 行の場合</target>
<note />
</trans-unit>
<trans-unit id="When_possible">
<source>When possible</source>
<target state="translated">可能な場合</target>
<note />
</trans-unit>
<trans-unit id="When_variable_type_is_apparent">
<source>When variable type is apparent</source>
<target state="translated">変数の型が明らかな場合</target>
<note />
</trans-unit>
<trans-unit id="_0_items_in_cache">
<source>'{0}' items in cache</source>
<target state="translated">キャッシュ内の '{0}' 個の項目</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Workspaces/Core/Portable/Workspace/Host/EventListener/EventListenerMetadata.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// MEF metadata class used to find exports declared for a specific <see cref="IEventListener"/>.
/// </summary>
internal class EventListenerMetadata : WorkspaceKindMetadata
{
public string Service { get; }
public EventListenerMetadata(IDictionary<string, object> data)
: base(data)
{
this.Service = (string)data.GetValueOrDefault("Service");
}
public EventListenerMetadata(string service, params string[] workspaceKinds)
: base(workspaceKinds)
{
if (workspaceKinds?.Length == 0)
{
throw new ArgumentException(nameof(workspaceKinds));
}
this.Service = service ?? throw new ArgumentException(nameof(service));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// MEF metadata class used to find exports declared for a specific <see cref="IEventListener"/>.
/// </summary>
internal class EventListenerMetadata : WorkspaceKindMetadata
{
public string Service { get; }
public EventListenerMetadata(IDictionary<string, object> data)
: base(data)
{
this.Service = (string)data.GetValueOrDefault("Service");
}
public EventListenerMetadata(string service, params string[] workspaceKinds)
: base(workspaceKinds)
{
if (workspaceKinds?.Length == 0)
{
throw new ArgumentException(nameof(workspaceKinds));
}
this.Service = service ?? throw new ArgumentException(nameof(service));
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/VisualBasic/Portable/Binding/MethodBodyBinder.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.Concurrent
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Provides context for binding body of a MethodSymbol.
''' </summary>
Friend NotInheritable Class MethodBodyBinder
Inherits SubOrFunctionBodyBinder
Private ReadOnly _functionValue As LocalSymbol
''' <summary>
''' Create binder for binding the body of a method.
''' </summary>
Public Sub New(methodSymbol As MethodSymbol, root As SyntaxNode, containingBinder As Binder)
MyBase.New(methodSymbol, root, containingBinder)
' this could be a synthetic method that does not have syntax for the method body
_functionValue = CreateFunctionValueLocal(methodSymbol, root)
If _functionValue IsNot Nothing AndAlso Not methodSymbol.IsUserDefinedOperator() Then
Dim parameterName = _functionValue.Name
' Note: the name can be empty in case syntax errors in function/property definition
If Not String.IsNullOrEmpty(parameterName) Then
' Note that, if there is a parameter with this name, we are overriding it in the map.
_parameterMap(parameterName) = _functionValue
End If
End If
End Sub
Private Function CreateFunctionValueLocal(methodSymbol As MethodSymbol, root As SyntaxNode) As LocalSymbol
Dim methodBlock = TryCast(root, MethodBlockBaseSyntax)
Debug.Assert(Not TypeOf methodSymbol Is SourceMethodSymbol OrElse
Me.IsSemanticModelBinder OrElse
(methodBlock Is DirectCast(methodSymbol, SourceMethodSymbol).BlockSyntax AndAlso
methodBlock IsNot Nothing))
If methodBlock Is Nothing Then
Return Nothing
End If
' Create a local for the function return value. The local's type is the same as the function's return type
Select Case methodBlock.Kind
Case SyntaxKind.FunctionBlock
Dim begin As MethodStatementSyntax = DirectCast(methodBlock, MethodBlockSyntax).SubOrFunctionStatement
' Note, it is an error if a parameter has the same name as the function.
Return LocalSymbol.Create(methodSymbol, Me, begin.Identifier, LocalDeclarationKind.FunctionValue,
If(methodSymbol.ReturnType.IsVoidType(), ErrorTypeSymbol.UnknownResultType, methodSymbol.ReturnType))
Case SyntaxKind.GetAccessorBlock
If methodBlock.Parent IsNot Nothing AndAlso
methodBlock.Parent.Kind = SyntaxKind.PropertyBlock Then
Debug.Assert(Not methodSymbol.ReturnType.IsVoidType())
Dim propertySyntax As PropertyStatementSyntax = DirectCast(methodBlock.Parent, PropertyBlockSyntax).PropertyStatement
Dim identifier = propertySyntax.Identifier
Return LocalSymbol.Create(methodSymbol, Me, identifier, LocalDeclarationKind.FunctionValue, methodSymbol.ReturnType)
End If
Case SyntaxKind.OperatorBlock
Debug.Assert(Not methodSymbol.ReturnType.IsVoidType())
' Function Return Value variable isn't accessible within an operator body
Return New SynthesizedLocal(methodSymbol, methodSymbol.ReturnType, SynthesizedLocalKind.FunctionReturnValue, DirectCast(methodBlock, OperatorBlockSyntax).BlockStatement)
Case SyntaxKind.AddHandlerAccessorBlock
If DirectCast(methodSymbol.AssociatedSymbol, EventSymbol).IsWindowsRuntimeEvent AndAlso
methodBlock.Parent IsNot Nothing AndAlso
methodBlock.Parent.Kind = SyntaxKind.EventBlock Then
Debug.Assert(Not methodSymbol.ReturnType.IsVoidType())
Dim eventSyntax As EventStatementSyntax = DirectCast(methodBlock.Parent, EventBlockSyntax).EventStatement
Dim identifier = eventSyntax.Identifier
' NOTE: To avoid a breaking change, we reproduce the dev11 behavior - the name of the local is
' taken from the name of the accessor, rather than the name of the event (as it would be for a property).
Return LocalSymbol.Create(methodSymbol, Me, identifier, LocalDeclarationKind.FunctionValue, methodSymbol.ReturnType, methodSymbol.Name)
End If
Case Else
Debug.Assert(methodSymbol.IsSub)
End Select
Return Nothing
End Function
Public Overrides Function GetLocalForFunctionValue() As LocalSymbol
Return _functionValue
End Function
Public Overrides ReadOnly Property IsInQuery As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property SuppressCallerInfo As Boolean
Get
Return DirectCast(ContainingMember, MethodSymbol).IsImplicitlyDeclared AndAlso TypeOf ContainingMember Is SynthesizedMyGroupCollectionPropertyAccessorSymbol
End Get
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Concurrent
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Provides context for binding body of a MethodSymbol.
''' </summary>
Friend NotInheritable Class MethodBodyBinder
Inherits SubOrFunctionBodyBinder
Private ReadOnly _functionValue As LocalSymbol
''' <summary>
''' Create binder for binding the body of a method.
''' </summary>
Public Sub New(methodSymbol As MethodSymbol, root As SyntaxNode, containingBinder As Binder)
MyBase.New(methodSymbol, root, containingBinder)
' this could be a synthetic method that does not have syntax for the method body
_functionValue = CreateFunctionValueLocal(methodSymbol, root)
If _functionValue IsNot Nothing AndAlso Not methodSymbol.IsUserDefinedOperator() Then
Dim parameterName = _functionValue.Name
' Note: the name can be empty in case syntax errors in function/property definition
If Not String.IsNullOrEmpty(parameterName) Then
' Note that, if there is a parameter with this name, we are overriding it in the map.
_parameterMap(parameterName) = _functionValue
End If
End If
End Sub
Private Function CreateFunctionValueLocal(methodSymbol As MethodSymbol, root As SyntaxNode) As LocalSymbol
Dim methodBlock = TryCast(root, MethodBlockBaseSyntax)
Debug.Assert(Not TypeOf methodSymbol Is SourceMethodSymbol OrElse
Me.IsSemanticModelBinder OrElse
(methodBlock Is DirectCast(methodSymbol, SourceMethodSymbol).BlockSyntax AndAlso
methodBlock IsNot Nothing))
If methodBlock Is Nothing Then
Return Nothing
End If
' Create a local for the function return value. The local's type is the same as the function's return type
Select Case methodBlock.Kind
Case SyntaxKind.FunctionBlock
Dim begin As MethodStatementSyntax = DirectCast(methodBlock, MethodBlockSyntax).SubOrFunctionStatement
' Note, it is an error if a parameter has the same name as the function.
Return LocalSymbol.Create(methodSymbol, Me, begin.Identifier, LocalDeclarationKind.FunctionValue,
If(methodSymbol.ReturnType.IsVoidType(), ErrorTypeSymbol.UnknownResultType, methodSymbol.ReturnType))
Case SyntaxKind.GetAccessorBlock
If methodBlock.Parent IsNot Nothing AndAlso
methodBlock.Parent.Kind = SyntaxKind.PropertyBlock Then
Debug.Assert(Not methodSymbol.ReturnType.IsVoidType())
Dim propertySyntax As PropertyStatementSyntax = DirectCast(methodBlock.Parent, PropertyBlockSyntax).PropertyStatement
Dim identifier = propertySyntax.Identifier
Return LocalSymbol.Create(methodSymbol, Me, identifier, LocalDeclarationKind.FunctionValue, methodSymbol.ReturnType)
End If
Case SyntaxKind.OperatorBlock
Debug.Assert(Not methodSymbol.ReturnType.IsVoidType())
' Function Return Value variable isn't accessible within an operator body
Return New SynthesizedLocal(methodSymbol, methodSymbol.ReturnType, SynthesizedLocalKind.FunctionReturnValue, DirectCast(methodBlock, OperatorBlockSyntax).BlockStatement)
Case SyntaxKind.AddHandlerAccessorBlock
If DirectCast(methodSymbol.AssociatedSymbol, EventSymbol).IsWindowsRuntimeEvent AndAlso
methodBlock.Parent IsNot Nothing AndAlso
methodBlock.Parent.Kind = SyntaxKind.EventBlock Then
Debug.Assert(Not methodSymbol.ReturnType.IsVoidType())
Dim eventSyntax As EventStatementSyntax = DirectCast(methodBlock.Parent, EventBlockSyntax).EventStatement
Dim identifier = eventSyntax.Identifier
' NOTE: To avoid a breaking change, we reproduce the dev11 behavior - the name of the local is
' taken from the name of the accessor, rather than the name of the event (as it would be for a property).
Return LocalSymbol.Create(methodSymbol, Me, identifier, LocalDeclarationKind.FunctionValue, methodSymbol.ReturnType, methodSymbol.Name)
End If
Case Else
Debug.Assert(methodSymbol.IsSub)
End Select
Return Nothing
End Function
Public Overrides Function GetLocalForFunctionValue() As LocalSymbol
Return _functionValue
End Function
Public Overrides ReadOnly Property IsInQuery As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property SuppressCallerInfo As Boolean
Get
Return DirectCast(ContainingMember, MethodSymbol).IsImplicitlyDeclared AndAlso TypeOf ContainingMember Is SynthesizedMyGroupCollectionPropertyAccessorSymbol
End Get
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/EditorFeatures/CSharpTest2/Recommendations/OutKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class OutKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInterfaceTypeVarianceAfterAngle()
{
await VerifyKeywordAsync(
@"interface IGoo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInterfaceTypeVarianceNotAfterOut()
{
await VerifyAbsenceAsync(
@"interface IGoo<in $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInterfaceTypeVarianceAfterComma()
{
await VerifyKeywordAsync(
@"interface IGoo<Goo, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInterfaceTypeVarianceAfterAttribute()
{
await VerifyKeywordAsync(
@"interface IGoo<[Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestDelegateTypeVarianceAfterAngle()
{
await VerifyKeywordAsync(
@"delegate void D<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestDelegateTypeVarianceAfterComma()
{
await VerifyKeywordAsync(
@"delegate void D<Goo, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestDelegateTypeVarianceAfterAttribute()
{
await VerifyKeywordAsync(
@"delegate void D<[Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotOutClassTypeVarianceAfterAngle()
{
await VerifyAbsenceAsync(
@"class IGoo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotOutStructTypeVarianceAfterAngle()
{
await VerifyAbsenceAsync(
@"struct IGoo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotOutBaseListAfterAngle()
{
await VerifyAbsenceAsync(
@"interface IGoo : Bar<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGenericMethod()
{
await VerifyAbsenceAsync(
@"interface IGoo {
void Goo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterOut()
{
await VerifyAbsenceAsync(
@"class C {
void Goo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Goo]$$");
}
[WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThisConstructorInitializer()
{
await VerifyKeywordAsync(
@"class C {
public C():this($$");
}
[WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThisConstructorInitializerNamedArgument()
{
await VerifyKeywordAsync(
@"class C {
public C():this(Goo:$$");
}
[WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterBaseConstructorInitializer()
{
await VerifyKeywordAsync(
@"class C {
public C():base($$");
}
[WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterBaseConstructorInitializerNamedArgument()
{
await VerifyKeywordAsync(
@"class C {
public C():base(5, Goo:$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(24079, "https://github.com/dotnet/roslyn/issues/24079")]
public async Task TestNotAfterOperator()
{
await VerifyAbsenceAsync(
@"class C {
static int operator +($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDestructor()
{
await VerifyAbsenceAsync(
@"class C {
~C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterIndexer()
{
await VerifyAbsenceAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInObjectCreationAfterOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
new Bar($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterRef()
{
await VerifyAbsenceAsync(
@"class C {
void Goo() {
new Bar(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterOutParam()
{
await VerifyAbsenceAsync(
@"class C {
void Goo() {
new Bar(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInObjectCreationAfterComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
new Bar(baz, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInObjectCreationAfterSecondComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
new Bar(baz, quux, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInObjectCreationAfterSecondNamedParam()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
new Bar(baz: 4, quux: $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInInvocationExpression()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
Bar($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInInvocationAfterComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
Bar(baz, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInInvocationAfterSecondComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
Bar(baz, quux, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInInvocationAfterSecondNamedParam()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
Bar(baz: 4, quux: $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLambdaDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLambdaDeclaration2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = (ref int a, $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLambdaDeclaration3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = (int a, $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = delegate ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateDeclaration2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = delegate (a, $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateDeclaration3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = delegate (int a, $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefParameterList()
{
var text = @"Class c
{
/// <see cref=""main($$""/>
void main(out goo) { }
}";
await VerifyKeywordAsync(text);
}
[WorkItem(22253, "https://github.com/dotnet/roslyn/issues/22253")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"void F(int x, $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestExtensionMethods_FirstParameter()
{
await VerifyKeywordAsync(
@"static class Extensions {
static void Extension($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword()
{
await VerifyAbsenceAsync(
@"static class Extensions {
static void Extension(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestExtensionMethods_SecondParameter()
{
await VerifyKeywordAsync(
@"static class Extensions {
static void Extension(this int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword()
{
await VerifyAbsenceAsync(
@"static class Extensions {
static void Extension(this int i, this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeNoExistingModifiers()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<$$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("in")]
[InlineData("out")]
[InlineData("ref")]
[InlineData("ref readonly")]
public async Task TestNotInFunctionPointerTypeExistingModifiers(string modifier)
{
await VerifyAbsenceAsync($@"
class C
{{
delegate*<{modifier} $$");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class OutKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInterfaceTypeVarianceAfterAngle()
{
await VerifyKeywordAsync(
@"interface IGoo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInterfaceTypeVarianceNotAfterOut()
{
await VerifyAbsenceAsync(
@"interface IGoo<in $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInterfaceTypeVarianceAfterComma()
{
await VerifyKeywordAsync(
@"interface IGoo<Goo, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInterfaceTypeVarianceAfterAttribute()
{
await VerifyKeywordAsync(
@"interface IGoo<[Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestDelegateTypeVarianceAfterAngle()
{
await VerifyKeywordAsync(
@"delegate void D<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestDelegateTypeVarianceAfterComma()
{
await VerifyKeywordAsync(
@"delegate void D<Goo, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestDelegateTypeVarianceAfterAttribute()
{
await VerifyKeywordAsync(
@"delegate void D<[Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotOutClassTypeVarianceAfterAngle()
{
await VerifyAbsenceAsync(
@"class IGoo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotOutStructTypeVarianceAfterAngle()
{
await VerifyAbsenceAsync(
@"struct IGoo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotOutBaseListAfterAngle()
{
await VerifyAbsenceAsync(
@"interface IGoo : Bar<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGenericMethod()
{
await VerifyAbsenceAsync(
@"interface IGoo {
void Goo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterOut()
{
await VerifyAbsenceAsync(
@"class C {
void Goo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Goo]$$");
}
[WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThisConstructorInitializer()
{
await VerifyKeywordAsync(
@"class C {
public C():this($$");
}
[WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThisConstructorInitializerNamedArgument()
{
await VerifyKeywordAsync(
@"class C {
public C():this(Goo:$$");
}
[WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterBaseConstructorInitializer()
{
await VerifyKeywordAsync(
@"class C {
public C():base($$");
}
[WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterBaseConstructorInitializerNamedArgument()
{
await VerifyKeywordAsync(
@"class C {
public C():base(5, Goo:$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(24079, "https://github.com/dotnet/roslyn/issues/24079")]
public async Task TestNotAfterOperator()
{
await VerifyAbsenceAsync(
@"class C {
static int operator +($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDestructor()
{
await VerifyAbsenceAsync(
@"class C {
~C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterIndexer()
{
await VerifyAbsenceAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInObjectCreationAfterOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
new Bar($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterRef()
{
await VerifyAbsenceAsync(
@"class C {
void Goo() {
new Bar(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterOutParam()
{
await VerifyAbsenceAsync(
@"class C {
void Goo() {
new Bar(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInObjectCreationAfterComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
new Bar(baz, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInObjectCreationAfterSecondComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
new Bar(baz, quux, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInObjectCreationAfterSecondNamedParam()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
new Bar(baz: 4, quux: $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInInvocationExpression()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
Bar($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInInvocationAfterComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
Bar(baz, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInInvocationAfterSecondComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
Bar(baz, quux, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInInvocationAfterSecondNamedParam()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
Bar(baz: 4, quux: $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLambdaDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLambdaDeclaration2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = (ref int a, $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLambdaDeclaration3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = (int a, $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = delegate ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateDeclaration2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = delegate (a, $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateDeclaration3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = delegate (int a, $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefParameterList()
{
var text = @"Class c
{
/// <see cref=""main($$""/>
void main(out goo) { }
}";
await VerifyKeywordAsync(text);
}
[WorkItem(22253, "https://github.com/dotnet/roslyn/issues/22253")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"void F(int x, $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestExtensionMethods_FirstParameter()
{
await VerifyKeywordAsync(
@"static class Extensions {
static void Extension($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword()
{
await VerifyAbsenceAsync(
@"static class Extensions {
static void Extension(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestExtensionMethods_SecondParameter()
{
await VerifyKeywordAsync(
@"static class Extensions {
static void Extension(this int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword()
{
await VerifyAbsenceAsync(
@"static class Extensions {
static void Extension(this int i, this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeNoExistingModifiers()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<$$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("in")]
[InlineData("out")]
[InlineData("ref")]
[InlineData("ref readonly")]
public async Task TestNotInFunctionPointerTypeExistingModifiers(string modifier)
{
await VerifyAbsenceAsync($@"
class C
{{
delegate*<{modifier} $$");
}
}
}
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Scripting/VisualBasic/VisualBasicScript.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 System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Scripting
Imports Microsoft.CodeAnalysis.Scripting.Hosting
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting
''' <summary>
''' A factory for creating and running Visual Basic scripts.
''' </summary>
Public NotInheritable Class VisualBasicScript
Private Sub New()
End Sub
''' <summary>
''' Create a new Visual Basic script.
''' </summary>
Public Shared Function Create(Of T)(code As String,
Optional options As ScriptOptions = Nothing,
Optional globalsType As Type = Nothing,
Optional assemblyLoader As InteractiveAssemblyLoader = Nothing) As Script(Of T)
Return Script.CreateInitialScript(Of T)(VisualBasicScriptCompiler.Instance, SourceText.From(If(code, String.Empty)), options, globalsType, assemblyLoader)
End Function
''' <summary>
''' Create a new Visual Basic script.
''' </summary>
Public Shared Function Create(code As String,
Optional options As ScriptOptions = Nothing,
Optional globalsType As Type = Nothing,
Optional assemblyLoader As InteractiveAssemblyLoader = Nothing) As Script(Of Object)
Return Create(Of Object)(code, options, globalsType, assemblyLoader)
End Function
''' <summary>
''' Run a Visual Basic script.
''' </summary>
Public Shared Function RunAsync(Of T)(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of ScriptState(Of T))
Return Create(Of T)(code, options, globals?.GetType()).RunAsync(globals, cancellationToken)
End Function
''' <summary>
''' Run a Visual Basic script.
''' </summary>
Public Shared Function RunAsync(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of ScriptState(Of Object))
Return RunAsync(Of Object)(code, options, globals, cancellationToken)
End Function
''' <summary>
''' Run a Visual Basic script and return its resulting value.
''' </summary>
Public Shared Function EvaluateAsync(Of T)(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of T)
Return RunAsync(Of T)(code, options, globals, cancellationToken).GetEvaluationResultAsync()
End Function
''' <summary>
''' Run a Visual Basic script and return its resulting value.
''' </summary>
Public Shared Function EvaluateAsync(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of Object)
Return EvaluateAsync(Of Object)(code, Nothing, globals, cancellationToken)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Scripting
Imports Microsoft.CodeAnalysis.Scripting.Hosting
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting
''' <summary>
''' A factory for creating and running Visual Basic scripts.
''' </summary>
Public NotInheritable Class VisualBasicScript
Private Sub New()
End Sub
''' <summary>
''' Create a new Visual Basic script.
''' </summary>
Public Shared Function Create(Of T)(code As String,
Optional options As ScriptOptions = Nothing,
Optional globalsType As Type = Nothing,
Optional assemblyLoader As InteractiveAssemblyLoader = Nothing) As Script(Of T)
Return Script.CreateInitialScript(Of T)(VisualBasicScriptCompiler.Instance, SourceText.From(If(code, String.Empty)), options, globalsType, assemblyLoader)
End Function
''' <summary>
''' Create a new Visual Basic script.
''' </summary>
Public Shared Function Create(code As String,
Optional options As ScriptOptions = Nothing,
Optional globalsType As Type = Nothing,
Optional assemblyLoader As InteractiveAssemblyLoader = Nothing) As Script(Of Object)
Return Create(Of Object)(code, options, globalsType, assemblyLoader)
End Function
''' <summary>
''' Run a Visual Basic script.
''' </summary>
Public Shared Function RunAsync(Of T)(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of ScriptState(Of T))
Return Create(Of T)(code, options, globals?.GetType()).RunAsync(globals, cancellationToken)
End Function
''' <summary>
''' Run a Visual Basic script.
''' </summary>
Public Shared Function RunAsync(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of ScriptState(Of Object))
Return RunAsync(Of Object)(code, options, globals, cancellationToken)
End Function
''' <summary>
''' Run a Visual Basic script and return its resulting value.
''' </summary>
Public Shared Function EvaluateAsync(Of T)(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of T)
Return RunAsync(Of T)(code, options, globals, cancellationToken).GetEvaluationResultAsync()
End Function
''' <summary>
''' Run a Visual Basic script and return its resulting value.
''' </summary>
Public Shared Function EvaluateAsync(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of Object)
Return EvaluateAsync(Of Object)(code, Nothing, globals, cancellationToken)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,294 | Report telemetry for HotReload sessions | Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | tmat | 2021-07-30T20:02:25Z | 2021-08-04T15:47:54Z | ab1130af679d8908e85735d43b26f8e4f10198e5 | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128
Also add solution update logging. | ./src/Compilers/Core/Rebuild/MetadataCompilationOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Linq;
using System.Diagnostics.CodeAnalysis;
using System;
using Microsoft.Extensions.Logging;
namespace Microsoft.CodeAnalysis.Rebuild
{
internal class MetadataCompilationOptions
{
private readonly ImmutableArray<(string optionName, string value)> _options;
public MetadataCompilationOptions(ImmutableArray<(string optionName, string value)> options)
{
_options = options;
}
public int Length => _options.Length;
public bool TryGetUniqueOption(ILogger logger, string optionName, [NotNullWhen(true)] out string? value)
{
var result = TryGetUniqueOption(optionName, out value);
logger.LogInformation($"{optionName} - {value}");
return result;
}
/// <summary>
/// Attempts to get an option value. Returns false if the option value does not
/// exist OR if it exists more than once
/// </summary>
public bool TryGetUniqueOption(string optionName, [NotNullWhen(true)] out string? value)
{
value = null;
var optionValues = _options.Where(pair => pair.optionName == optionName).ToArray();
if (optionValues.Length != 1)
{
return false;
}
value = optionValues[0].value;
return true;
}
public string GetUniqueOption(string optionName)
{
var optionValues = _options.Where(pair => pair.optionName == optionName).ToArray();
if (optionValues.Length != 1)
{
throw new InvalidOperationException(string.Format(RebuildResources._0_exists_1_times_in_compilation_options, optionName, optionValues.Length));
}
return optionValues[0].value;
}
public string? OptionToString(string option) => TryGetUniqueOption(option, out var value) ? value : null;
public bool? OptionToBool(string option) => TryGetUniqueOption(option, out var value) ? ToBool(value) : null;
public T? OptionToEnum<T>(string option) where T : struct => TryGetUniqueOption(option, out var value) ? ToEnum<T>(value) : null;
public static bool? ToBool(string value) => bool.TryParse(value, out var boolValue) ? boolValue : null;
public static T? ToEnum<T>(string value) where T : struct => Enum.TryParse<T>(value, out var enumValue) ? enumValue : null;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Linq;
using System.Diagnostics.CodeAnalysis;
using System;
using Microsoft.Extensions.Logging;
namespace Microsoft.CodeAnalysis.Rebuild
{
internal class MetadataCompilationOptions
{
private readonly ImmutableArray<(string optionName, string value)> _options;
public MetadataCompilationOptions(ImmutableArray<(string optionName, string value)> options)
{
_options = options;
}
public int Length => _options.Length;
public bool TryGetUniqueOption(ILogger logger, string optionName, [NotNullWhen(true)] out string? value)
{
var result = TryGetUniqueOption(optionName, out value);
logger.LogInformation($"{optionName} - {value}");
return result;
}
/// <summary>
/// Attempts to get an option value. Returns false if the option value does not
/// exist OR if it exists more than once
/// </summary>
public bool TryGetUniqueOption(string optionName, [NotNullWhen(true)] out string? value)
{
value = null;
var optionValues = _options.Where(pair => pair.optionName == optionName).ToArray();
if (optionValues.Length != 1)
{
return false;
}
value = optionValues[0].value;
return true;
}
public string GetUniqueOption(string optionName)
{
var optionValues = _options.Where(pair => pair.optionName == optionName).ToArray();
if (optionValues.Length != 1)
{
throw new InvalidOperationException(string.Format(RebuildResources._0_exists_1_times_in_compilation_options, optionName, optionValues.Length));
}
return optionValues[0].value;
}
public string? OptionToString(string option) => TryGetUniqueOption(option, out var value) ? value : null;
public bool? OptionToBool(string option) => TryGetUniqueOption(option, out var value) ? ToBool(value) : null;
public T? OptionToEnum<T>(string option) where T : struct => TryGetUniqueOption(option, out var value) ? ToEnum<T>(value) : null;
public static bool? ToBool(string value) => bool.TryParse(value, out var boolValue) ? boolValue : null;
public static T? ToEnum<T>(string value) where T : struct => Enum.TryParse<T>(value, out var enumValue) ? enumValue : null;
}
}
| -1 |
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle;
using Microsoft.CodeAnalysis.CSharp.TypeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType
{
public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public UseExplicitTypeTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseExplicitTypeDiagnosticAnalyzer(), new UseExplicitTypeCodeFixProvider());
private readonly CodeStyleOption2<bool> offWithSilent = new CodeStyleOption2<bool>(false, NotificationOption2.Silent);
private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion);
private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion);
private readonly CodeStyleOption2<bool> offWithWarning = new CodeStyleOption2<bool>(false, NotificationOption2.Warning);
private readonly CodeStyleOption2<bool> offWithError = new CodeStyleOption2<bool>(false, NotificationOption2.Error);
// specify all options explicitly to override defaults.
private OptionsCollection ExplicitTypeEverywhere() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithInfo },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithInfo },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeExceptWhereApparent() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithInfo },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeForBuiltInTypesOnly() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, onWithInfo },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeEnforcements() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithWarning },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithError },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeSilentEnforcement() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithSilent },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithSilent },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithSilent },
};
#region Error Cases
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldDeclaration()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
[|var|] _myfield = 5;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldLikeEvents()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
public event [|var|] _myevent;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnAnonymousMethodExpression()
{
var before =
@"using System;
class Program
{
void Method()
{
[|var|] comparer = delegate (string value) {
return value != ""0"";
};
}
}";
var after =
@"using System;
class Program
{
void Method()
{
Func<string, bool> comparer = delegate (string value) {
return value != ""0"";
};
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnLambdaExpression()
{
var before =
@"using System;
class Program
{
void Method()
{
[|var|] x = (int y) => y * y;
}
}";
var after =
@"using System;
class Program
{
void Method()
{
Func<int, int> x = (int y) => y * y;
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithMultipleDeclarators()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = 5, y = x;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithoutInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotDuringConflicts()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] p = new var();
}
class var
{
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotIfAlreadyExplicitlyTyped()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|Program|] p = new Program();
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")]
public async Task NotIfRefTypeAlreadyExplicitlyTyped()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
struct Program
{
void Method()
{
ref [|Program|] p = Ref();
}
ref Program Ref() => throw null;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnRHS()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
var c = new [|var|]();
}
}
class var
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorSymbol()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new Goo();
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorConvertedType_ForEachVariableStatement()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
void M()
{
// Error CS1061: 'KeyValuePair<int, int>' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'KeyValuePair<int, int>' could be found (are you missing a using directive or an assembly reference?)
// Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'KeyValuePair<int, int>', with 2 out parameters and a void return type.
foreach ([|var|] (key, value) in new Dictionary<int, int>())
{
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorConvertedType_AssignmentExpressionStatement()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
void M(C c)
{
// Error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type.
[|var|] (key, value) = c;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
#endregion
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InArrayType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = new Program[0];
}
}";
var after = @"
class Program
{
void Method()
{
Program[] x = new Program[0];
}
}";
// The type is apparent and not intrinsic
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InArrayTypeWithIntrinsicType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = new int[0];
}
}";
var after = @"
class Program
{
void Method()
{
int[] x = new int[0];
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InNullableIntrinsicType()
{
var before = @"
class Program
{
void Method(int? x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(int? x)
{
int? y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")]
public async Task InNativeIntIntrinsicType()
{
var before = @"
class Program
{
void Method(nint x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(nint x)
{
nint y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")]
public async Task InNativeUnsignedIntIntrinsicType()
{
var before = @"
class Program
{
void Method(nuint x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(nuint x)
{
nuint y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")]
public async Task WithRefIntrinsicType()
{
var before = @"
class Program
{
void Method()
{
ref [|var|] y = Ref();
}
ref int Ref() => throw null;
}";
var after = @"
class Program
{
void Method()
{
ref int y = Ref();
}
ref int Ref() => throw null;
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")]
public async Task WithRefIntrinsicTypeInForeach()
{
var before = @"
class E
{
public ref int Current => throw null;
public bool MoveNext() => throw null;
public E GetEnumerator() => throw null;
void M()
{
foreach (ref [|var|] x in this) { }
}
}";
var after = @"
class E
{
public ref int Current => throw null;
public bool MoveNext() => throw null;
public E GetEnumerator() => throw null;
void M()
{
foreach (ref int x in this) { }
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InArrayOfNullableIntrinsicType()
{
var before = @"
class Program
{
void Method(int?[] x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(int?[] x)
{
int?[] y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InNullableCustomType()
{
var before = @"
struct Program
{
void Method(Program? x)
{
[|var|] y = x;
}
}";
var after = @"
struct Program
{
void Method(Program? x)
{
Program? y = x;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType()
{
var before = @"
#nullable enable
class Program
{
void Method(Program x)
{
[|var|] y = x;
y = null;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(Program x)
{
Program? y = x;
y = null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType()
{
var before = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
[|var|] y = x;
y = null;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
Program y = x;
y = null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType()
{
var before = @"
class Program
{
void Method(Program x)
{
#nullable enable
[|var|] y = x;
y = null;
}
}";
var after = @"
class Program
{
void Method(Program x)
{
#nullable enable
Program? y = x;
y = null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType_OutVar()
{
var before = @"
#nullable enable
class Program
{
void Method(out Program? x)
{
Method(out [|var|] y1);
throw null!;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(out Program? x)
{
Method(out Program? y1);
throw null!;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_OutVar()
{
var before = @"
#nullable enable
class Program
{
void Method(out Program x)
{
Method(out [|var|] y1);
throw null!;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(out Program x)
{
Method(out Program? y1);
throw null!;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_OutVar()
{
var before = @"
class Program
{
void Method(out Program x)
{
Method(out [|var|] y1);
throw null;
}
}";
var after = @"
class Program
{
void Method(out Program x)
{
Method(out Program y1);
throw null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40925"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
[WorkItem(40925, "https://github.com/dotnet/roslyn/issues/40925")]
public async Task NullableTypeAndNotNullableType_VarDeconstruction()
{
var before = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program? x, Program2 x2)
{
[|var|] (y1, y2) = (x, x2);
}
}";
var after = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program? x, Program2 x2)
{
(Program? y1, Program2? y2) = (x, x2);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_VarDeconstruction()
{
var before = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program x, Program2 x2)
{
#nullable disable
[|var|] (y1, y2) = (x, x2);
}
}";
var after = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program x, Program2 x2)
{
#nullable disable
(Program y1, Program2 y2) = (x, x2);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_Deconstruction()
{
var before = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
([|var|] y1, Program y2) = (x, x);
}
}";
var after = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
(Program y1, Program y2) = (x, x);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_Deconstruction()
{
var before = @"
class Program
{
void Method(Program x)
{
#nullable enable
([|var|] y1, Program y2) = (x, x);
}
}";
var after = @"
class Program
{
void Method(Program x)
{
#nullable enable
(Program? y1, Program y2) = (x, x);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType_Deconstruction()
{
var before = @"
class Program
{
void Method(Program? x)
{
#nullable enable
([|var|] y1, Program y2) = (x, x);
}
}";
var after = @"
class Program
{
void Method(Program? x)
{
#nullable enable
(Program? y1, Program y2) = (x, x);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_Foreach()
{
var before = @"
#nullable enable
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable disable
foreach ([|var|] y in x)
{
}
}
}";
var after = @"
#nullable enable
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable disable
foreach ([|Program|] y in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_Foreach()
{
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach ([|var|] y in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach (Program? y in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType_Foreach()
{
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach ([|var|] y in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach (Program? y in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37491"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_ForeachVarDeconstruction()
{
// Semantic model doesn't yet handle var deconstruction foreach
// https://github.com/dotnet/roslyn/issues/37491
// https://github.com/dotnet/roslyn/issues/35010
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach ([|var|] (y1, y2) in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach ((Program? y1, Program? y2) in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_ForeachDeconstruction()
{
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach (([|var|] y1, var y2) in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach ((Program? y1, var y2) in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InPointerTypeWithIntrinsicType()
{
var before = @"
unsafe class Program
{
void Method(int* y)
{
[|var|] x = y;
}
}";
var after = @"
unsafe class Program
{
void Method(int* y)
{
int* x = y;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InPointerTypeWithCustomType()
{
var before = @"
unsafe class Program
{
void Method(Program* y)
{
[|var|] x = y;
}
}";
var after = @"
unsafe class Program
{
void Method(Program* y)
{
Program* x = y;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23893, "https://github.com/dotnet/roslyn/issues/23893")]
public async Task InOutParameter()
{
var before = @"
class Program
{
void Method(out int x)
{
Method(out [|var|] x);
}
}";
var after = @"
class Program
{
void Method(out int x)
{
Method(out int x);
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDynamic()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|dynamic|] x = 1;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnForEachVarWithAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5).Select(i => new { Value = i });
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnDeconstructionVarParens()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", @"using System;
class Program
{
void M()
{
(int x, string y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
([|var|] x, var y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", @"using System;
class Program
{
void M()
{
(int x, var y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnNestedDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, (y, z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
(int x, (int y, Program z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnBadlyFormattedNestedDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|](x,(y,z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
(int x, (int y, Program z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnForeachNestedDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
foreach ([|var|] (x, (y, z)) in new[] { new Program() } { }
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
foreach ((int x, (int y, Program z)) in new[] { new Program() } { }
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnNestedDeconstructionVarWithTrivia()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
/*before*/[|var|]/*after*/ (/*x1*/x/*x2*/, /*yz1*/(/*y1*/y/*y2*/, /*z1*/z/*z2*/)/*yz2*/) /*end*/ = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
/*before*//*after*/(/*x1*/int x/*x2*/, /*yz1*/(/*y1*/int y/*y2*/, /*z1*/Program z/*z2*/)/*yz2*/) /*end*/ = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnDeconstructionVarWithDiscard()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, _) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", @"using System;
class Program
{
void M()
{
(int x, string _) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnDeconstructionVarWithErrorType()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, y) = new Program();
}
void Deconstruct(out int i, out Error s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
(int x, Error y) = new Program();
}
void Deconstruct(out int i, out Error s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnForEachVarWithExplicitType()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}",
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach (int value in values)
{
Console.WriteLine(value.Value);
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new { Amount = 108, Message = ""Hello"" };
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnArrayOfAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new[] { new { name = ""apple"", diam = 4 }, new { name = ""grape"", diam = 1 } };
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
void Method()
{
var products = new List<Product>();
[|var|] productQuery = from prod in products
select new { prod.Color, prod.Price };
}
}
class Product
{
public ConsoleColor Color { get; set; }
public int Price { get; set; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = ""hello"";
}
}",
@"using System;
class C
{
static void M()
{
string s = ""hello"";
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnIntrinsicType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}",
@"using System;
class C
{
static void M()
{
int s = 5;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnFrameworkType()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
static void M()
{
[|var|] c = new List<int>();
}
}",
@"using System.Collections.Generic;
class C
{
static void M()
{
List<int> c = new List<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnUserDefinedType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
[|var|] c = new C();
}
}",
@"using System;
class C
{
void M()
{
C c = new C();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnGenericType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C<T>
{
static void M()
{
[|var|] c = new C<int>();
}
}",
@"using System;
class C<T>
{
static void M()
{
C<int> c = new C<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new int[4] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new int[4] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new[] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}",
@"using System;
class C
{
static void M()
{
int[][] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithObjectInitializer()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] cc = new Customer { City = ""Chennai"" };
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
class C
{
static void M()
{
Customer cc = new Customer { City = ""Chennai"" };
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] digits = new List<int> { 1, 2, 3 };
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<int> digits = new List<int> { 1, 2, 3 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] cs = new List<Customer>
{
new Customer { City = ""Chennai"" }
};
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<Customer> cs = new List<Customer>
{
new Customer { City = ""Chennai"" }
};
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
for ([|var|] i = 0; i < 5; i++)
{
}
}
}",
@"using System;
class C
{
static void M()
{
for (int i = 0; i < 5; i++)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForeachStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach ([|var|] item in l)
{
}
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach (int item in l)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnQueryExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
[|var|] expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
IEnumerable<Customer> expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInUsingStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
using ([|var|] r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}",
@"using System;
class C
{
static void M()
{
using (Res r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnInterpolatedString()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] s = $""Hello, {name}""
}
}",
@"using System;
class Program
{
void Method()
{
string s = $""Hello, {name}""
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnExplicitConversion()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
double x = 1234.7;
[|var|] a = (int)x;
}
}",
@"using System;
class C
{
static void M()
{
double x = 1234.7;
int a = (int)x;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnConditionalAccessExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
C obj = new C();
[|var|] anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}",
@"using System;
class C
{
static void M()
{
C obj = new C();
C anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInCheckedExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
[|var|] intNumber = checked((int)number1);
}
}",
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
int intNumber = checked((int)number1);
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInAwaitExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
[|var|] text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
string text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInNumericType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = 1;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
int text = 1;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInCharType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = GetChar();
}
public char GetChar() => 'c';
}",
@"using System;
class C
{
public void ProcessRead()
{
char text = GetChar();
}
public char GetChar() => 'c';
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_string()
{
// though string isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = string.Empty;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
string text = string.Empty;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_object()
{
// object isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
[|var|] text = j;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
object text = j;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeNotificationLevelSilent()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeSilentEnforcement(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Hidden);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeNotificationLevelInfo()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Info);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task SuggestExplicitTypeNotificationLevelWarning()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] { new C() }; // type not apparent and not intrinsic
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Warning);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeNotificationLevelError()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Error);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int, string) s = (1, ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, b: ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string b) s = (a: 1, b: ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string) s = (a: 1, ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20437, "https://github.com/dotnet/roslyn/issues/20437")]
public async Task SuggestExplicitTypeOnDeclarationExpressionSyntax()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
DateTime.TryParse(string.Empty, [|out var|] date);
}
}",
@"using System;
class C
{
static void M()
{
DateTime.TryParse(string.Empty, out DateTime date);
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames1()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|String|] test = new String(' ', 4);
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames2()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
foreach ([|String|] test in new String[] { ""test1"", ""test2"" })
{
}
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames3()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
[|Int32[]|] array = new[] { 1, 2, 3 };
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames4()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
[|Int32[][]|] a = new Int32[][]
{
new[] { 1, 2 },
new[] { 3, 4 }
};
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames5()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class Program
{
void Main()
{
[|IEnumerable<Int32>|] a = new List<Int32> { 1, 2 }.Where(x => x > 1);
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames6()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
String name = ""name"";
[|String|] s = $""Hello, {name}""
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames7()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
Object name = ""name"";
[|String|] s = (String) name;
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames8()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
[|String|] text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return String.Empty;
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames9()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
String number = ""12"";
Int32.TryParse(name, out [|Int32|] number)
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames10()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
for ([|Int32|] i = 0; i < 5; i++)
{
}
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames11()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class Program
{
void Main()
{
[|List<Int32>|] a = new List<Int32> { 1, 2 };
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")]
public async Task NoSuggestionOnForeachCollectionExpression()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class Program
{
void Method(List<int> var)
{
foreach (int value in [|var|])
{
Console.WriteLine(value.Value);
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnConstVar()
{
// This error case is handled by a separate code fix (UseExplicitTypeForConst).
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
const [|var|] v = 0;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle;
using Microsoft.CodeAnalysis.CSharp.TypeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType
{
public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public UseExplicitTypeTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseExplicitTypeDiagnosticAnalyzer(), new UseExplicitTypeCodeFixProvider());
private readonly CodeStyleOption2<bool> offWithSilent = new CodeStyleOption2<bool>(false, NotificationOption2.Silent);
private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion);
private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion);
private readonly CodeStyleOption2<bool> offWithWarning = new CodeStyleOption2<bool>(false, NotificationOption2.Warning);
private readonly CodeStyleOption2<bool> offWithError = new CodeStyleOption2<bool>(false, NotificationOption2.Error);
// specify all options explicitly to override defaults.
private OptionsCollection ExplicitTypeEverywhere() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithInfo },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithInfo },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeExceptWhereApparent() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithInfo },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeForBuiltInTypesOnly() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, onWithInfo },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeEnforcements() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithWarning },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithError },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeSilentEnforcement() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithSilent },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithSilent },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithSilent },
};
#region Error Cases
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldDeclaration()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
[|var|] _myfield = 5;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldLikeEvents()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
public event [|var|] _myevent;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnAnonymousMethodExpression()
{
var before =
@"using System;
class Program
{
void Method()
{
[|var|] comparer = delegate (string value) {
return value != ""0"";
};
}
}";
var after =
@"using System;
class Program
{
void Method()
{
Func<string, bool> comparer = delegate (string value) {
return value != ""0"";
};
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnLambdaExpression()
{
var before =
@"using System;
class Program
{
void Method()
{
[|var|] x = (int y) => y * y;
}
}";
var after =
@"using System;
class Program
{
void Method()
{
Func<int, int> x = (int y) => y * y;
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithMultipleDeclarators()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = 5, y = x;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithoutInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotDuringConflicts()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] p = new var();
}
class var
{
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotIfAlreadyExplicitlyTyped()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|Program|] p = new Program();
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")]
public async Task NotIfRefTypeAlreadyExplicitlyTyped()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
struct Program
{
void Method()
{
ref [|Program|] p = Ref();
}
ref Program Ref() => throw null;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnRHS()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
var c = new [|var|]();
}
}
class var
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorSymbol()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new Goo();
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorConvertedType_ForEachVariableStatement()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
void M()
{
// Error CS1061: 'KeyValuePair<int, int>' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'KeyValuePair<int, int>' could be found (are you missing a using directive or an assembly reference?)
// Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'KeyValuePair<int, int>', with 2 out parameters and a void return type.
foreach ([|var|] (key, value) in new Dictionary<int, int>())
{
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorConvertedType_AssignmentExpressionStatement()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
void M(C c)
{
// Error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type.
[|var|] (key, value) = c;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
#endregion
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InArrayType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = new Program[0];
}
}";
var after = @"
class Program
{
void Method()
{
Program[] x = new Program[0];
}
}";
// The type is apparent and not intrinsic
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InArrayTypeWithIntrinsicType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = new int[0];
}
}";
var after = @"
class Program
{
void Method()
{
int[] x = new int[0];
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InNullableIntrinsicType()
{
var before = @"
class Program
{
void Method(int? x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(int? x)
{
int? y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")]
public async Task InNativeIntIntrinsicType()
{
var before = @"
class Program
{
void Method(nint x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(nint x)
{
nint y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")]
public async Task InNativeUnsignedIntIntrinsicType()
{
var before = @"
class Program
{
void Method(nuint x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(nuint x)
{
nuint y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")]
public async Task WithRefIntrinsicType()
{
var before = @"
class Program
{
void Method()
{
ref [|var|] y = Ref();
}
ref int Ref() => throw null;
}";
var after = @"
class Program
{
void Method()
{
ref int y = Ref();
}
ref int Ref() => throw null;
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")]
public async Task WithRefIntrinsicTypeInForeach()
{
var before = @"
class E
{
public ref int Current => throw null;
public bool MoveNext() => throw null;
public E GetEnumerator() => throw null;
void M()
{
foreach (ref [|var|] x in this) { }
}
}";
var after = @"
class E
{
public ref int Current => throw null;
public bool MoveNext() => throw null;
public E GetEnumerator() => throw null;
void M()
{
foreach (ref int x in this) { }
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InArrayOfNullableIntrinsicType()
{
var before = @"
class Program
{
void Method(int?[] x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(int?[] x)
{
int?[] y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InNullableCustomType()
{
var before = @"
struct Program
{
void Method(Program? x)
{
[|var|] y = x;
}
}";
var after = @"
struct Program
{
void Method(Program? x)
{
Program? y = x;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType()
{
var before = @"
#nullable enable
class Program
{
void Method(Program x)
{
[|var|] y = x;
y = null;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(Program x)
{
Program? y = x;
y = null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType()
{
var before = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
[|var|] y = x;
y = null;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
Program y = x;
y = null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType()
{
var before = @"
class Program
{
void Method(Program x)
{
#nullable enable
[|var|] y = x;
y = null;
}
}";
var after = @"
class Program
{
void Method(Program x)
{
#nullable enable
Program? y = x;
y = null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType_OutVar()
{
var before = @"
#nullable enable
class Program
{
void Method(out Program? x)
{
Method(out [|var|] y1);
throw null!;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(out Program? x)
{
Method(out Program? y1);
throw null!;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_OutVar()
{
var before = @"
#nullable enable
class Program
{
void Method(out Program x)
{
Method(out [|var|] y1);
throw null!;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(out Program x)
{
Method(out Program? y1);
throw null!;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_OutVar()
{
var before = @"
class Program
{
void Method(out Program x)
{
Method(out [|var|] y1);
throw null;
}
}";
var after = @"
class Program
{
void Method(out Program x)
{
Method(out Program y1);
throw null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40925"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
[WorkItem(40925, "https://github.com/dotnet/roslyn/issues/40925")]
public async Task NullableTypeAndNotNullableType_VarDeconstruction()
{
var before = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program? x, Program2 x2)
{
[|var|] (y1, y2) = (x, x2);
}
}";
var after = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program? x, Program2 x2)
{
(Program? y1, Program2? y2) = (x, x2);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_VarDeconstruction()
{
var before = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program x, Program2 x2)
{
#nullable disable
[|var|] (y1, y2) = (x, x2);
}
}";
var after = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program x, Program2 x2)
{
#nullable disable
(Program y1, Program2 y2) = (x, x2);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_Deconstruction()
{
var before = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
([|var|] y1, Program y2) = (x, x);
}
}";
var after = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
(Program y1, Program y2) = (x, x);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_Deconstruction()
{
var before = @"
class Program
{
void Method(Program x)
{
#nullable enable
([|var|] y1, Program y2) = (x, x);
}
}";
var after = @"
class Program
{
void Method(Program x)
{
#nullable enable
(Program? y1, Program y2) = (x, x);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType_Deconstruction()
{
var before = @"
class Program
{
void Method(Program? x)
{
#nullable enable
([|var|] y1, Program y2) = (x, x);
}
}";
var after = @"
class Program
{
void Method(Program? x)
{
#nullable enable
(Program? y1, Program y2) = (x, x);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_Foreach()
{
var before = @"
#nullable enable
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable disable
foreach ([|var|] y in x)
{
}
}
}";
var after = @"
#nullable enable
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable disable
foreach ([|Program|] y in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_Foreach()
{
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach ([|var|] y in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach (Program? y in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType_Foreach()
{
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach ([|var|] y in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach (Program? y in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37491"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_ForeachVarDeconstruction()
{
// Semantic model doesn't yet handle var deconstruction foreach
// https://github.com/dotnet/roslyn/issues/37491
// https://github.com/dotnet/roslyn/issues/35010
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach ([|var|] (y1, y2) in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach ((Program? y1, Program? y2) in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_ForeachDeconstruction()
{
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach (([|var|] y1, var y2) in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach ((Program? y1, var y2) in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InPointerTypeWithIntrinsicType()
{
var before = @"
unsafe class Program
{
void Method(int* y)
{
[|var|] x = y;
}
}";
var after = @"
unsafe class Program
{
void Method(int* y)
{
int* x = y;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InPointerTypeWithCustomType()
{
var before = @"
unsafe class Program
{
void Method(Program* y)
{
[|var|] x = y;
}
}";
var after = @"
unsafe class Program
{
void Method(Program* y)
{
Program* x = y;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23893, "https://github.com/dotnet/roslyn/issues/23893")]
public async Task InOutParameter()
{
var before = @"
class Program
{
void Method(out int x)
{
Method(out [|var|] x);
}
}";
var after = @"
class Program
{
void Method(out int x)
{
Method(out int x);
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDynamic()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|dynamic|] x = 1;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnForEachVarWithAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5).Select(i => new { Value = i });
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnDeconstructionVarParens()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", @"using System;
class Program
{
void M()
{
(int x, string y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
([|var|] x, var y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", @"using System;
class Program
{
void M()
{
(int x, var y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnNestedDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, (y, z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
(int x, (int y, Program z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnBadlyFormattedNestedDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|](x,(y,z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
(int x, (int y, Program z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnForeachNestedDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
foreach ([|var|] (x, (y, z)) in new[] { new Program() } { }
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
foreach ((int x, (int y, Program z)) in new[] { new Program() } { }
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnNestedDeconstructionVarWithTrivia()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
/*before*/[|var|]/*after*/ (/*x1*/x/*x2*/, /*yz1*/(/*y1*/y/*y2*/, /*z1*/z/*z2*/)/*yz2*/) /*end*/ = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
/*before*//*after*/(/*x1*/int x/*x2*/, /*yz1*/(/*y1*/int y/*y2*/, /*z1*/Program z/*z2*/)/*yz2*/) /*end*/ = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnDeconstructionVarWithDiscard()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, _) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", @"using System;
class Program
{
void M()
{
(int x, string _) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnDeconstructionVarWithErrorType()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, y) = new Program();
}
void Deconstruct(out int i, out Error s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
(int x, Error y) = new Program();
}
void Deconstruct(out int i, out Error s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnForEachVarWithExplicitType()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}",
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach (int value in values)
{
Console.WriteLine(value.Value);
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new { Amount = 108, Message = ""Hello"" };
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnArrayOfAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new[] { new { name = ""apple"", diam = 4 }, new { name = ""grape"", diam = 1 } };
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
void Method()
{
var products = new List<Product>();
[|var|] productQuery = from prod in products
select new { prod.Color, prod.Price };
}
}
class Product
{
public ConsoleColor Color { get; set; }
public int Price { get; set; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = ""hello"";
}
}",
@"using System;
class C
{
static void M()
{
string s = ""hello"";
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnIntrinsicType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}",
@"using System;
class C
{
static void M()
{
int s = 5;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnFrameworkType()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
static void M()
{
[|var|] c = new List<int>();
}
}",
@"using System.Collections.Generic;
class C
{
static void M()
{
List<int> c = new List<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnUserDefinedType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
[|var|] c = new C();
}
}",
@"using System;
class C
{
void M()
{
C c = new C();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnGenericType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C<T>
{
static void M()
{
[|var|] c = new C<int>();
}
}",
@"using System;
class C<T>
{
static void M()
{
C<int> c = new C<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new int[4] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new int[4] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new[] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}",
@"using System;
class C
{
static void M()
{
int[][] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithObjectInitializer()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] cc = new Customer { City = ""Chennai"" };
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
class C
{
static void M()
{
Customer cc = new Customer { City = ""Chennai"" };
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] digits = new List<int> { 1, 2, 3 };
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<int> digits = new List<int> { 1, 2, 3 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] cs = new List<Customer>
{
new Customer { City = ""Chennai"" }
};
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<Customer> cs = new List<Customer>
{
new Customer { City = ""Chennai"" }
};
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
for ([|var|] i = 0; i < 5; i++)
{
}
}
}",
@"using System;
class C
{
static void M()
{
for (int i = 0; i < 5; i++)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForeachStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach ([|var|] item in l)
{
}
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach (int item in l)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnQueryExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
[|var|] expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
IEnumerable<Customer> expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInUsingStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
using ([|var|] r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}",
@"using System;
class C
{
static void M()
{
using (Res r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnInterpolatedString()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] s = $""Hello, {name}""
}
}",
@"using System;
class Program
{
void Method()
{
string s = $""Hello, {name}""
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnExplicitConversion()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
double x = 1234.7;
[|var|] a = (int)x;
}
}",
@"using System;
class C
{
static void M()
{
double x = 1234.7;
int a = (int)x;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnConditionalAccessExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
C obj = new C();
[|var|] anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}",
@"using System;
class C
{
static void M()
{
C obj = new C();
C anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInCheckedExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
[|var|] intNumber = checked((int)number1);
}
}",
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
int intNumber = checked((int)number1);
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInAwaitExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
[|var|] text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
string text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInNumericType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = 1;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
int text = 1;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInCharType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = GetChar();
}
public char GetChar() => 'c';
}",
@"using System;
class C
{
public void ProcessRead()
{
char text = GetChar();
}
public char GetChar() => 'c';
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_string()
{
// though string isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = string.Empty;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
string text = string.Empty;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_object()
{
// object isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
[|var|] text = j;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
object text = j;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeNotificationLevelSilent()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeSilentEnforcement(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Hidden);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeNotificationLevelInfo()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Info);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task SuggestExplicitTypeNotificationLevelWarning()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] { new C() }; // type not apparent and not intrinsic
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Warning);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeNotificationLevelError()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Error);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int, string) s = (1, ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, b: ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string b) s = (a: 1, b: ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string) s = (a: 1, ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20437, "https://github.com/dotnet/roslyn/issues/20437")]
public async Task SuggestExplicitTypeOnDeclarationExpressionSyntax()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
DateTime.TryParse(string.Empty, [|out var|] date);
}
}",
@"using System;
class C
{
static void M()
{
DateTime.TryParse(string.Empty, out DateTime date);
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames1()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|String|] test = new String(' ', 4);
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames2()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
foreach ([|String|] test in new String[] { ""test1"", ""test2"" })
{
}
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames3()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
[|Int32[]|] array = new[] { 1, 2, 3 };
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames4()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
[|Int32[][]|] a = new Int32[][]
{
new[] { 1, 2 },
new[] { 3, 4 }
};
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames5()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class Program
{
void Main()
{
[|IEnumerable<Int32>|] a = new List<Int32> { 1, 2 }.Where(x => x > 1);
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames6()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
String name = ""name"";
[|String|] s = $""Hello, {name}""
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames7()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
Object name = ""name"";
[|String|] s = (String) name;
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames8()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
[|String|] text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return String.Empty;
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames9()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
String number = ""12"";
Int32.TryParse(name, out [|Int32|] number)
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames10()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
for ([|Int32|] i = 0; i < 5; i++)
{
}
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames11()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class Program
{
void Main()
{
[|List<Int32>|] a = new List<Int32> { 1, 2 };
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")]
public async Task NoSuggestionOnForeachCollectionExpression()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class Program
{
void Method(List<int> var)
{
foreach (int value in [|var|])
{
Console.WriteLine(value.Value);
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnConstVar()
{
// This error case is handled by a separate code fix (UseExplicitTypeForConst).
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
const [|var|] v = 0;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task WithNormalFuncSynthesizedLambdaType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = (int i) => i.ToString();
}
}";
var after = @"
class Program
{
void Method()
{
System.Func<int, string> x = (int i) => i.ToString();
}
}";
// The type is not apparent and not intrinsic
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task WithAnonymousSynthesizedLambdaType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = (ref int i) => i.ToString();
}
}";
// The type is apparent and not intrinsic
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeEverywhere()));
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent()));
}
}
}
| 1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor.Types.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.SymbolDisplay;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class SymbolDisplayVisitor
{
public override void VisitArrayType(IArrayTypeSymbol symbol)
{
VisitArrayTypeWithoutNullability(symbol);
AddNullableAnnotations(symbol);
}
private void VisitArrayTypeWithoutNullability(IArrayTypeSymbol symbol)
{
if (TryAddAlias(symbol, builder))
{
return;
}
//See spec section 12.1 for the order of rank specifiers
//e.g. int[][,][,,] is stored as
// ArrayType
// Rank = 1
// ElementType = ArrayType
// Rank = 2
// ElementType = ArrayType
// Rank = 3
// ElementType = int
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.ReverseArrayRankSpecifiers))
{
// Ironically, reverse order is simpler - we just have to recurse on the element type and then add a rank specifier.
symbol.ElementType.Accept(this);
AddArrayRank(symbol);
return;
}
ITypeSymbol underlyingType = symbol;
do
{
underlyingType = ((IArrayTypeSymbol)underlyingType).ElementType;
}
while (underlyingType.Kind == SymbolKind.ArrayType && !ShouldAddNullableAnnotation(underlyingType));
underlyingType.Accept(this.NotFirstVisitor);
var arrayType = symbol;
while (arrayType != null && arrayType != underlyingType)
{
if (!this.isFirstSymbolVisited)
{
AddCustomModifiersIfRequired(arrayType.CustomModifiers, leadingSpace: true);
}
AddArrayRank(arrayType);
arrayType = arrayType.ElementType as IArrayTypeSymbol;
}
}
private void AddNullableAnnotations(ITypeSymbol type)
{
if (ShouldAddNullableAnnotation(type))
{
AddPunctuation(type.NullableAnnotation == CodeAnalysis.NullableAnnotation.Annotated ? SyntaxKind.QuestionToken : SyntaxKind.ExclamationToken);
}
}
private bool ShouldAddNullableAnnotation(ITypeSymbol type)
{
switch (type.NullableAnnotation)
{
case CodeAnalysis.NullableAnnotation.Annotated:
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier) &&
!ITypeSymbolHelpers.IsNullableType(type) && !type.IsValueType)
{
return true;
}
break;
case CodeAnalysis.NullableAnnotation.NotAnnotated:
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier) &&
!type.IsValueType &&
(type as Symbols.PublicModel.TypeSymbol)?.UnderlyingTypeSymbol.IsTypeParameterDisallowingAnnotationInCSharp8() != true)
{
return true;
}
break;
}
return false;
}
private void AddArrayRank(IArrayTypeSymbol symbol)
{
bool insertStars = format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays);
AddPunctuation(SyntaxKind.OpenBracketToken);
if (symbol.Rank > 1)
{
if (insertStars)
{
AddPunctuation(SyntaxKind.AsteriskToken);
}
}
else
{
if (!symbol.IsSZArray)
{
// Always add an asterisk in this case in order to distinguish between SZArray and MDArray.
AddPunctuation(SyntaxKind.AsteriskToken);
}
}
for (int i = 0; i < symbol.Rank - 1; i++)
{
AddPunctuation(SyntaxKind.CommaToken);
if (insertStars)
{
AddPunctuation(SyntaxKind.AsteriskToken);
}
}
AddPunctuation(SyntaxKind.CloseBracketToken);
}
public override void VisitPointerType(IPointerTypeSymbol symbol)
{
symbol.PointedAtType.Accept(this.NotFirstVisitor);
AddNullableAnnotations(symbol);
if (!this.isFirstSymbolVisited)
{
AddCustomModifiersIfRequired(symbol.CustomModifiers, leadingSpace: true);
}
AddPunctuation(SyntaxKind.AsteriskToken);
}
public override void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol)
{
VisitMethod(symbol.Signature);
}
public override void VisitTypeParameter(ITypeParameterSymbol symbol)
{
if (this.isFirstSymbolVisited)
{
AddTypeParameterVarianceIfRequired(symbol);
}
//variance and constraints are handled by methods and named types
builder.Add(CreatePart(SymbolDisplayPartKind.TypeParameterName, symbol, symbol.Name));
AddNullableAnnotations(symbol);
}
public override void VisitDynamicType(IDynamicTypeSymbol symbol)
{
builder.Add(CreatePart(SymbolDisplayPartKind.Keyword, symbol, symbol.Name));
AddNullableAnnotations(symbol);
}
public override void VisitNamedType(INamedTypeSymbol symbol)
{
VisitNamedTypeWithoutNullability(symbol);
AddNullableAnnotations(symbol);
}
private void VisitNamedTypeWithoutNullability(INamedTypeSymbol symbol)
{
if (this.IsMinimizing && TryAddAlias(symbol, builder))
{
return;
}
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.UseSpecialTypes) ||
(symbol.IsNativeIntegerType && !format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseNativeIntegerUnderlyingType)))
{
if (AddSpecialTypeKeyword(symbol))
{
//if we're using special type keywords and this is a special type, then no other work is required
return;
}
}
if (!format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.ExpandNullable))
{
//if we're expanding nullable, we just visit nullable types normally
if (ITypeSymbolHelpers.IsNullableType(symbol) && !symbol.IsDefinition)
{
// Can't have a type called "int*?".
var typeArg = symbol.TypeArguments[0];
if (typeArg.TypeKind != TypeKind.Pointer)
{
typeArg.Accept(this.NotFirstVisitor);
AddCustomModifiersIfRequired(symbol.GetTypeArgumentCustomModifiers(0), leadingSpace: true, trailingSpace: false);
AddPunctuation(SyntaxKind.QuestionToken);
//visiting the underlying type did all of the work for us
return;
}
}
}
if (this.IsMinimizing || (symbol.IsTupleType && !ShouldDisplayAsValueTuple(symbol)))
{
MinimallyQualify(symbol);
return;
}
AddTypeKind(symbol);
if (CanShowDelegateSignature(symbol))
{
if (format.DelegateStyle == SymbolDisplayDelegateStyle.NameAndSignature)
{
var invokeMethod = symbol.DelegateInvokeMethod;
if (invokeMethod.ReturnsByRef)
{
AddRefIfRequired();
}
else if (invokeMethod.ReturnsByRefReadonly)
{
AddRefReadonlyIfRequired();
}
if (invokeMethod.ReturnsVoid)
{
AddKeyword(SyntaxKind.VoidKeyword);
}
else
{
AddReturnType(symbol.DelegateInvokeMethod);
}
AddSpace();
}
}
//only visit the namespace if the style requires it and there isn't an enclosing type
var containingSymbol = symbol.ContainingSymbol;
if (ShouldVisitNamespace(containingSymbol))
{
var namespaceSymbol = (INamespaceSymbol)containingSymbol;
var shouldSkip = namespaceSymbol.IsGlobalNamespace && symbol.TypeKind == TypeKind.Error;
if (!shouldSkip)
{
namespaceSymbol.Accept(this.NotFirstVisitor);
AddPunctuation(namespaceSymbol.IsGlobalNamespace ? SyntaxKind.ColonColonToken : SyntaxKind.DotToken);
}
}
//visit the enclosing type if the style requires it
if (format.TypeQualificationStyle == SymbolDisplayTypeQualificationStyle.NameAndContainingTypes ||
format.TypeQualificationStyle == SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)
{
if (IncludeNamedType(symbol.ContainingType))
{
symbol.ContainingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
}
AddNameAndTypeArgumentsOrParameters(symbol);
}
private bool ShouldDisplayAsValueTuple(INamedTypeSymbol symbol)
{
Debug.Assert(symbol.IsTupleType);
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseValueTuple))
{
return true;
}
return !CanUseTupleSyntax(symbol);
}
private void AddNameAndTypeArgumentsOrParameters(INamedTypeSymbol symbol)
{
if (symbol.IsAnonymousType)
{
AddAnonymousTypeName(symbol);
return;
}
else if (symbol.IsTupleType && !ShouldDisplayAsValueTuple(symbol))
{
AddTupleTypeName(symbol);
return;
}
string symbolName = null;
// It would be nice to handle VB NoPia symbols too, but it's not worth the effort.
NamedTypeSymbol underlyingTypeSymbol = (symbol as Symbols.PublicModel.NamedTypeSymbol)?.UnderlyingNamedTypeSymbol;
var illegalGenericInstantiationSymbol = underlyingTypeSymbol as NoPiaIllegalGenericInstantiationSymbol;
if ((object)illegalGenericInstantiationSymbol != null)
{
symbol = illegalGenericInstantiationSymbol.UnderlyingSymbol.GetPublicSymbol();
}
else
{
var ambiguousCanonicalTypeSymbol = underlyingTypeSymbol as NoPiaAmbiguousCanonicalTypeSymbol;
if ((object)ambiguousCanonicalTypeSymbol != null)
{
symbol = ambiguousCanonicalTypeSymbol.FirstCandidate.GetPublicSymbol();
}
else
{
var missingCanonicalTypeSymbol = underlyingTypeSymbol as NoPiaMissingCanonicalTypeSymbol;
if ((object)missingCanonicalTypeSymbol != null)
{
symbolName = missingCanonicalTypeSymbol.FullTypeName;
}
}
}
var partKind = GetPartKind(symbol);
if (symbolName == null)
{
symbolName = symbol.Name;
}
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName) &&
partKind == SymbolDisplayPartKind.ErrorTypeName &&
string.IsNullOrEmpty(symbolName))
{
builder.Add(CreatePart(partKind, symbol, "?"));
}
else
{
symbolName = RemoveAttributeSufficeIfNecessary(symbol, symbolName);
builder.Add(CreatePart(partKind, symbol, symbolName));
}
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes))
{
// Only the compiler can set the internal option and the compiler doesn't use other implementations of INamedTypeSymbol.
if (underlyingTypeSymbol?.MangleName == true)
{
Debug.Assert(symbol.Arity > 0);
builder.Add(CreatePart(InternalSymbolDisplayPartKind.Arity, null,
MetadataHelpers.GetAritySuffix(symbol.Arity)));
}
}
else if (symbol.Arity > 0 && format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeParameters))
{
// It would be nice to handle VB symbols too, but it's not worth the effort.
if (underlyingTypeSymbol is UnsupportedMetadataTypeSymbol || underlyingTypeSymbol is MissingMetadataTypeSymbol || symbol.IsUnboundGenericType)
{
AddPunctuation(SyntaxKind.LessThanToken);
for (int i = 0; i < symbol.Arity - 1; i++)
{
AddPunctuation(SyntaxKind.CommaToken);
}
AddPunctuation(SyntaxKind.GreaterThanToken);
}
else
{
ImmutableArray<ImmutableArray<CustomModifier>> modifiers = GetTypeArgumentsModifiers(underlyingTypeSymbol);
AddTypeArguments(symbol, modifiers);
AddDelegateParameters(symbol);
// TODO: do we want to skip these if we're being visited as a containing type?
AddTypeParameterConstraints(symbol.TypeArguments);
}
}
else
{
AddDelegateParameters(symbol);
}
// Only the compiler can set the internal option and the compiler doesn't use other implementations of INamedTypeSymbol.
if (underlyingTypeSymbol?.OriginalDefinition is MissingMetadataTypeSymbol &&
format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.FlagMissingMetadataTypes))
{
//add it as punctuation - it's just for testing
AddPunctuation(SyntaxKind.OpenBracketToken);
builder.Add(CreatePart(InternalSymbolDisplayPartKind.Other, symbol, "missing"));
AddPunctuation(SyntaxKind.CloseBracketToken);
}
}
private ImmutableArray<ImmutableArray<CustomModifier>> GetTypeArgumentsModifiers(NamedTypeSymbol underlyingTypeSymbol)
{
if (this.format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers))
{
if ((object)underlyingTypeSymbol != null)
{
return underlyingTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.SelectAsArray(a => a.CustomModifiers);
}
}
return default;
}
private void AddDelegateParameters(INamedTypeSymbol symbol)
{
if (CanShowDelegateSignature(symbol))
{
if (format.DelegateStyle == SymbolDisplayDelegateStyle.NameAndParameters ||
format.DelegateStyle == SymbolDisplayDelegateStyle.NameAndSignature)
{
var method = symbol.DelegateInvokeMethod;
AddPunctuation(SyntaxKind.OpenParenToken);
AddParametersIfRequired(hasThisParameter: false, isVarargs: method.IsVararg, parameters: method.Parameters);
AddPunctuation(SyntaxKind.CloseParenToken);
}
}
}
private void AddAnonymousTypeName(INamedTypeSymbol symbol)
{
// TODO: revise to generate user-friendly name
var members = string.Join(", ", symbol.GetMembers().OfType<IPropertySymbol>().Select(CreateAnonymousTypeMember));
if (members.Length == 0)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.ClassName, symbol, "<empty anonymous type>"));
}
else
{
var name = $"<anonymous type: {members}>";
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.ClassName, symbol, name));
}
}
/// <summary>
/// Returns true if tuple type syntax can be used to refer to the tuple type without loss of information.
/// For example, it cannot be used when extension tuple is using non-default friendly names.
/// </summary>
/// <param name="tupleSymbol"></param>
/// <returns></returns>
private bool CanUseTupleSyntax(INamedTypeSymbol tupleSymbol)
{
if (containsModopt(tupleSymbol))
{
return false;
}
INamedTypeSymbol currentUnderlying = GetTupleUnderlyingTypeOrSelf(tupleSymbol);
if (currentUnderlying.Arity <= 1)
{
return false;
}
while (currentUnderlying.Arity == NamedTypeSymbol.ValueTupleRestPosition)
{
tupleSymbol = (INamedTypeSymbol)currentUnderlying.TypeArguments[NamedTypeSymbol.ValueTupleRestPosition - 1];
Debug.Assert(tupleSymbol.IsTupleType);
if (tupleSymbol.TypeKind == TypeKind.Error ||
HasNonDefaultTupleElements(tupleSymbol) ||
containsModopt(tupleSymbol))
{
return false;
}
currentUnderlying = GetTupleUnderlyingTypeOrSelf(tupleSymbol);
}
return true;
bool containsModopt(INamedTypeSymbol symbol)
{
NamedTypeSymbol underlyingTypeSymbol = (symbol as Symbols.PublicModel.NamedTypeSymbol)?.UnderlyingNamedTypeSymbol;
ImmutableArray<ImmutableArray<CustomModifier>> modifiers = GetTypeArgumentsModifiers(underlyingTypeSymbol);
if (modifiers.IsDefault)
{
return false;
}
return modifiers.Any(m => !m.IsEmpty);
}
}
private static INamedTypeSymbol GetTupleUnderlyingTypeOrSelf(INamedTypeSymbol type)
{
return type.TupleUnderlyingType ?? type;
}
private static bool HasNonDefaultTupleElements(INamedTypeSymbol tupleSymbol)
{
return tupleSymbol.TupleElements.Any(e => !e.IsDefaultTupleElement());
}
private void AddTupleTypeName(INamedTypeSymbol symbol)
{
Debug.Assert(symbol.IsTupleType);
ImmutableArray<IFieldSymbol> elements = symbol.TupleElements;
AddPunctuation(SyntaxKind.OpenParenToken);
for (int i = 0; i < elements.Length; i++)
{
var element = elements[i];
if (i != 0)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
VisitFieldType(element);
if (element.IsExplicitlyNamedTupleElement)
{
AddSpace();
builder.Add(CreatePart(SymbolDisplayPartKind.FieldName, symbol, element.Name));
}
}
AddPunctuation(SyntaxKind.CloseParenToken);
if (symbol.TypeKind == TypeKind.Error &&
format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.FlagMissingMetadataTypes))
{
//add it as punctuation - it's just for testing
AddPunctuation(SyntaxKind.OpenBracketToken);
builder.Add(CreatePart(InternalSymbolDisplayPartKind.Other, symbol, "missing"));
AddPunctuation(SyntaxKind.CloseBracketToken);
}
}
private string CreateAnonymousTypeMember(IPropertySymbol property)
{
return property.Type.ToDisplayString(format) + " " + property.Name;
}
private bool CanShowDelegateSignature(INamedTypeSymbol symbol)
{
return
isFirstSymbolVisited &&
symbol.TypeKind == TypeKind.Delegate &&
format.DelegateStyle != SymbolDisplayDelegateStyle.NameOnly &&
symbol.DelegateInvokeMethod != null;
}
private static SymbolDisplayPartKind GetPartKind(INamedTypeSymbol symbol)
{
switch (symbol.TypeKind)
{
case TypeKind.Class when symbol.IsRecord:
return SymbolDisplayPartKind.RecordClassName;
case TypeKind.Struct when symbol.IsRecord:
return SymbolDisplayPartKind.RecordStructName;
case TypeKind.Submission:
case TypeKind.Module:
case TypeKind.Class:
return SymbolDisplayPartKind.ClassName;
case TypeKind.Delegate:
return SymbolDisplayPartKind.DelegateName;
case TypeKind.Enum:
return SymbolDisplayPartKind.EnumName;
case TypeKind.Error:
return SymbolDisplayPartKind.ErrorTypeName;
case TypeKind.Interface:
return SymbolDisplayPartKind.InterfaceName;
case TypeKind.Struct:
return SymbolDisplayPartKind.StructName;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.TypeKind);
}
}
private bool AddSpecialTypeKeyword(INamedTypeSymbol symbol)
{
var specialTypeName = GetSpecialTypeName(symbol);
if (specialTypeName == null)
{
return false;
}
// cheat - skip escapeKeywordIdentifiers. not calling AddKeyword because someone
// else is working out the text for us
builder.Add(CreatePart(SymbolDisplayPartKind.Keyword, symbol, specialTypeName));
return true;
}
private static string GetSpecialTypeName(INamedTypeSymbol symbol)
{
switch (symbol.SpecialType)
{
case SpecialType.System_Void:
return "void";
case SpecialType.System_SByte:
return "sbyte";
case SpecialType.System_Int16:
return "short";
case SpecialType.System_Int32:
return "int";
case SpecialType.System_Int64:
return "long";
case SpecialType.System_IntPtr when symbol.IsNativeIntegerType:
return "nint";
case SpecialType.System_UIntPtr when symbol.IsNativeIntegerType:
return "nuint";
case SpecialType.System_Byte:
return "byte";
case SpecialType.System_UInt16:
return "ushort";
case SpecialType.System_UInt32:
return "uint";
case SpecialType.System_UInt64:
return "ulong";
case SpecialType.System_Single:
return "float";
case SpecialType.System_Double:
return "double";
case SpecialType.System_Decimal:
return "decimal";
case SpecialType.System_Char:
return "char";
case SpecialType.System_Boolean:
return "bool";
case SpecialType.System_String:
return "string";
case SpecialType.System_Object:
return "object";
default:
return null;
}
}
private void AddTypeKind(INamedTypeSymbol symbol)
{
if (isFirstSymbolVisited && format.KindOptions.IncludesOption(SymbolDisplayKindOptions.IncludeTypeKeyword))
{
if (symbol.IsAnonymousType)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.AnonymousTypeIndicator, null, "AnonymousType"));
AddSpace();
}
else if (symbol.IsTupleType && !ShouldDisplayAsValueTuple(symbol))
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.AnonymousTypeIndicator, null, "Tuple"));
AddSpace();
}
else
{
switch (symbol.TypeKind)
{
case TypeKind.Class when symbol.IsRecord:
AddKeyword(SyntaxKind.RecordKeyword);
AddSpace();
break;
case TypeKind.Struct when symbol.IsRecord:
// In case ref record structs are allowed in future, call AddKeyword(SyntaxKind.RefKeyword) and remove assertion.
Debug.Assert(!symbol.IsRefLikeType);
if (symbol.IsReadOnly)
{
AddKeyword(SyntaxKind.ReadOnlyKeyword);
AddSpace();
}
AddKeyword(SyntaxKind.RecordKeyword);
AddSpace();
AddKeyword(SyntaxKind.StructKeyword);
AddSpace();
break;
case TypeKind.Module:
case TypeKind.Class:
AddKeyword(SyntaxKind.ClassKeyword);
AddSpace();
break;
case TypeKind.Enum:
AddKeyword(SyntaxKind.EnumKeyword);
AddSpace();
break;
case TypeKind.Delegate:
AddKeyword(SyntaxKind.DelegateKeyword);
AddSpace();
break;
case TypeKind.Interface:
AddKeyword(SyntaxKind.InterfaceKeyword);
AddSpace();
break;
case TypeKind.Struct:
if (symbol.IsReadOnly)
{
AddKeyword(SyntaxKind.ReadOnlyKeyword);
AddSpace();
}
if (symbol.IsRefLikeType)
{
AddKeyword(SyntaxKind.RefKeyword);
AddSpace();
}
AddKeyword(SyntaxKind.StructKeyword);
AddSpace();
break;
}
}
}
}
private void AddTypeParameterVarianceIfRequired(ITypeParameterSymbol symbol)
{
if (format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeVariance))
{
switch (symbol.Variance)
{
case VarianceKind.In:
AddKeyword(SyntaxKind.InKeyword);
AddSpace();
break;
case VarianceKind.Out:
AddKeyword(SyntaxKind.OutKeyword);
AddSpace();
break;
}
}
}
//returns true if there are constraints
private void AddTypeArguments(ISymbol owner, ImmutableArray<ImmutableArray<CustomModifier>> modifiers)
{
ImmutableArray<ITypeSymbol> typeArguments;
if (owner.Kind == SymbolKind.Method)
{
typeArguments = ((IMethodSymbol)owner).TypeArguments;
}
else
{
typeArguments = ((INamedTypeSymbol)owner).TypeArguments;
}
if (typeArguments.Length > 0 && format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeParameters))
{
AddPunctuation(SyntaxKind.LessThanToken);
var first = true;
for (int i = 0; i < typeArguments.Length; i++)
{
var typeArg = typeArguments[i];
if (!first)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
first = false;
AbstractSymbolDisplayVisitor visitor;
if (typeArg.Kind == SymbolKind.TypeParameter)
{
var typeParam = (ITypeParameterSymbol)typeArg;
AddTypeParameterVarianceIfRequired(typeParam);
visitor = this.NotFirstVisitor;
}
else
{
visitor = this.NotFirstVisitorNamespaceOrType;
}
typeArg.Accept(visitor);
if (!modifiers.IsDefault)
{
AddCustomModifiersIfRequired(modifiers[i], leadingSpace: true, trailingSpace: false);
}
}
AddPunctuation(SyntaxKind.GreaterThanToken);
}
}
private static bool TypeParameterHasConstraints(ITypeParameterSymbol typeParam)
{
return !typeParam.ConstraintTypes.IsEmpty || typeParam.HasConstructorConstraint ||
typeParam.HasReferenceTypeConstraint || typeParam.HasValueTypeConstraint ||
typeParam.HasNotNullConstraint;
}
private void AddTypeParameterConstraints(ImmutableArray<ITypeSymbol> typeArguments)
{
if (this.isFirstSymbolVisited && format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeConstraints))
{
foreach (var typeArg in typeArguments)
{
if (typeArg.Kind == SymbolKind.TypeParameter)
{
var typeParam = (ITypeParameterSymbol)typeArg;
if (TypeParameterHasConstraints(typeParam))
{
AddSpace();
AddKeyword(SyntaxKind.WhereKeyword);
AddSpace();
typeParam.Accept(this.NotFirstVisitor);
AddSpace();
AddPunctuation(SyntaxKind.ColonToken);
AddSpace();
bool needComma = false;
//class/struct constraint must be first
if (typeParam.HasReferenceTypeConstraint)
{
AddKeyword(SyntaxKind.ClassKeyword);
switch (typeParam.ReferenceTypeConstraintNullableAnnotation)
{
case CodeAnalysis.NullableAnnotation.Annotated:
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier))
{
AddPunctuation(SyntaxKind.QuestionToken);
}
break;
case CodeAnalysis.NullableAnnotation.NotAnnotated:
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))
{
AddPunctuation(SyntaxKind.ExclamationToken);
}
break;
}
needComma = true;
}
else if (typeParam.HasUnmanagedTypeConstraint)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "unmanaged"));
needComma = true;
}
else if (typeParam.HasValueTypeConstraint)
{
AddKeyword(SyntaxKind.StructKeyword);
needComma = true;
}
else if (typeParam.HasNotNullConstraint)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "notnull"));
needComma = true;
}
for (int i = 0; i < typeParam.ConstraintTypes.Length; i++)
{
ITypeSymbol baseType = typeParam.ConstraintTypes[i];
if (needComma)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
baseType.Accept(this.NotFirstVisitor);
needComma = true;
}
//ctor constraint must be last
if (typeParam.HasConstructorConstraint)
{
if (needComma)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
AddKeyword(SyntaxKind.NewKeyword);
AddPunctuation(SyntaxKind.OpenParenToken);
AddPunctuation(SyntaxKind.CloseParenToken);
}
}
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.SymbolDisplay;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class SymbolDisplayVisitor
{
public override void VisitArrayType(IArrayTypeSymbol symbol)
{
VisitArrayTypeWithoutNullability(symbol);
AddNullableAnnotations(symbol);
}
private void VisitArrayTypeWithoutNullability(IArrayTypeSymbol symbol)
{
if (TryAddAlias(symbol, builder))
{
return;
}
//See spec section 12.1 for the order of rank specifiers
//e.g. int[][,][,,] is stored as
// ArrayType
// Rank = 1
// ElementType = ArrayType
// Rank = 2
// ElementType = ArrayType
// Rank = 3
// ElementType = int
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.ReverseArrayRankSpecifiers))
{
// Ironically, reverse order is simpler - we just have to recurse on the element type and then add a rank specifier.
symbol.ElementType.Accept(this);
AddArrayRank(symbol);
return;
}
ITypeSymbol underlyingType = symbol;
do
{
underlyingType = ((IArrayTypeSymbol)underlyingType).ElementType;
}
while (underlyingType.Kind == SymbolKind.ArrayType && !ShouldAddNullableAnnotation(underlyingType));
underlyingType.Accept(this.NotFirstVisitor);
var arrayType = symbol;
while (arrayType != null && arrayType != underlyingType)
{
if (!this.isFirstSymbolVisited)
{
AddCustomModifiersIfRequired(arrayType.CustomModifiers, leadingSpace: true);
}
AddArrayRank(arrayType);
arrayType = arrayType.ElementType as IArrayTypeSymbol;
}
}
private void AddNullableAnnotations(ITypeSymbol type)
{
if (ShouldAddNullableAnnotation(type))
{
AddPunctuation(type.NullableAnnotation == CodeAnalysis.NullableAnnotation.Annotated ? SyntaxKind.QuestionToken : SyntaxKind.ExclamationToken);
}
}
private bool ShouldAddNullableAnnotation(ITypeSymbol type)
{
switch (type.NullableAnnotation)
{
case CodeAnalysis.NullableAnnotation.Annotated:
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier) &&
!ITypeSymbolHelpers.IsNullableType(type) && !type.IsValueType)
{
return true;
}
break;
case CodeAnalysis.NullableAnnotation.NotAnnotated:
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier) &&
!type.IsValueType &&
(type as Symbols.PublicModel.TypeSymbol)?.UnderlyingTypeSymbol.IsTypeParameterDisallowingAnnotationInCSharp8() != true)
{
return true;
}
break;
}
return false;
}
private void AddArrayRank(IArrayTypeSymbol symbol)
{
bool insertStars = format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays);
AddPunctuation(SyntaxKind.OpenBracketToken);
if (symbol.Rank > 1)
{
if (insertStars)
{
AddPunctuation(SyntaxKind.AsteriskToken);
}
}
else
{
if (!symbol.IsSZArray)
{
// Always add an asterisk in this case in order to distinguish between SZArray and MDArray.
AddPunctuation(SyntaxKind.AsteriskToken);
}
}
for (int i = 0; i < symbol.Rank - 1; i++)
{
AddPunctuation(SyntaxKind.CommaToken);
if (insertStars)
{
AddPunctuation(SyntaxKind.AsteriskToken);
}
}
AddPunctuation(SyntaxKind.CloseBracketToken);
}
public override void VisitPointerType(IPointerTypeSymbol symbol)
{
symbol.PointedAtType.Accept(this.NotFirstVisitor);
AddNullableAnnotations(symbol);
if (!this.isFirstSymbolVisited)
{
AddCustomModifiersIfRequired(symbol.CustomModifiers, leadingSpace: true);
}
AddPunctuation(SyntaxKind.AsteriskToken);
}
public override void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol)
{
VisitMethod(symbol.Signature);
}
public override void VisitTypeParameter(ITypeParameterSymbol symbol)
{
if (this.isFirstSymbolVisited)
{
AddTypeParameterVarianceIfRequired(symbol);
}
//variance and constraints are handled by methods and named types
builder.Add(CreatePart(SymbolDisplayPartKind.TypeParameterName, symbol, symbol.Name));
AddNullableAnnotations(symbol);
}
public override void VisitDynamicType(IDynamicTypeSymbol symbol)
{
builder.Add(CreatePart(SymbolDisplayPartKind.Keyword, symbol, symbol.Name));
AddNullableAnnotations(symbol);
}
public override void VisitNamedType(INamedTypeSymbol symbol)
{
VisitNamedTypeWithoutNullability(symbol);
AddNullableAnnotations(symbol);
}
private void VisitNamedTypeWithoutNullability(INamedTypeSymbol symbol)
{
if (this.IsMinimizing && TryAddAlias(symbol, builder))
{
return;
}
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.UseSpecialTypes) ||
(symbol.IsNativeIntegerType && !format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseNativeIntegerUnderlyingType)))
{
if (AddSpecialTypeKeyword(symbol))
{
//if we're using special type keywords and this is a special type, then no other work is required
return;
}
}
if (!format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.ExpandNullable))
{
//if we're expanding nullable, we just visit nullable types normally
if (ITypeSymbolHelpers.IsNullableType(symbol) && !symbol.IsDefinition)
{
// Can't have a type called "int*?".
var typeArg = symbol.TypeArguments[0];
if (typeArg.TypeKind != TypeKind.Pointer)
{
typeArg.Accept(this.NotFirstVisitor);
AddCustomModifiersIfRequired(symbol.GetTypeArgumentCustomModifiers(0), leadingSpace: true, trailingSpace: false);
AddPunctuation(SyntaxKind.QuestionToken);
//visiting the underlying type did all of the work for us
return;
}
}
}
if (this.IsMinimizing || (symbol.IsTupleType && !ShouldDisplayAsValueTuple(symbol)))
{
MinimallyQualify(symbol);
return;
}
AddTypeKind(symbol);
if (CanShowDelegateSignature(symbol))
{
if (format.DelegateStyle == SymbolDisplayDelegateStyle.NameAndSignature)
{
var invokeMethod = symbol.DelegateInvokeMethod;
if (invokeMethod.ReturnsByRef)
{
AddRefIfRequired();
}
else if (invokeMethod.ReturnsByRefReadonly)
{
AddRefReadonlyIfRequired();
}
if (invokeMethod.ReturnsVoid)
{
AddKeyword(SyntaxKind.VoidKeyword);
}
else
{
AddReturnType(symbol.DelegateInvokeMethod);
}
AddSpace();
}
}
//only visit the namespace if the style requires it and there isn't an enclosing type
var containingSymbol = symbol.ContainingSymbol;
if (ShouldVisitNamespace(containingSymbol))
{
var namespaceSymbol = (INamespaceSymbol)containingSymbol;
var shouldSkip = namespaceSymbol.IsGlobalNamespace && symbol.TypeKind == TypeKind.Error;
if (!shouldSkip)
{
namespaceSymbol.Accept(this.NotFirstVisitor);
AddPunctuation(namespaceSymbol.IsGlobalNamespace ? SyntaxKind.ColonColonToken : SyntaxKind.DotToken);
}
}
//visit the enclosing type if the style requires it
if (format.TypeQualificationStyle == SymbolDisplayTypeQualificationStyle.NameAndContainingTypes ||
format.TypeQualificationStyle == SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)
{
if (IncludeNamedType(symbol.ContainingType))
{
symbol.ContainingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
}
AddNameAndTypeArgumentsOrParameters(symbol);
}
private bool ShouldDisplayAsValueTuple(INamedTypeSymbol symbol)
{
Debug.Assert(symbol.IsTupleType);
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseValueTuple))
{
return true;
}
return !CanUseTupleSyntax(symbol);
}
private void AddNameAndTypeArgumentsOrParameters(INamedTypeSymbol symbol)
{
if (symbol.IsAnonymousType)
{
AddAnonymousTypeName(symbol);
return;
}
else if (symbol.IsTupleType && !ShouldDisplayAsValueTuple(symbol))
{
AddTupleTypeName(symbol);
return;
}
string symbolName = null;
// It would be nice to handle VB NoPia symbols too, but it's not worth the effort.
NamedTypeSymbol underlyingTypeSymbol = (symbol as Symbols.PublicModel.NamedTypeSymbol)?.UnderlyingNamedTypeSymbol;
var illegalGenericInstantiationSymbol = underlyingTypeSymbol as NoPiaIllegalGenericInstantiationSymbol;
if (illegalGenericInstantiationSymbol is not null)
{
symbol = illegalGenericInstantiationSymbol.UnderlyingSymbol.GetPublicSymbol();
}
else
{
var ambiguousCanonicalTypeSymbol = underlyingTypeSymbol as NoPiaAmbiguousCanonicalTypeSymbol;
if (ambiguousCanonicalTypeSymbol is not null)
{
symbol = ambiguousCanonicalTypeSymbol.FirstCandidate.GetPublicSymbol();
}
else
{
var missingCanonicalTypeSymbol = underlyingTypeSymbol as NoPiaMissingCanonicalTypeSymbol;
if (missingCanonicalTypeSymbol is not null)
{
symbolName = missingCanonicalTypeSymbol.FullTypeName;
}
}
}
var partKind = GetPartKind(symbol);
symbolName ??= symbol.Name;
var renderSimpleAnonymousDelegate =
symbol.TypeKind == TypeKind.Delegate &&
!symbol.CanBeReferencedByName &&
!format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames);
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName) &&
partKind == SymbolDisplayPartKind.ErrorTypeName &&
string.IsNullOrEmpty(symbolName))
{
builder.Add(CreatePart(partKind, symbol, "?"));
}
else if (renderSimpleAnonymousDelegate)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.DelegateName, null, "<anonymous delegate>"));
}
else
{
symbolName = RemoveAttributeSufficeIfNecessary(symbol, symbolName);
builder.Add(CreatePart(partKind, symbol, symbolName));
}
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes))
{
// Only the compiler can set the internal option and the compiler doesn't use other implementations of INamedTypeSymbol.
if (underlyingTypeSymbol?.MangleName == true)
{
Debug.Assert(symbol.Arity > 0);
builder.Add(CreatePart(InternalSymbolDisplayPartKind.Arity, null,
MetadataHelpers.GetAritySuffix(symbol.Arity)));
}
}
else if (!renderSimpleAnonymousDelegate &&
symbol.Arity > 0 &&
format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeParameters))
{
// It would be nice to handle VB symbols too, but it's not worth the effort.
if (underlyingTypeSymbol is UnsupportedMetadataTypeSymbol || underlyingTypeSymbol is MissingMetadataTypeSymbol || symbol.IsUnboundGenericType)
{
AddPunctuation(SyntaxKind.LessThanToken);
for (int i = 0; i < symbol.Arity - 1; i++)
{
AddPunctuation(SyntaxKind.CommaToken);
}
AddPunctuation(SyntaxKind.GreaterThanToken);
}
else
{
AddTypeArguments(symbol, GetTypeArgumentsModifiers(underlyingTypeSymbol));
AddDelegateParameters(symbol);
// TODO: do we want to skip these if we're being visited as a containing type?
AddTypeParameterConstraints(symbol.TypeArguments);
}
}
else
{
AddDelegateParameters(symbol);
}
// Only the compiler can set the internal option and the compiler doesn't use other implementations of INamedTypeSymbol.
if (underlyingTypeSymbol?.OriginalDefinition is MissingMetadataTypeSymbol &&
format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.FlagMissingMetadataTypes))
{
//add it as punctuation - it's just for testing
AddPunctuation(SyntaxKind.OpenBracketToken);
builder.Add(CreatePart(InternalSymbolDisplayPartKind.Other, symbol, "missing"));
AddPunctuation(SyntaxKind.CloseBracketToken);
}
}
private ImmutableArray<ImmutableArray<CustomModifier>> GetTypeArgumentsModifiers(NamedTypeSymbol underlyingTypeSymbol)
{
if (this.format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers))
{
if ((object)underlyingTypeSymbol != null)
{
return underlyingTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.SelectAsArray(a => a.CustomModifiers);
}
}
return default;
}
private void AddDelegateParameters(INamedTypeSymbol symbol)
{
if (CanShowDelegateSignature(symbol))
{
if (format.DelegateStyle == SymbolDisplayDelegateStyle.NameAndParameters ||
format.DelegateStyle == SymbolDisplayDelegateStyle.NameAndSignature)
{
var method = symbol.DelegateInvokeMethod;
AddPunctuation(SyntaxKind.OpenParenToken);
AddParametersIfRequired(hasThisParameter: false, isVarargs: method.IsVararg, parameters: method.Parameters);
AddPunctuation(SyntaxKind.CloseParenToken);
}
}
}
private void AddAnonymousTypeName(INamedTypeSymbol symbol)
{
// TODO: revise to generate user-friendly name
var members = string.Join(", ", symbol.GetMembers().OfType<IPropertySymbol>().Select(CreateAnonymousTypeMember));
if (members.Length == 0)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.ClassName, symbol, "<empty anonymous type>"));
}
else
{
var name = $"<anonymous type: {members}>";
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.ClassName, symbol, name));
}
}
/// <summary>
/// Returns true if tuple type syntax can be used to refer to the tuple type without loss of information.
/// For example, it cannot be used when extension tuple is using non-default friendly names.
/// </summary>
/// <param name="tupleSymbol"></param>
/// <returns></returns>
private bool CanUseTupleSyntax(INamedTypeSymbol tupleSymbol)
{
if (containsModopt(tupleSymbol))
{
return false;
}
INamedTypeSymbol currentUnderlying = GetTupleUnderlyingTypeOrSelf(tupleSymbol);
if (currentUnderlying.Arity <= 1)
{
return false;
}
while (currentUnderlying.Arity == NamedTypeSymbol.ValueTupleRestPosition)
{
tupleSymbol = (INamedTypeSymbol)currentUnderlying.TypeArguments[NamedTypeSymbol.ValueTupleRestPosition - 1];
Debug.Assert(tupleSymbol.IsTupleType);
if (tupleSymbol.TypeKind == TypeKind.Error ||
HasNonDefaultTupleElements(tupleSymbol) ||
containsModopt(tupleSymbol))
{
return false;
}
currentUnderlying = GetTupleUnderlyingTypeOrSelf(tupleSymbol);
}
return true;
bool containsModopt(INamedTypeSymbol symbol)
{
NamedTypeSymbol underlyingTypeSymbol = (symbol as Symbols.PublicModel.NamedTypeSymbol)?.UnderlyingNamedTypeSymbol;
ImmutableArray<ImmutableArray<CustomModifier>> modifiers = GetTypeArgumentsModifiers(underlyingTypeSymbol);
if (modifiers.IsDefault)
{
return false;
}
return modifiers.Any(m => !m.IsEmpty);
}
}
private static INamedTypeSymbol GetTupleUnderlyingTypeOrSelf(INamedTypeSymbol type)
{
return type.TupleUnderlyingType ?? type;
}
private static bool HasNonDefaultTupleElements(INamedTypeSymbol tupleSymbol)
{
return tupleSymbol.TupleElements.Any(e => !e.IsDefaultTupleElement());
}
private void AddTupleTypeName(INamedTypeSymbol symbol)
{
Debug.Assert(symbol.IsTupleType);
ImmutableArray<IFieldSymbol> elements = symbol.TupleElements;
AddPunctuation(SyntaxKind.OpenParenToken);
for (int i = 0; i < elements.Length; i++)
{
var element = elements[i];
if (i != 0)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
VisitFieldType(element);
if (element.IsExplicitlyNamedTupleElement)
{
AddSpace();
builder.Add(CreatePart(SymbolDisplayPartKind.FieldName, symbol, element.Name));
}
}
AddPunctuation(SyntaxKind.CloseParenToken);
if (symbol.TypeKind == TypeKind.Error &&
format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.FlagMissingMetadataTypes))
{
//add it as punctuation - it's just for testing
AddPunctuation(SyntaxKind.OpenBracketToken);
builder.Add(CreatePart(InternalSymbolDisplayPartKind.Other, symbol, "missing"));
AddPunctuation(SyntaxKind.CloseBracketToken);
}
}
private string CreateAnonymousTypeMember(IPropertySymbol property)
{
return property.Type.ToDisplayString(format) + " " + property.Name;
}
private bool CanShowDelegateSignature(INamedTypeSymbol symbol)
{
return
isFirstSymbolVisited &&
symbol.TypeKind == TypeKind.Delegate &&
format.DelegateStyle != SymbolDisplayDelegateStyle.NameOnly &&
symbol.DelegateInvokeMethod != null;
}
private static SymbolDisplayPartKind GetPartKind(INamedTypeSymbol symbol)
{
switch (symbol.TypeKind)
{
case TypeKind.Class when symbol.IsRecord:
return SymbolDisplayPartKind.RecordClassName;
case TypeKind.Struct when symbol.IsRecord:
return SymbolDisplayPartKind.RecordStructName;
case TypeKind.Submission:
case TypeKind.Module:
case TypeKind.Class:
return SymbolDisplayPartKind.ClassName;
case TypeKind.Delegate:
return SymbolDisplayPartKind.DelegateName;
case TypeKind.Enum:
return SymbolDisplayPartKind.EnumName;
case TypeKind.Error:
return SymbolDisplayPartKind.ErrorTypeName;
case TypeKind.Interface:
return SymbolDisplayPartKind.InterfaceName;
case TypeKind.Struct:
return SymbolDisplayPartKind.StructName;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.TypeKind);
}
}
private bool AddSpecialTypeKeyword(INamedTypeSymbol symbol)
{
var specialTypeName = GetSpecialTypeName(symbol);
if (specialTypeName == null)
{
return false;
}
// cheat - skip escapeKeywordIdentifiers. not calling AddKeyword because someone
// else is working out the text for us
builder.Add(CreatePart(SymbolDisplayPartKind.Keyword, symbol, specialTypeName));
return true;
}
private static string GetSpecialTypeName(INamedTypeSymbol symbol)
{
switch (symbol.SpecialType)
{
case SpecialType.System_Void:
return "void";
case SpecialType.System_SByte:
return "sbyte";
case SpecialType.System_Int16:
return "short";
case SpecialType.System_Int32:
return "int";
case SpecialType.System_Int64:
return "long";
case SpecialType.System_IntPtr when symbol.IsNativeIntegerType:
return "nint";
case SpecialType.System_UIntPtr when symbol.IsNativeIntegerType:
return "nuint";
case SpecialType.System_Byte:
return "byte";
case SpecialType.System_UInt16:
return "ushort";
case SpecialType.System_UInt32:
return "uint";
case SpecialType.System_UInt64:
return "ulong";
case SpecialType.System_Single:
return "float";
case SpecialType.System_Double:
return "double";
case SpecialType.System_Decimal:
return "decimal";
case SpecialType.System_Char:
return "char";
case SpecialType.System_Boolean:
return "bool";
case SpecialType.System_String:
return "string";
case SpecialType.System_Object:
return "object";
default:
return null;
}
}
private void AddTypeKind(INamedTypeSymbol symbol)
{
if (isFirstSymbolVisited && format.KindOptions.IncludesOption(SymbolDisplayKindOptions.IncludeTypeKeyword))
{
if (symbol.IsAnonymousType)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.AnonymousTypeIndicator, null, "AnonymousType"));
AddSpace();
}
else if (symbol.IsTupleType && !ShouldDisplayAsValueTuple(symbol))
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.AnonymousTypeIndicator, null, "Tuple"));
AddSpace();
}
else
{
switch (symbol.TypeKind)
{
case TypeKind.Class when symbol.IsRecord:
AddKeyword(SyntaxKind.RecordKeyword);
AddSpace();
break;
case TypeKind.Struct when symbol.IsRecord:
// In case ref record structs are allowed in future, call AddKeyword(SyntaxKind.RefKeyword) and remove assertion.
Debug.Assert(!symbol.IsRefLikeType);
if (symbol.IsReadOnly)
{
AddKeyword(SyntaxKind.ReadOnlyKeyword);
AddSpace();
}
AddKeyword(SyntaxKind.RecordKeyword);
AddSpace();
AddKeyword(SyntaxKind.StructKeyword);
AddSpace();
break;
case TypeKind.Module:
case TypeKind.Class:
AddKeyword(SyntaxKind.ClassKeyword);
AddSpace();
break;
case TypeKind.Enum:
AddKeyword(SyntaxKind.EnumKeyword);
AddSpace();
break;
case TypeKind.Delegate:
AddKeyword(SyntaxKind.DelegateKeyword);
AddSpace();
break;
case TypeKind.Interface:
AddKeyword(SyntaxKind.InterfaceKeyword);
AddSpace();
break;
case TypeKind.Struct:
if (symbol.IsReadOnly)
{
AddKeyword(SyntaxKind.ReadOnlyKeyword);
AddSpace();
}
if (symbol.IsRefLikeType)
{
AddKeyword(SyntaxKind.RefKeyword);
AddSpace();
}
AddKeyword(SyntaxKind.StructKeyword);
AddSpace();
break;
}
}
}
}
private void AddTypeParameterVarianceIfRequired(ITypeParameterSymbol symbol)
{
if (format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeVariance))
{
switch (symbol.Variance)
{
case VarianceKind.In:
AddKeyword(SyntaxKind.InKeyword);
AddSpace();
break;
case VarianceKind.Out:
AddKeyword(SyntaxKind.OutKeyword);
AddSpace();
break;
}
}
}
//returns true if there are constraints
private void AddTypeArguments(ISymbol owner, ImmutableArray<ImmutableArray<CustomModifier>> modifiers)
{
ImmutableArray<ITypeSymbol> typeArguments;
if (owner.Kind == SymbolKind.Method)
{
typeArguments = ((IMethodSymbol)owner).TypeArguments;
}
else
{
typeArguments = ((INamedTypeSymbol)owner).TypeArguments;
}
if (typeArguments.Length > 0 && format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeParameters))
{
AddPunctuation(SyntaxKind.LessThanToken);
var first = true;
for (int i = 0; i < typeArguments.Length; i++)
{
var typeArg = typeArguments[i];
if (!first)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
first = false;
AbstractSymbolDisplayVisitor visitor;
if (typeArg.Kind == SymbolKind.TypeParameter)
{
var typeParam = (ITypeParameterSymbol)typeArg;
AddTypeParameterVarianceIfRequired(typeParam);
visitor = this.NotFirstVisitor;
}
else
{
visitor = this.NotFirstVisitorNamespaceOrType;
}
typeArg.Accept(visitor);
if (!modifiers.IsDefault)
{
AddCustomModifiersIfRequired(modifiers[i], leadingSpace: true, trailingSpace: false);
}
}
AddPunctuation(SyntaxKind.GreaterThanToken);
}
}
private static bool TypeParameterHasConstraints(ITypeParameterSymbol typeParam)
{
return !typeParam.ConstraintTypes.IsEmpty || typeParam.HasConstructorConstraint ||
typeParam.HasReferenceTypeConstraint || typeParam.HasValueTypeConstraint ||
typeParam.HasNotNullConstraint;
}
private void AddTypeParameterConstraints(ImmutableArray<ITypeSymbol> typeArguments)
{
if (this.isFirstSymbolVisited && format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeConstraints))
{
foreach (var typeArg in typeArguments)
{
if (typeArg.Kind == SymbolKind.TypeParameter)
{
var typeParam = (ITypeParameterSymbol)typeArg;
if (TypeParameterHasConstraints(typeParam))
{
AddSpace();
AddKeyword(SyntaxKind.WhereKeyword);
AddSpace();
typeParam.Accept(this.NotFirstVisitor);
AddSpace();
AddPunctuation(SyntaxKind.ColonToken);
AddSpace();
bool needComma = false;
//class/struct constraint must be first
if (typeParam.HasReferenceTypeConstraint)
{
AddKeyword(SyntaxKind.ClassKeyword);
switch (typeParam.ReferenceTypeConstraintNullableAnnotation)
{
case CodeAnalysis.NullableAnnotation.Annotated:
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier))
{
AddPunctuation(SyntaxKind.QuestionToken);
}
break;
case CodeAnalysis.NullableAnnotation.NotAnnotated:
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))
{
AddPunctuation(SyntaxKind.ExclamationToken);
}
break;
}
needComma = true;
}
else if (typeParam.HasUnmanagedTypeConstraint)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "unmanaged"));
needComma = true;
}
else if (typeParam.HasValueTypeConstraint)
{
AddKeyword(SyntaxKind.StructKeyword);
needComma = true;
}
else if (typeParam.HasNotNullConstraint)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "notnull"));
needComma = true;
}
for (int i = 0; i < typeParam.ConstraintTypes.Length; i++)
{
ITypeSymbol baseType = typeParam.ConstraintTypes[i];
if (needComma)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
baseType.Accept(this.NotFirstVisitor);
needComma = true;
}
//ctor constraint must be last
if (typeParam.HasConstructorConstraint)
{
if (needComma)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
AddKeyword(SyntaxKind.NewKeyword);
AddPunctuation(SyntaxKind.OpenParenToken);
AddPunctuation(SyntaxKind.CloseParenToken);
}
}
}
}
}
}
}
}
| 1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/CSharp/Test/Symbol/SymbolDisplay/SymbolDisplayTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Globalization;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class SymbolDisplayTests : CSharpTestBase
{
[Fact]
public void TestClassNameOnlySimple()
{
var text = "class A {}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("A", 0).Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly);
TestSymbolDescription(
text,
findSymbol,
format,
"A",
SymbolDisplayPartKind.ClassName);
}
[Fact, WorkItem(46985, "https://github.com/dotnet/roslyn/issues/46985")]
public void TestRecordNameOnlySimple()
{
var text = "record A {}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("A", 0).Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly);
TestSymbolDescription(
text,
findSymbol,
format,
"A",
SymbolDisplayPartKind.RecordClassName);
}
[Fact, WorkItem(46985, "https://github.com/dotnet/roslyn/issues/46985")]
public void TestRecordNameOnlyComplex()
{
var text = @"
namespace N1 {
namespace N2.N3 {
record R1 {
record R2 {} } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("R1").Single().
GetTypeMembers("R2").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly);
TestSymbolDescription(
text,
findSymbol,
format,
"R2",
SymbolDisplayPartKind.RecordClassName);
}
[Fact]
public void TestClassNameOnlyComplex()
{
var text = @"
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {} } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly);
TestSymbolDescription(
text,
findSymbol,
format,
"C2",
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestFullyQualifiedFormat()
{
var text = @"
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {} } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single();
TestSymbolDescription(
text,
findSymbol,
SymbolDisplayFormat.FullyQualifiedFormat,
"global::N1.N2.N3.C1.C2",
SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestClassNameAndContainingTypesSimple()
{
var text = "class A {}";
Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("A", 0).Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"A",
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestClassNameAndContainingTypesComplex()
{
var text = @"
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {} } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"C1.C2",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestMethodNameOnlySimple()
{
var text = @"
class A {
void M() {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("A", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat();
TestSymbolDescription(
text,
findSymbol,
format,
"M",
SymbolDisplayPartKind.MethodName);
}
[Fact]
public void TestMethodNameOnlyComplex()
{
var text = @"
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {
public static int[] M(int? x, C1 c) {} } } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat();
TestSymbolDescription(
text,
findSymbol,
format,
"M",
SymbolDisplayPartKind.MethodName);
}
[Fact]
public void TestMethodAndParamsSimple()
{
var text = @"
class A {
void M() {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("A", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"private void M()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestMethodAndParamsComplex()
{
var text = @"
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {
public static int[] M(int? x, C1 c) {} } } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public static int[] M(int? x, C1 c)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //x
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //c
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestExtensionMethodAsStatic()
{
var text = @"
class C1<T> { }
class C2 {
public static TSource M<TSource>(this C1<TSource> source, int index) {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C2").Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public static TSource C2.M<TSource>(this C1<TSource> source, int index)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C2
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //source
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //index
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestExtensionMethodAsInstance()
{
var text = @"
class C1<T> { }
class C2 {
public static TSource M<TSource>(this C1<TSource> source, int index) {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C2").Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.InstanceMethod,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public TSource C1<TSource>.M<TSource>(int index)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ExtensionMethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //index
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestExtensionMethodAsDefault()
{
var text = @"
class C1<T> { }
class C2 {
public static TSource M<TSource>(this C1<TSource> source, int index) {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C2").Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.Default,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public static TSource C2.M<TSource>(this C1<TSource> source, int index)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C2
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //source
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //index
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestReducedExtensionMethodAsStatic()
{
var text = @"
class C1 { }
class C2 {
public static TSource M<TSource>(this C1 source, int index) {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
{
var type = global.GetTypeMember("C1");
var method = (MethodSymbol)global.GetTypeMember("C2").GetMember("M");
return method.ReduceExtensionMethod(type, null!);
};
var format = new SymbolDisplayFormat(
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public static TSource C2.M<TSource>(this C1 source, int index)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C2
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //source
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //index
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestReducedExtensionMethodAsInstance()
{
var text = @"
class C1 { }
class C2 {
public static TSource M<TSource>(this C1 source, int index) {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
{
var type = global.GetTypeMember("C1");
var method = (MethodSymbol)global.GetTypeMember("C2").GetMember("M");
return method.ReduceExtensionMethod(type, null!);
};
var format = new SymbolDisplayFormat(
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.InstanceMethod,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public TSource C1.M<TSource>(int index)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ExtensionMethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //index
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestReducedExtensionMethodAsDefault()
{
var text = @"
class C1 { }
class C2 {
public static TSource M<TSource>(this C1 source, int index) {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
{
var type = global.GetTypeMember("C1");
var method = (MethodSymbol)global.GetTypeMember("C2").GetMember("M");
return method.ReduceExtensionMethod(type, null!);
};
var format = new SymbolDisplayFormat(
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.Default,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public TSource C1.M<TSource>(int index)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ExtensionMethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //index
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestPrivateProtected()
{
var text = @"class C2 { private protected void M() {} }";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C2").Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType);
TestSymbolDescription(
text,
findSymbol,
format,
"private protected void C2.M()",
SymbolDisplayPartKind.Keyword, // private
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // protected
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // void
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C2
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestNullParameters()
{
var text = @"
class A {
int[][,][,,] f; }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("A", 0).Single().
GetMembers("f").Single();
SymbolDisplayFormat format = null;
TestSymbolDescription(
text,
findSymbol,
format,
"A.f",
SymbolDisplayPartKind.ClassName, //A
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.FieldName); //f
}
[Fact]
public void TestArrayRank()
{
var text = @"
class A {
int[][,][,,] f; }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("A", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"int[][,][,,] f",
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Punctuation, //[
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation, //[
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation, //[
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName); //f
}
[Fact]
public void TestOptionalParameters_Bool()
{
var text = @"
using System.Runtime.InteropServices;
class C
{
void F([Optional]bool arg) { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"void F(bool arg)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // arg
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameters_String()
{
var text = @"
class C
{
void F(string s = ""f\t\r\noo"") { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
@"void F(string s = ""f\t\r\noo"")",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // s
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, // =
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StringLiteral,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameters_ReferenceType()
{
var text = @"
using System.Runtime.InteropServices;
class C
{
void F([Optional]C arg) { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"void F(C arg)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // arg
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameters_Constrained_Class()
{
var text = @"
using System.Runtime.InteropServices;
class C
{
void F<T>([Optional]T arg) where T : class { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"void F(T arg)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // arg
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameters_Constrained_Struct()
{
var text = @"
using System.Runtime.InteropServices;
class C
{
void F<T>([Optional]T arg) where T : struct { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"void F(T arg)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // arg
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameters_Unconstrained()
{
var text = @"
using System.Runtime.InteropServices;
class C
{
void F<T>([Optional]T arg) { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"void F(T arg)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // arg
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameters_ArrayAndType()
{
var text = @"
using System.Runtime.InteropServices;
class C
{
void F<T>(int a, [Optional]double[] arg, int b, [Optional]System.Type t) { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"void F(int a, double[] arg, int b, Type t)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword, // int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // a
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // double
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // arg
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // b
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, // Type
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // t
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestEscapeKeywordIdentifiers()
{
var text = @"
class @true {
@true @false(@true @true, bool @bool = true) { return @true; } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("true", 0).Single().
GetMembers("false").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"@true @false(@true @true, bool @bool = true)",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, //@false
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //@true
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //@bool
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestNoEscapeKeywordIdentifiers()
{
var text = @"
class @true {
@true @false(@true @true, bool @bool = true) { return @true; } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("true", 0).Single().
GetMembers("false").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"true false(true true, bool bool = true)",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // @false
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // @true
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // @bool
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestExplicitMethodImplNameOnly()
{
var text = @"
interface I {
void M(); }
class C : I {
void I.M() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("I.M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.None);
TestSymbolDescription(
text,
findSymbol,
format,
"M",
SymbolDisplayPartKind.MethodName); //M
}
[Fact]
public void TestExplicitMethodImplNameAndInterface()
{
var text = @"
interface I {
void M(); }
class C : I {
void I.M() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("I.M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface);
TestSymbolDescription(
text,
findSymbol,
format,
"I.M",
SymbolDisplayPartKind.InterfaceName, //I
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName); //M
}
[Fact]
public void TestExplicitMethodImplNameAndInterfaceAndType()
{
var text = @"
interface I {
void M(); }
class C : I {
void I.M() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("I.M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType);
TestSymbolDescription(
text,
findSymbol,
format,
"C.I.M",
SymbolDisplayPartKind.ClassName, //C
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.InterfaceName, //I
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName); //M
}
[Fact]
public void TestGlobalNamespaceCode()
{
var text = @"
class C { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included);
TestSymbolDescription(
text,
findSymbol,
format,
"global::C",
SymbolDisplayPartKind.Keyword, //global
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName); //C
}
[Fact]
public void TestGlobalNamespaceHumanReadable()
{
var text = @"
class C { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global;
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included);
TestSymbolDescription(
text,
findSymbol,
format,
"<global namespace>",
SymbolDisplayPartKind.Text);
}
[Fact]
public void TestSpecialTypes()
{
var text = @"
class C {
int f; }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"int f",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[Fact]
public void TestArrayAsterisks()
{
var text = @"
class C {
int[][,][,,] f; }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays);
TestSymbolDescription(
text,
findSymbol,
format,
"Int32[][*,*][*,*,*] f",
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[Fact]
public void TestMetadataMethodNames()
{
var text = @"
class C {
C() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers(".ctor").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames);
TestSymbolDescription(
text,
findSymbol,
format,
".ctor",
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestArityForGenericTypes()
{
var text = @"
class C<T, U, V> { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 3).Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"C`3",
SymbolDisplayPartKind.ClassName,
InternalSymbolDisplayPartKind.Arity);
}
[Fact]
public void TestGenericTypeParameters()
{
var text = @"
class C<in T, out U, V> { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 3).Single();
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
TestSymbolDescription(
text,
findSymbol,
format,
"C<T, U, V>",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestGenericTypeParametersAndVariance()
{
var text = @"
class C<in T, out U, V> { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 3).Single();
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance);
TestSymbolDescription(
text,
findSymbol,
format,
"C<in T, out U, V>",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestGenericTypeConstraints()
{
var text = @"
class C<T> where T : C<T> { }
";
Func<NamespaceSymbol, Symbol> findType = global =>
global.GetMember<NamedTypeSymbol>("C");
Func<NamespaceSymbol, Symbol> findTypeParameter = global =>
global.GetMember<NamedTypeSymbol>("C").TypeParameters.Single();
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints);
TestSymbolDescription(text, findType,
format,
"C<T> where T : C<T>",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation);
TestSymbolDescription(text, findTypeParameter,
format,
"T",
SymbolDisplayPartKind.TypeParameterName);
}
[Fact]
public void TestGenericMethodParameters()
{
var text = @"
class C {
void M<in T, out U, V>() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
TestSymbolDescription(
text,
findSymbol,
format,
"M<T, U, V>",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestGenericMethodParametersAndVariance()
{
var text = @"
class C {
void M<in T, out U, V>() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance);
TestSymbolDescription(
text,
findSymbol,
format,
"M<T, U, V>",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestGenericMethodConstraints()
{
var text = @"
class C<T>
{
void M<U, V>() where V : class, U, T {}
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M");
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints);
TestSymbolDescription(
text,
findSymbol,
format,
"M<U, V> where V : class, U, T",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName);
}
[Fact]
public void TestMemberMethodNone()
{
var text = @"
class C {
void M(int p) { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.None);
TestSymbolDescription(
text,
findSymbol,
format,
"M",
SymbolDisplayPartKind.MethodName);
}
[Fact]
public void TestMemberMethodAll()
{
var text = @"
class C {
void M(int p) { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private void C.M()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestMemberFieldNone()
{
var text = @"
class C {
int f; }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.None);
TestSymbolDescription(
text,
findSymbol,
format,
"f",
SymbolDisplayPartKind.FieldName);
}
[Fact]
public void TestMemberFieldAll()
{
var text =
@"class C {
int f;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private Int32 C.f",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.FieldName);
}
[Fact]
public void TestMemberPropertyNone()
{
var text = @"
class C {
int P { get; } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("P").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.None);
TestSymbolDescription(
text,
findSymbol,
format,
"P",
SymbolDisplayPartKind.PropertyName);
}
[Fact]
public void TestMemberPropertyAll()
{
var text = @"
class C {
int P { get; } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("P").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private Int32 C.P",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName);
}
[Fact]
public void TestMemberPropertyGetSet()
{
var text = @"
class C
{
int P { get; }
object Q { set; }
object R { get { return null; } set { } }
}
";
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor);
TestSymbolDescription(
text,
global => global.GetTypeMembers("C", 0).Single().GetMembers("P").Single(),
format,
"Int32 P { get; }",
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
TestSymbolDescription(
text,
global => global.GetTypeMembers("C", 0).Single().GetMembers("Q").Single(),
format,
"Object Q { set; }",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
TestSymbolDescription(
text,
global => global.GetTypeMembers("C", 0).Single().GetMembers("R").Single(),
format,
"Object R { get; set; }",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestPropertyGetAccessor()
{
var text = @"
class C {
int P { get; set; } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("get_P").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private Int32 C.P.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[Fact]
public void TestPropertySetAccessor()
{
var text = @"
class C {
int P { get; set; } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("set_P").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private void C.P.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[Fact]
public void TestMemberEventAll()
{
var text = @"
class C {
event System.Action E;
event System.Action F { add { } remove { } } }
";
Func<NamespaceSymbol, Symbol> findSymbol1 = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMembers("E").Where(m => m.Kind == SymbolKind.Event).Single();
Func<NamespaceSymbol, Symbol> findSymbol2 = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMember<EventSymbol>("F");
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol1,
format,
"private Action C.E",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
TestSymbolDescription(
text,
findSymbol2,
format,
"private Action C.F",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
}
[Fact]
public void TestMemberEventAddRemove()
{
var text = @"
class C {
event System.Action E;
event System.Action F { add { } remove { } } }
";
Func<NamespaceSymbol, Symbol> findSymbol1 = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMembers("E").Where(m => m.Kind == SymbolKind.Event).Single();
Func<NamespaceSymbol, Symbol> findSymbol2 = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMember<EventSymbol>("F");
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor); // Does not affect events (did before rename).
TestSymbolDescription(
text,
findSymbol1,
format,
"Action E",
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EventName);
TestSymbolDescription(
text,
findSymbol2,
format,
"Action F",
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EventName);
}
[Fact]
public void TestEventAddAccessor()
{
var text = @"
class C {
event System.Action E { add { } remove { } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMembers("add_E").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private void C.E.add",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[Fact]
public void TestEventRemoveAccessor()
{
var text = @"
class C {
event System.Action E { add { } remove { } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMembers("remove_E").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private void C.E.remove",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[Fact]
public void TestParameterMethodNone()
{
var text = @"
static class C {
static void M(this object obj, ref short s, int i = 1) { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.None);
TestSymbolDescription(
text,
findSymbol,
format,
"M()",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestMethodReturnType1()
{
var text = @"
static class C {
static int M() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"System.Int32 M()",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestMethodReturnType2()
{
var text = @"
static class C {
static void M() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"void M()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestParameterMethodNameTypeModifiers()
{
var text = @"
class C {
void M(ref short s, int i, params string[] args) { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions:
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName);
TestSymbolDescription(
text,
findSymbol,
format,
"M(ref Int16 s, Int32 i, params String[] args)",
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //s
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //i
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //args
SymbolDisplayPartKind.Punctuation);
// Without SymbolDisplayParameterOptions.IncludeParamsRefOut.
TestSymbolDescription(
text,
findSymbol,
format.WithParameterOptions(SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName),
"M(Int16 s, Int32 i, String[] args)",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
// Without SymbolDisplayParameterOptions.IncludeType, drops
// ref/out/params modifiers. (VB retains ByRef/ParamArray.)
TestSymbolDescription(
text,
findSymbol,
format.WithParameterOptions(SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeName),
"M(s, i, args)",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact()]
public void TestParameterMethodNameAll()
{
var text = @"
static class C {
static void M(this object self, ref short s, int i = 1, params string[] args) { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions:
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue);
TestSymbolDescription(
text,
findSymbol,
format,
"M(this Object self, ref Int16 s, Int32 i = 1, params String[] args)",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //self
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //s
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //i
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NumericLiteral,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //args
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameterBrackets()
{
var text = @"
class C {
void M(int i = 0) { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions:
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeOptionalBrackets);
TestSymbolDescription(
text,
findSymbol,
format,
"M([Int32 i])",
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //i
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
/// <summary>
/// "public" and "abstract" should not be included for interface members.
/// </summary>
[Fact]
public void TestInterfaceMembers()
{
var text = @"
interface I
{
int P { get; }
object F();
}
abstract class C
{
public abstract object F();
interface I
{
void M();
}
}";
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType,
propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
global => global.GetTypeMembers("I", 0).Single().GetMembers("P").Single(),
format,
"int P { get; }");
TestSymbolDescription(
text,
global => global.GetTypeMembers("I", 0).Single().GetMembers("F").Single(),
format,
"object F()");
TestSymbolDescription(
text,
global => global.GetTypeMembers("C", 0).Single().GetMembers("F").Single(),
format,
"public abstract object F()");
TestSymbolDescription(
text,
global => global.GetTypeMembers("C", 0).Single().GetTypeMembers("I", 0).Single().GetMembers("M").Single(),
format,
"void M()");
}
[WorkItem(537447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537447")]
[Fact]
public void TestBug2239()
{
var text = @"
public class GC1<T> {}
public class X : GC1<BOGUS> {}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("X", 0).Single().
BaseType();
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
TestSymbolDescription(
text,
findSymbol,
format,
"GC1<BOGUS>",
SymbolDisplayPartKind.ClassName, //GC1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ErrorTypeName, //BOGUS
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestAlias1()
{
var text = @"
using Goo = N1.N2.N3;
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {} } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces);
TestSymbolDescription(
text,
findSymbol,
format,
"Goo.C1.C2",
text.IndexOf("namespace", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.AliasName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestAlias2()
{
var text = @"
using Goo = N1.N2.N3.C1;
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {} } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces);
TestSymbolDescription(
text,
findSymbol,
format,
"Goo.C2",
text.IndexOf("namespace", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.AliasName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Theory, MemberData(nameof(FileScopedOrBracedNamespace))]
public void TestAlias3(string ob, string cb)
{
var text = @"
using Goo = N1.C1;
namespace N1 " + ob + @"
class Goo { }
class C1 { }
" + cb + @"
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetTypeMembers("C1").Single();
var format = SymbolDisplayFormat.MinimallyQualifiedFormat;
TestSymbolDescription(
text,
findSymbol,
format,
"C1",
text.IndexOf("class Goo", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestMinimalNamespace1()
{
var text = @"
namespace N1 {
namespace N2 {
namespace N3 {
class C1 {
class C2 {} } } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3");
var format = new SymbolDisplayFormat();
TestSymbolDescription(text, findSymbol, format,
"N1.N2.N3",
text.IndexOf("N1", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName);
TestSymbolDescription(text, findSymbol, format,
"N2.N3",
text.IndexOf("N2", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName);
TestSymbolDescription(text, findSymbol, format,
"N3",
text.IndexOf("N3", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.NamespaceName);
TestSymbolDescription(text, findSymbol, format,
"N3",
text.IndexOf("C1", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.NamespaceName);
TestSymbolDescription(text, findSymbol, format,
"N3",
text.IndexOf("C2", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.NamespaceName);
}
public class ScriptGlobals
{
public void Method(int p) { Event.Invoke(); }
public delegate void MyDelegate(int x);
public int Field;
public int Property => 1;
public event Action Event;
public class NestedType
{
public void Method(int p) { Event.Invoke(); }
public delegate void MyDelegate(int x);
public int Field;
public int Property => 1;
public event Action Event;
}
}
[Fact]
public void TestMembersInScriptGlobals()
{
var text = @"1";
var tree = SyntaxFactory.ParseSyntaxTree(text, TestOptions.Script);
var hostReference = MetadataReference.CreateFromFile(typeof(ScriptGlobals).Assembly.Location);
var comp = CSharpCompilation.CreateScriptCompilation(
"submission1",
tree,
TargetFrameworkUtil.GetReferences(TargetFramework.Standard).Concat(hostReference),
returnType: typeof(object),
globalsType: typeof(ScriptGlobals));
var model = comp.GetSemanticModel(tree);
var hostTypeSymbol = comp.GetHostObjectTypeSymbol();
var methodSymbol = hostTypeSymbol.GetMember("Method");
var delegateSymbol = hostTypeSymbol.GetMember("MyDelegate");
var fieldSymbol = hostTypeSymbol.GetMember("Field");
var propertySymbol = hostTypeSymbol.GetMember("Property");
var eventSymbol = hostTypeSymbol.GetMember("Event");
var nestedTypeSymbol = (TypeSymbol)hostTypeSymbol.GetMember("NestedType");
var nestedMethodSymbol = nestedTypeSymbol.GetMember("Method");
var nestedDelegateSymbol = nestedTypeSymbol.GetMember("MyDelegate");
var nestedFieldSymbol = nestedTypeSymbol.GetMember("Field");
var nestedPropertySymbol = nestedTypeSymbol.GetMember("Property");
var nestedEventSymbol = nestedTypeSymbol.GetMember("Event");
Verify(methodSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"void Method(int p)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(delegateSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"MyDelegate(int x)",
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(fieldSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"int Field",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
Verify(propertySymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"int Property { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(eventSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"event System.Action Event",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EventName);
Verify(nestedTypeSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"NestedType",
SymbolDisplayPartKind.ClassName);
Verify(nestedMethodSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"void NestedType.Method(int p)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(nestedDelegateSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"NestedType.MyDelegate(int x)",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(nestedFieldSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"int NestedType.Field",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.FieldName);
Verify(nestedPropertySymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"int NestedType.Property { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(nestedEventSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"event System.Action NestedType.Event",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
}
private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions:
SymbolDisplayMemberOptions.IncludeRef |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeContainingType,
delegateStyle:
SymbolDisplayDelegateStyle.NameAndSignature,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
propertyStyle:
SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeOptionalBrackets,
localOptions:
SymbolDisplayLocalOptions.IncludeRef |
SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName |
SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier |
SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral);
[Fact]
public void TestRemoveAttributeSuffix1()
{
var text = @"
class class1Attribute : System.Attribute { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("class1Attribute").Single();
TestSymbolDescription(text, findSymbol,
new SymbolDisplayFormat(),
"class1Attribute",
SymbolDisplayPartKind.ClassName);
TestSymbolDescription(text, findSymbol,
new SymbolDisplayFormat(miscellaneousOptions: SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix),
"class1",
0,
true,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestRemoveAttributeSuffix2()
{
var text = @"
class classAttribute : System.Attribute { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("classAttribute").Single();
TestSymbolDescription(text, findSymbol,
new SymbolDisplayFormat(),
"classAttribute",
SymbolDisplayPartKind.ClassName);
TestSymbolDescription(text, findSymbol,
new SymbolDisplayFormat(miscellaneousOptions: SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix),
"classAttribute",
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestRemoveAttributeSuffix3()
{
var text = @"
class class1Attribute { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("class1Attribute").Single();
TestSymbolDescription(text, findSymbol,
new SymbolDisplayFormat(),
"class1Attribute",
SymbolDisplayPartKind.ClassName);
TestSymbolDescription(text, findSymbol,
new SymbolDisplayFormat(miscellaneousOptions: SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix),
"class1Attribute",
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestMinimalClass1()
{
var text = @"
using System.Collections.Generic;
class C1 {
private System.Collections.Generic.IDictionary<System.Collections.Generic.IList<System.Int32>, System.String> goo;
}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
((FieldSymbol)global.GetTypeMembers("C1").Single().GetMembers("goo").Single()).Type;
var format = SymbolDisplayFormat.MinimallyQualifiedFormat;
TestSymbolDescription(text, findSymbol, format,
"IDictionary<IList<int>, string>",
text.IndexOf("goo", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.InterfaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.InterfaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestMethodCustomModifierPositions()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[]
{
TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll,
Net40.mscorlib
});
var globalNamespace = assemblies[0].GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("MethodCustomModifierCombinations");
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers);
Verify(@class.GetMember<MethodSymbol>("Method1111").ToDisplayParts(format),
"int modopt(IsConst) [] modopt(IsConst) Method1111(int modopt(IsConst) [] modopt(IsConst) a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(@class.GetMember<MethodSymbol>("Method1000").ToDisplayParts(format),
"int modopt(IsConst) [] Method1000(int[] a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(@class.GetMember<MethodSymbol>("Method0100").ToDisplayParts(format),
"int[] modopt(IsConst) Method0100(int[] a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(@class.GetMember<MethodSymbol>("Method0010").ToDisplayParts(format),
"int[] Method0010(int modopt(IsConst) [] a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(@class.GetMember<MethodSymbol>("Method0001").ToDisplayParts(format),
"int[] Method0001(int[] modopt(IsConst) a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(@class.GetMember<MethodSymbol>("Method0000").ToDisplayParts(format),
"int[] Method0000(int[] a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestPropertyCustomModifierPositions()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[]
{
TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll,
Net40.mscorlib
});
var globalNamespace = assemblies[0].GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("PropertyCustomModifierCombinations");
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers);
Verify(@class.GetMember<PropertySymbol>("Property11").ToDisplayParts(format),
"int modopt(IsConst) [] modopt(IsConst) Property11",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName);
Verify(@class.GetMember<PropertySymbol>("Property10").ToDisplayParts(format),
"int modopt(IsConst) [] Property10",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName);
Verify(@class.GetMember<PropertySymbol>("Property01").ToDisplayParts(format),
"int[] modopt(IsConst) Property01",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName);
Verify(@class.GetMember<PropertySymbol>("Property00").ToDisplayParts(format),
"int[] Property00",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName);
}
[Fact]
public void TestFieldCustomModifierPositions()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[]
{
TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll,
Net40.mscorlib
});
var globalNamespace = assemblies[0].GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("FieldCustomModifierCombinations");
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers);
Verify(@class.GetMember<FieldSymbol>("field11").ToDisplayParts(format),
"int modopt(IsConst) [] modopt(IsConst) field11",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
Verify(@class.GetMember<FieldSymbol>("field10").ToDisplayParts(format),
"int modopt(IsConst) [] field10",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
Verify(@class.GetMember<FieldSymbol>("field01").ToDisplayParts(format),
"int[] modopt(IsConst) field01",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
Verify(@class.GetMember<FieldSymbol>("field00").ToDisplayParts(format),
"int[] field00",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[Fact]
public void TestMultipleCustomModifier()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[]
{
TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll,
Net40.mscorlib
});
var globalNamespace = assemblies[0].GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("Modifiers");
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers);
Verify(@class.GetMember<MethodSymbol>("F3").ToDisplayParts(format),
"void F3(int modopt(int) modopt(IsConst) modopt(IsConst) p)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
}
private static void TestSymbolDescription(
string source,
Func<NamespaceSymbol, Symbol> findSymbol,
SymbolDisplayFormat format,
string expectedText,
int position,
bool minimal,
params SymbolDisplayPartKind[] expectedKinds)
{
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var global = comp.GlobalNamespace;
var symbol = findSymbol(global);
var description = minimal
? symbol.ToMinimalDisplayParts(model, position, format)
: symbol.ToDisplayParts(format);
Verify(description, expectedText, expectedKinds);
}
private static void TestSymbolDescription(
string source,
Func<NamespaceSymbol, Symbol> findSymbol,
SymbolDisplayFormat format,
string expectedText,
params SymbolDisplayPartKind[] expectedKinds)
{
TestSymbolDescription(source, findSymbol, format, null, expectedText, expectedKinds);
}
private static void TestSymbolDescription(
string source,
Func<NamespaceSymbol, Symbol> findSymbol,
SymbolDisplayFormat format,
CSharpParseOptions parseOptions,
string expectedText,
params SymbolDisplayPartKind[] expectedKinds)
{
var comp = CreateCompilation(source, parseOptions: parseOptions);
var global = comp.GlobalNamespace;
var symbol = findSymbol(global);
var description = symbol.ToDisplayParts(format);
Verify(description, expectedText, expectedKinds);
}
private static void Verify(ImmutableArray<SymbolDisplayPart> actualParts, string expectedText, params SymbolDisplayPartKind[] expectedKinds)
{
Assert.Equal(expectedText, actualParts.ToDisplayString());
if (expectedKinds.Length > 0)
{
AssertEx.Equal(expectedKinds, actualParts.Select(p => p.Kind), itemInspector: p => $" SymbolDisplayPartKind.{p}");
}
}
[Fact]
public void DelegateStyleRecursive()
{
var text = "public delegate void D(D param);";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("D", 0).Single();
var format = new SymbolDisplayFormat(globalNamespaceStyle: SymbolDisplayFormat.CSharpErrorMessageFormat.GlobalNamespaceStyle,
typeQualificationStyle: SymbolDisplayFormat.CSharpErrorMessageFormat.TypeQualificationStyle,
genericsOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.GenericsOptions,
memberOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.MemberOptions,
parameterOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.ParameterOptions,
propertyStyle: SymbolDisplayFormat.CSharpErrorMessageFormat.PropertyStyle,
localOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.LocalOptions,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
miscellaneousOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.MiscellaneousOptions);
TestSymbolDescription(
text,
findSymbol,
format,
"delegate void D(D)",
SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Punctuation);
format = new SymbolDisplayFormat(parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
miscellaneousOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.MiscellaneousOptions);
TestSymbolDescription(
text,
findSymbol,
format,
"void D(D param)",
SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void GlobalNamespace1()
{
var text = @"public class Test
{
public class System
{
public class Action
{
}
}
public global::System.Action field;
public System.Action field2;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
{
var field = global.GetTypeMembers("Test", 0).Single().GetMembers("field").Single() as FieldSymbol;
return field.Type;
};
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"global::System.Action",
text.IndexOf("global::System.Action", StringComparison.Ordinal),
true /* minimal */,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName);
}
[Fact]
public void GlobalNamespace2()
{
var text = @"public class Test
{
public class System
{
public class Action
{
}
}
public global::System.Action field;
public System.Action field2;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
{
var field = global.GetTypeMembers("Test", 0).Single().GetMembers("field").Single() as FieldSymbol;
return field.Type;
};
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"System.Action",
text.IndexOf("global::System.Action", StringComparison.Ordinal),
true /* minimal */,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName);
}
[Fact]
public void GlobalNamespace3()
{
var text = @"public class Test
{
public class System
{
public class Action
{
}
}
public System.Action field2;
public global::System.Action field;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
{
var field = global.GetTypeMembers("Test", 0).Single().GetMembers("field2").Single() as FieldSymbol;
return field.Type;
};
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"System.Action",
text.IndexOf("System.Action", StringComparison.Ordinal),
true /* minimal */,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void DefaultParameterValues()
{
var text = @"
struct S
{
void M(
int i = 1,
string str = ""hello"",
object o = null
S s = default(S))
{
}
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("M");
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(text, findSymbol,
format,
@"void S.M(int i = 1, string str = ""hello"", object o = null, S s = default(S))",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NumericLiteral,
SymbolDisplayPartKind.Punctuation, //,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StringLiteral,
SymbolDisplayPartKind.Punctuation, //,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation, //,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //)
SymbolDisplayPartKind.Punctuation); //)
}
[Fact]
public void DefaultParameterValues_TypeParameter()
{
var text = @"
struct S
{
void M<T>(T t = default(T))
{
}
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("M");
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(text, findSymbol,
format,
@"void S.M<T>(T t = default(T))",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //<
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation, //>
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation, //)
SymbolDisplayPartKind.Punctuation); //)
}
[Fact]
public void DefaultParameterValues_Enum()
{
var text = @"
enum E
{
A = 1,
B = 2,
C = 5,
}
struct S
{
void P(E e = (E)1)
{
}
void Q(E e = (E)3)
{
}
void R(E e = (E)5)
{
}
}";
Func<NamespaceSymbol, Symbol> findSymbol1 = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("P");
Func<NamespaceSymbol, Symbol> findSymbol2 = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("Q");
Func<NamespaceSymbol, Symbol> findSymbol3 = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("R");
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(text, findSymbol1,
format,
@"void S.P(E e = E.A)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation); //)
TestSymbolDescription(text, findSymbol2,
format,
@"void S.Q(E e = (E)3)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //)
SymbolDisplayPartKind.NumericLiteral,
SymbolDisplayPartKind.Punctuation); //)
TestSymbolDescription(text, findSymbol3,
format,
@"void S.R(E e = E.C)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation); //)
}
[Fact]
public void DefaultParameterValues_FlagsEnum()
{
var text = @"
[System.FlagsAttribute]
enum E
{
A = 1,
B = 2,
C = 5,
}
struct S
{
void P(E e = (E)1)
{
}
void Q(E e = (E)3)
{
}
void R(E e = (E)5)
{
}
}";
Func<NamespaceSymbol, Symbol> findSymbol1 = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("P");
Func<NamespaceSymbol, Symbol> findSymbol2 = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("Q");
Func<NamespaceSymbol, Symbol> findSymbol3 = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("R");
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(text, findSymbol1,
format,
@"void S.P(E e = E.A)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation); //)
TestSymbolDescription(text, findSymbol2,
format,
@"void S.Q(E e = E.A | E.B)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //|
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation); //)
TestSymbolDescription(text, findSymbol3,
format,
@"void S.R(E e = E.C)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void DefaultParameterValues_NegativeEnum()
{
var text = @"
[System.FlagsAttribute]
enum E : sbyte
{
A = -2,
A1 = -2,
B = 1,
B1 = 1,
C = 0,
C1 = 0,
}
struct S
{
void P(E e = (E)(-2), E f = (E)(-1), E g = (E)0, E h = (E)(-3))
{
}
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("P");
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(text, findSymbol,
format,
@"void S.P(E e = E.A, E f = E.A | E.B, E g = E.C, E h = (E)-3)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation, //,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //|
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation, //,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation, //,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, // =
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, // (
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, // )
SymbolDisplayPartKind.NumericLiteral,
SymbolDisplayPartKind.Punctuation); //)
}
[Fact]
public void TestConstantFieldValue()
{
var text =
@"class C {
const int f = 1;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeConstantValue);
TestSymbolDescription(
text,
findSymbol,
format,
"private const Int32 C.f = 1",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ConstantName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NumericLiteral);
}
[Fact]
public void TestConstantFieldValue_EnumMember()
{
var text =
@"
enum E { A, B, C }
class C {
const E f = E.B;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeConstantValue);
TestSymbolDescription(
text,
findSymbol,
format,
"private const E C.f = E.B",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ConstantName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName);
}
[Fact]
public void TestConstantFieldValue_EnumMember_Flags()
{
var text =
@"
[System.FlagsAttribute]
enum E { A = 1, B = 2, C = 4, D = A | B | C }
class C {
const E f = E.D;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeConstantValue);
TestSymbolDescription(
text,
findSymbol,
format,
"private const E C.f = E.D",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ConstantName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName);
}
[Fact]
public void TestEnumMember()
{
var text =
@"enum E { A, B, C }";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("E", 0).Single().
GetMembers("B").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeConstantValue);
TestSymbolDescription(
text,
findSymbol,
format,
"E.B = 1",
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NumericLiteral);
}
[Fact]
public void TestEnumMember_Flags()
{
var text =
@"[System.FlagsAttribute]
enum E { A = 1, B = 2, C = 4, D = A | B | C }";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("E", 0).Single().
GetMembers("D").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeConstantValue);
TestSymbolDescription(
text,
findSymbol,
format,
"E.D = E.A | E.B | E.C",
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName);
}
[Fact]
public void TestEnumMember_FlagsWithoutAttribute()
{
var text =
@"enum E { A = 1, B = 2, C = 4, D = A | B | C }";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("E", 0).Single().
GetMembers("D").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeConstantValue);
TestSymbolDescription(
text,
findSymbol,
format,
"E.D = 7",
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NumericLiteral);
}
[Fact, WorkItem(545462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545462")]
public void DateTimeDefaultParameterValue()
{
var text = @"
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class C
{
static void Goo([Optional][DateTimeConstant(100)] DateTime d) { }
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMember<MethodSymbol>("Goo");
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue);
TestSymbolDescription(
text,
findSymbol,
format,
"Goo(DateTime d)",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact, WorkItem(545681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545681")]
public void TypeParameterFromMetadata()
{
var src1 = @"
public class LibG<T>
{
}
";
var src2 = @"
public class Gen<V>
{
public void M(LibG<V> p)
{
}
}
";
var complib = CreateCompilation(src1, assemblyName: "Lib");
var compref = new CSharpCompilationReference(complib);
var comp1 = CreateCompilation(src2, references: new MetadataReference[] { compref }, assemblyName: "Comp1");
var mtdata = comp1.EmitToArray();
var mtref = MetadataReference.CreateFromImage(mtdata);
var comp2 = CreateCompilation("", references: new MetadataReference[] { mtref }, assemblyName: "Comp2");
var tsym1 = comp1.SourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("Gen");
Assert.NotNull(tsym1);
var msym1 = tsym1.GetMember<MethodSymbol>("M");
Assert.NotNull(msym1);
Assert.Equal("Gen<V>.M(LibG<V>)", msym1.ToDisplayString());
var tsym2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("Gen");
Assert.NotNull(tsym2);
var msym2 = tsym2.GetMember<MethodSymbol>("M");
Assert.NotNull(msym2);
Assert.Equal(msym1.ToDisplayString(), msym2.ToDisplayString());
}
[Fact, WorkItem(545625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545625")]
public void ReverseArrayRankSpecifiers()
{
var text = @"
public class C
{
C[][,] F;
}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("C").GetMember<FieldSymbol>("F").Type;
var normalFormat = new SymbolDisplayFormat();
var reverseFormat = new SymbolDisplayFormat(
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.ReverseArrayRankSpecifiers);
TestSymbolDescription(
text,
findSymbol,
normalFormat,
"C[][,]",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
TestSymbolDescription(
text,
findSymbol,
reverseFormat,
"C[,][]",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact, WorkItem(546638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546638")]
public void InvariantCultureNegatives()
{
var text = @"
public class C
{
void M(
sbyte p1 = (sbyte)-1,
short p2 = (short)-1,
int p3 = (int)-1,
long p4 = (long)-1,
float p5 = (float)-0.5,
double p6 = (double)-0.5,
decimal p7 = (decimal)-0.5)
{
}
}
";
var newCulture = (CultureInfo)CultureInfo.CurrentUICulture.Clone();
newCulture.NumberFormat.NegativeSign = "~";
newCulture.NumberFormat.NumberDecimalSeparator = ",";
using (new CultureContext(newCulture))
{
var compilation = CreateCompilation(text);
compilation.VerifyDiagnostics();
var symbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M");
Assert.Equal("void C.M(" +
"[System.SByte p1 = -1], " +
"[System.Int16 p2 = -1], " +
"[System.Int32 p3 = -1], " +
"[System.Int64 p4 = -1], " +
"[System.Single p5 = -0.5], " +
"[System.Double p6 = -0.5], " +
"[System.Decimal p7 = -0.5])", symbol.ToTestDisplayString());
}
}
[Fact]
public void TestMethodVB()
{
var text = @"
Class A
Public Sub Goo(a As Integer)
End Sub
End Class";
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var comp = CreateVisualBasicCompilation("c", text);
var a = (ITypeSymbol)comp.GlobalNamespace.GetMembers("A").Single();
var goo = a.GetMembers("Goo").Single();
var parts = Microsoft.CodeAnalysis.CSharp.SymbolDisplay.ToDisplayParts(goo, format);
Verify(
parts,
"public void Goo(int a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestWindowsRuntimeEvent()
{
var source = @"
class C
{
event System.Action E;
}
";
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface);
var comp = CreateEmptyCompilation(source, WinRtRefs, TestOptions.ReleaseWinMD);
var eventSymbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<EventSymbol>("E");
Assert.True(eventSymbol.IsWindowsRuntimeEvent);
Verify(
eventSymbol.ToDisplayParts(format),
"Action C.E",
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
Verify(
eventSymbol.AddMethod.ToDisplayParts(format),
"EventRegistrationToken C.E.add",
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(
eventSymbol.RemoveMethod.ToDisplayParts(format),
"void C.E.remove",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[WorkItem(791756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/791756")]
[Theory]
[MemberData(nameof(FileScopedOrBracedNamespace))]
public void KindOptions(string ob, string cb)
{
var source = @"
namespace N
" + ob + @"
class C
{
event System.Action E;
}
" + cb + @"
";
var memberFormat = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword);
var typeFormat = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
kindOptions: SymbolDisplayKindOptions.IncludeTypeKeyword);
var namespaceFormat = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword);
var comp = CreateCompilation(source);
var namespaceSymbol = comp.GlobalNamespace.GetMember<NamespaceSymbol>("N");
var typeSymbol = namespaceSymbol.GetMember<NamedTypeSymbol>("C");
var eventSymbol = typeSymbol.GetMember<EventSymbol>("E");
Verify(
namespaceSymbol.ToDisplayParts(memberFormat),
"N",
SymbolDisplayPartKind.NamespaceName);
Verify(
namespaceSymbol.ToDisplayParts(typeFormat),
"N",
SymbolDisplayPartKind.NamespaceName);
Verify(
namespaceSymbol.ToDisplayParts(namespaceFormat),
"namespace N",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName);
Verify(
typeSymbol.ToDisplayParts(memberFormat),
"N.C",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
Verify(
typeSymbol.ToDisplayParts(typeFormat),
"class N.C",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
Verify(
typeSymbol.ToDisplayParts(namespaceFormat),
"N.C",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
Verify(
eventSymbol.ToDisplayParts(memberFormat),
"event N.C.E",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
Verify(
eventSymbol.ToDisplayParts(typeFormat),
"N.C.E",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
Verify(
eventSymbol.ToDisplayParts(namespaceFormat),
"N.C.E",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
}
[WorkItem(765287, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/765287")]
[Fact]
public void TestVbSymbols()
{
var vbComp = CreateVisualBasicCompilation(@"
Class Outer
Class Inner(Of T)
End Class
Sub M(Of U)()
End Sub
WriteOnly Property P() As String
Set(value)
End Set
End Property
Private F As Integer
Event E()
Delegate Sub D()
Function [Error]() As Missing
End Function
End Class
", assemblyName: "VB");
var outer = (INamedTypeSymbol)vbComp.GlobalNamespace.GetMembers("Outer").Single();
var type = outer.GetMembers("Inner").Single();
var method = outer.GetMembers("M").Single();
var property = outer.GetMembers("P").Single();
var field = outer.GetMembers("F").Single();
var @event = outer.GetMembers("E").Single();
var @delegate = outer.GetMembers("D").Single();
var error = outer.GetMembers("Error").Single();
Assert.False(type is Symbol);
Assert.False(method is Symbol);
Assert.False(property is Symbol);
Assert.False(field is Symbol);
Assert.False(@event is Symbol);
Assert.False(@delegate is Symbol);
Assert.False(error is Symbol);
// 1) Looks like C#.
// 2) Doesn't blow up.
Assert.Equal("Outer.Inner<T>", CSharp.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat));
Assert.Equal("void Outer.M<U>()", CSharp.SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat));
Assert.Equal("System.String Outer.P { set; }", CSharp.SymbolDisplay.ToDisplayString(property, SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Int32 Outer.F", CSharp.SymbolDisplay.ToDisplayString(field, SymbolDisplayFormat.TestFormat));
Assert.Equal("event Outer.EEventHandler Outer.E", CSharp.SymbolDisplay.ToDisplayString(@event, SymbolDisplayFormat.TestFormat));
Assert.Equal("Outer.D", CSharp.SymbolDisplay.ToDisplayString(@delegate, SymbolDisplayFormat.TestFormat));
Assert.Equal("Missing Outer.Error()", CSharp.SymbolDisplay.ToDisplayString(error, SymbolDisplayFormat.TestFormat));
}
[Fact]
public void FormatPrimitive()
{
// basic tests, more cases are covered by ObjectFormatterTests
Assert.Equal("1", SymbolDisplay.FormatPrimitive(1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((uint)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((byte)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((sbyte)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((short)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((ushort)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((long)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((ulong)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("x", SymbolDisplay.FormatPrimitive('x', quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("true", SymbolDisplay.FormatPrimitive(true, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1.5", SymbolDisplay.FormatPrimitive(1.5, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1.5", SymbolDisplay.FormatPrimitive((float)1.5, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1.5", SymbolDisplay.FormatPrimitive((decimal)1.5, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("null", SymbolDisplay.FormatPrimitive(null, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("abc", SymbolDisplay.FormatPrimitive("abc", quoteStrings: false, useHexadecimalNumbers: false));
Assert.Null(SymbolDisplay.FormatPrimitive(SymbolDisplayFormat.TestFormat, quoteStrings: false, useHexadecimalNumbers: false));
}
[WorkItem(879984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879984")]
[Fact]
public void EnumAmbiguityResolution()
{
var source = @"
using System;
class Program
{
static void M(E1 e1 = (E1)1, E2 e2 = (E2)1)
{
}
}
enum E1
{
B = 1,
A = 1,
}
[Flags]
enum E2 // Identical to E1, but has [Flags]
{
B = 1,
A = 1,
}
";
var comp = CreateCompilation(source);
var method = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").GetMember<MethodSymbol>("M");
var memberFormat = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue);
Assert.Equal("M(e1 = A, e2 = A)", method.ToDisplayString(memberFormat)); // Alphabetically first candidate chosen for both enums.
}
[Fact, WorkItem(1028003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1028003")]
public void UnconventionalExplicitInterfaceImplementation()
{
var il = @"
.class public auto ansi sealed DTest
extends [mscorlib]System.MulticastDelegate
{
.method public hidebysig specialname rtspecialname
instance void .ctor(object 'object',
native int 'method') runtime managed
{
} // end of method DTest::.ctor
.method public hidebysig newslot virtual
instance void Invoke() runtime managed
{
} // end of method DTest::Invoke
.method public hidebysig newslot virtual
instance class [mscorlib]System.IAsyncResult
BeginInvoke(class [mscorlib]System.AsyncCallback callback,
object 'object') runtime managed
{
} // end of method DTest::BeginInvoke
.method public hidebysig newslot virtual
instance void EndInvoke(class [mscorlib]System.IAsyncResult result) runtime managed
{
} // end of method DTest::EndInvoke
} // end of class DTest
.class interface public abstract auto ansi ITest
{
.method public hidebysig newslot abstract virtual
instance void M1() cil managed
{
} // end of method ITest::M1
.method public hidebysig newslot specialname abstract virtual
instance int32 get_P1() cil managed
{
} // end of method ITest::get_P1
.method public hidebysig newslot specialname abstract virtual
instance void set_P1(int32 'value') cil managed
{
} // end of method ITest::set_P1
.method public hidebysig newslot specialname abstract virtual
instance void add_E1(class DTest 'value') cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
} // end of method ITest::add_E1
.method public hidebysig newslot specialname abstract virtual
instance void remove_E1(class DTest 'value') cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
} // end of method ITest::remove_E1
.event DTest E1
{
.addon instance void ITest::add_E1(class DTest)
.removeon instance void ITest::remove_E1(class DTest)
} // end of event ITest::E1
.property instance int32 P1()
{
.get instance int32 ITest::get_P1()
.set instance void ITest::set_P1(int32)
} // end of property ITest::P1
} // end of class ITest
.class public auto ansi beforefieldinit CTest
extends [mscorlib]System.Object
implements ITest
{
.method public hidebysig newslot specialname virtual final
instance int32 get_P1() cil managed
{
.override ITest::get_P1
// Code size 7 (0x7)
.maxstack 8
IL_0000: nop
IL_0001: newobj instance void [mscorlib]System.NotImplementedException::.ctor()
IL_0006: throw
} // end of method CTest::ITest.get_P1
.method public hidebysig newslot specialname virtual final
instance void set_P1(int32 'value') cil managed
{
.override ITest::set_P1
// Code size 7 (0x7)
.maxstack 8
IL_0000: nop
IL_0001: newobj instance void [mscorlib]System.NotImplementedException::.ctor()
IL_0006: throw
} // end of method CTest::ITest.set_P1
.method public hidebysig newslot specialname virtual final
instance void add_E1(class DTest 'value') cil managed
{
.override ITest::add_E1
// Code size 7 (0x7)
.maxstack 8
IL_0000: nop
IL_0001: newobj instance void [mscorlib]System.NotImplementedException::.ctor()
IL_0006: throw
} // end of method CTest::ITest.add_E1
.method public hidebysig newslot specialname virtual final
instance void remove_E1(class DTest 'value') cil managed
{
.override ITest::remove_E1
// Code size 7 (0x7)
.maxstack 8
IL_0000: nop
IL_0001: newobj instance void [mscorlib]System.NotImplementedException::.ctor()
IL_0006: throw
} // end of method CTest::ITest.remove_E1
.method public hidebysig newslot virtual final
instance void M1() cil managed
{
.override ITest::M1
// Code size 7 (0x7)
.maxstack 8
IL_0000: nop
IL_0001: newobj instance void [mscorlib]System.NotImplementedException::.ctor()
IL_0006: throw
} // end of method CTest::ITest.M1
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method CTest::.ctor
.event DTest E1
{
.addon instance void CTest::add_E1(class DTest)
.removeon instance void CTest::remove_E1(class DTest)
} // end of event CTest::ITest.E1
.property instance int32 P1()
{
.get instance int32 CTest::get_P1()
.set instance void CTest::set_P1(int32)
} // end of property CTest::ITest.P1
} // end of class CTest
";
var text = @"";
var comp = CreateCompilationWithILAndMscorlib40(text, il);
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface);
var cTest = comp.GetTypeByMetadataName("CTest");
var m1 = cTest.GetMember("M1");
Assert.Equal("M1", m1.Name);
Assert.Equal("M1", m1.ToDisplayString(format));
var p1 = cTest.GetMember("P1");
Assert.Equal("P1", p1.Name);
Assert.Equal("P1", p1.ToDisplayString(format));
var e1 = cTest.GetMember("E1");
Assert.Equal("E1", e1.Name);
Assert.Equal("E1", e1.ToDisplayString(format));
}
[WorkItem(6262, "https://github.com/dotnet/roslyn/issues/6262")]
[Fact]
public void FormattedSymbolEquality()
{
var source =
@"class A { }
class B { }
class C<T> { }";
var compilation = CreateCompilation(source);
var sA = compilation.GetMember<NamedTypeSymbol>("A");
var sB = compilation.GetMember<NamedTypeSymbol>("B");
var sC = compilation.GetMember<NamedTypeSymbol>("C");
var f1 = new SymbolDisplayFormat();
var f2 = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeParameters);
Assert.False(new FormattedSymbol(sA, f1).Equals((object)sA));
Assert.False(new FormattedSymbol(sA, f1).Equals(null));
Assert.True(new FormattedSymbol(sA, f1).Equals(new FormattedSymbol(sA, f1)));
Assert.False(new FormattedSymbol(sA, f1).Equals(new FormattedSymbol(sA, f2)));
Assert.False(new FormattedSymbol(sA, f1).Equals(new FormattedSymbol(sB, f1)));
Assert.False(new FormattedSymbol(sA, f1).Equals(new FormattedSymbol(sB, f2)));
Assert.False(new FormattedSymbol(sC, f1).Equals(new FormattedSymbol(sC.Construct(sA), f1)));
Assert.True(new FormattedSymbol(sC.Construct(sA), f1).Equals(new FormattedSymbol(sC.Construct(sA), f1)));
Assert.False(new FormattedSymbol(sA, new SymbolDisplayFormat()).Equals(new FormattedSymbol(sA, new SymbolDisplayFormat())));
Assert.True(new FormattedSymbol(sA, f1).GetHashCode().Equals(new FormattedSymbol(sA, f1).GetHashCode()));
}
[Fact, CompilerTrait(CompilerFeature.Tuples)]
public void Tuple()
{
var text = @"
public class C
{
public (int, string) f;
}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.
GetTypeMembers("C").Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular,
"(Int32, String) f",
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName, // Int32
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, // String
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, CompilerTrait(CompilerFeature.Tuples)]
public void TupleWith1Arity()
{
var text = @"
using System;
public class C
{
public ValueTuple<int> f;
}
" + TestResources.NetFX.ValueTuple.tuplelib_cs;
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.
GetTypeMembers("C").Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular,
"ValueTuple<Int32> f",
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[Fact, CompilerTrait(CompilerFeature.Tuples)]
public void TupleWithNames()
{
var text = @"
public class C
{
public (int x, string y) f;
}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.
GetTypeMembers("C").Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular,
"(Int32 x, String y) f",
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName, // Int32
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName, // x
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, // String
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName, // y
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[Fact, CompilerTrait(CompilerFeature.Tuples)]
public void LongTupleWithSpecialTypes()
{
var text = @"
public class C
{
public (int, string, bool, byte, long, ulong, short, ushort) f;
}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.
GetTypeMembers("C").Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular,
"(int, string, bool, byte, long, ulong, short, ushort) f",
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword, // int
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // string
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // bool
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // byte
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // long
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // ulong
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // short
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // ushort
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[Fact, CompilerTrait(CompilerFeature.Tuples)]
public void TupleProperty()
{
var text = @"
class C
{
(int Item1, string Item2) P { get; set; }
}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.
GetTypeMembers("C").Single().
GetMembers("P").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular,
"(int Item1, string Item2) P",
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword, // int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName, // Item1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // string
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName, // Item2
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName);
}
[Fact, CompilerTrait(CompilerFeature.Tuples)]
public void TupleQualifiedNames()
{
var text =
@"using NAB = N.A.B;
namespace N
{
class A
{
internal class B {}
}
class C<T>
{
// offset 1
}
}
class C
{
#pragma warning disable CS0169
(int One, N.C<(object[], NAB Two)>, int, object Four, int, object, int, object, N.A Nine) f;
#pragma warning restore CS0169
// offset 2
}";
var format = new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions: SymbolDisplayMemberOptions.IncludeType,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var comp = (Compilation)CreateCompilationWithMscorlib46(text, references: new[] { SystemRuntimeFacadeRef, ValueTupleRef });
comp.VerifyDiagnostics();
var symbol = comp.GetMember("C.f");
// Fully qualified format.
Verify(
SymbolDisplay.ToDisplayParts(symbol, format),
"(int One, global::N.C<(object[], global::N.A.B Two)>, int, object Four, int, object, int, object, global::N.A Nine) f");
// Minimally qualified format.
Verify(
SymbolDisplay.ToDisplayParts(symbol, SymbolDisplayFormat.MinimallyQualifiedFormat),
"(int One, C<(object[], B Two)>, int, object Four, int, object, int, object, A Nine) C.f");
// ToMinimalDisplayParts.
var model = comp.GetSemanticModel(comp.SyntaxTrees.First());
Verify(
SymbolDisplay.ToMinimalDisplayParts(symbol, model, text.IndexOf("offset 1"), format),
"(int One, C<(object[], NAB Two)>, int, object Four, int, object, int, object, A Nine) f");
Verify(
SymbolDisplay.ToMinimalDisplayParts(symbol, model, text.IndexOf("offset 2"), format),
"(int One, N.C<(object[], NAB Two)>, int, object Four, int, object, int, object, N.A Nine) f");
}
[Fact]
[WorkItem(23970, "https://github.com/dotnet/roslyn/pull/23970")]
public void ThisDisplayParts()
{
var text =
@"
class A
{
void M(int @this)
{
this.M(@this);
}
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single();
Assert.Equal("this.M(@this)", invocation.ToString());
var actualThis = ((MemberAccessExpressionSyntax)invocation.Expression).Expression;
Assert.Equal("this", actualThis.ToString());
Verify(
SymbolDisplay.ToDisplayParts(model.GetSymbolInfo(actualThis).Symbol, SymbolDisplayFormat.MinimallyQualifiedFormat),
"A this",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword);
var escapedThis = invocation.ArgumentList.Arguments[0].Expression;
Assert.Equal("@this", escapedThis.ToString());
Verify(
SymbolDisplay.ToDisplayParts(model.GetSymbolInfo(escapedThis).Symbol, SymbolDisplayFormat.MinimallyQualifiedFormat),
"int @this",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName);
}
[WorkItem(11356, "https://github.com/dotnet/roslyn/issues/11356")]
[Fact]
public void RefReturn()
{
var sourceA =
@"public delegate ref int D();
public class C
{
public ref int F(ref int i) => ref i;
int _p;
public ref int P => ref _p;
public ref int this[int i] => ref _p;
}";
var compA = CreateEmptyCompilation(sourceA, new[] { MscorlibRef });
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
// From C# symbols.
RefReturnInternal(compA);
var compB = CreateVisualBasicCompilation(GetUniqueName(), "", referencedAssemblies: new[] { MscorlibRef, refA });
compB.VerifyDiagnostics();
// From VB symbols.
RefReturnInternal(compB);
}
private static void RefReturnInternal(Compilation comp)
{
var formatBase = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut,
propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var formatWithoutRef = formatBase.WithMemberOptions(
SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType);
var formatWithRef = formatBase.WithMemberOptions(
SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef);
var formatWithoutTypeWithRef = formatBase.WithMemberOptions(
SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeRef);
var global = comp.GlobalNamespace;
var type = global.GetTypeMembers("C").Single();
var method = type.GetMembers("F").Single();
var property = type.GetMembers("P").Single();
var indexer = type.GetMembers().Where(m => m.Kind == SymbolKind.Property && ((IPropertySymbol)m).IsIndexer).Single();
var @delegate = global.GetTypeMembers("D").Single();
// Method without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutRef),
"int F(ref int)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
// Property without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(property, formatWithoutRef),
"int P { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Indexer without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(indexer, formatWithoutRef),
"int this[int] { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Delegate without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(@delegate, formatWithoutRef),
"int D()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
// Method with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithRef),
"ref int F(ref int)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
// Property with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(property, formatWithRef),
"ref int P { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Indexer with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(indexer, formatWithRef),
"ref int this[int] { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Delegate with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(@delegate, formatWithRef),
"ref int D()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
// Method without IncludeType, with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutTypeWithRef),
"F(ref int)",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public void RefReadonlyReturn()
{
var sourceA =
@"public delegate ref readonly int D();
public class C
{
public ref readonly int F(in int i) => ref i;
int _p;
public ref readonly int P => ref _p;
public ref readonly int this[in int i] => ref _p;
}";
var compA = CreateCompilation(sourceA);
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
// From C# symbols.
RefReadonlyReturnInternal(compA);
var compB = CreateVisualBasicCompilation(GetUniqueName(), "", referencedAssemblies: new[] { MscorlibRef, refA });
compB.VerifyDiagnostics();
// From VB symbols.
//RefReadonlyReturnInternal(compB);
}
[Fact]
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public void RefReadonlyReturn1()
{
var sourceA =
@"public delegate ref readonly int D();
public class C
{
public ref readonly int F(in int i) => ref i;
int _p;
public ref readonly int P => ref _p;
public ref readonly int this[in int i] => ref _p;
}";
var compA = CreateCompilation(sourceA);
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
// From C# symbols.
RefReadonlyReturnInternal(compA);
var compB = CreateVisualBasicCompilation(GetUniqueName(), "", referencedAssemblies: new[] { MscorlibRef, refA });
compB.VerifyDiagnostics();
// From VB symbols.
//RefReadonlyReturnInternal(compB);
}
private static void RefReadonlyReturnInternal(Compilation comp)
{
var formatBase = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut,
propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var formatWithoutRef = formatBase.WithMemberOptions(
SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType);
var formatWithRef = formatBase.WithMemberOptions(
SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef);
var formatWithoutTypeWithRef = formatBase.WithMemberOptions(
SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeRef);
var global = comp.GlobalNamespace;
var type = global.GetTypeMembers("C").Single();
var method = type.GetMembers("F").Single();
var property = type.GetMembers("P").Single();
var indexer = type.GetMembers().Where(m => m.Kind == SymbolKind.Property && ((IPropertySymbol)m).IsIndexer).Single();
var @delegate = global.GetTypeMembers("D").Single();
// Method without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutRef),
"int F(in int)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
// Property without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(property, formatWithoutRef),
"int P { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Indexer without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(indexer, formatWithoutRef),
"int this[in int] { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Delegate without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(@delegate, formatWithoutRef),
"int D()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
// Method with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithRef),
"ref readonly int F(in int)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
// Property with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(property, formatWithRef),
"ref readonly int P { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Indexer with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(indexer, formatWithRef),
"ref readonly int this[in int] { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Delegate with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(@delegate, formatWithRef),
"ref readonly int D()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
// Method without IncludeType, with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutTypeWithRef),
"F(in int)",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
}
[WorkItem(5002, "https://github.com/dotnet/roslyn/issues/5002")]
[Fact]
public void AliasInSpeculativeSemanticModel()
{
var text =
@"using A = N.M;
namespace N.M
{
class B
{
}
}
class C
{
static void M()
{
}
}";
var comp = CreateCompilation(text);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
int position = methodDecl.Body.SpanStart;
tree = CSharpSyntaxTree.ParseText(@"
class C
{
static void M()
{
}
}");
methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(position, methodDecl, out model));
var symbol = comp.GetMember<NamedTypeSymbol>("N.M.B");
position = methodDecl.Body.SpanStart;
var description = symbol.ToMinimalDisplayParts(model, position, SymbolDisplayFormat.MinimallyQualifiedFormat);
Verify(description, "A.B", SymbolDisplayPartKind.AliasName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName);
}
[Fact]
public void NullableReferenceTypes()
{
var source = @"
class A<T>
{
}
class B
{
static object F1(object? o) => null!;
static object?[] F2(object[]? o) => null;
static A<object>? F3(A<object?> o) => null;
}";
var comp = (Compilation)CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable());
var formatWithoutNonNullableModifier = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
var formatWithNonNullableModifier = formatWithoutNonNullableModifier
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier)
.WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None);
var method = comp.GetMember<IMethodSymbol>("B.F1");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutNonNullableModifier),
"static object F1(object? o)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithNonNullableModifier),
"static object! F1(object? o)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
method = comp.GetMember<IMethodSymbol>("B.F2");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutNonNullableModifier),
"static object?[] F2(object[]? o)");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithNonNullableModifier),
"static object?[]! F2(object![]? o)");
method = comp.GetMember<IMethodSymbol>("B.F3");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutNonNullableModifier),
"static A<object>? F3(A<object?> o)");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithNonNullableModifier),
"static A<object!>? F3(A<object?>! o)");
}
[Fact]
public void NullableReferenceTypes2()
{
var source =
@"class A<T>
{
}
class B
{
static object F1(object? o) => null!;
static object?[] F2(object[]? o) => null;
static A<object>? F3(A<object?> o) => null;
}";
var comp = (Compilation)CreateCompilation(source, parseOptions: TestOptions.Regular8);
var formatWithoutNullableModifier = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var formatWithNullableModifier = formatWithoutNullableModifier
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier)
.WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None);
var method = comp.GetMember<IMethodSymbol>("B.F1");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutNullableModifier),
"static object F1(object o)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithNullableModifier),
"static object F1(object? o)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
method = comp.GetMember<IMethodSymbol>("B.F2");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutNullableModifier),
"static object[] F2(object[] o)");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithNullableModifier),
"static object?[] F2(object[]? o)");
method = comp.GetMember<IMethodSymbol>("B.F3");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutNullableModifier),
"static A<object> F3(A<object> o)");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithNullableModifier),
"static A<object>? F3(A<object?> o)");
}
[WorkItem(31700, "https://github.com/dotnet/roslyn/issues/31700")]
[Fact]
public void NullableArrays()
{
var source =
@"#nullable enable
class C
{
static object?[,][] F1;
static object[,]?[] F2;
static object[,][]? F3;
}";
var comp = (Compilation)CreateCompilation(source, parseOptions: TestOptions.Regular8);
var formatWithoutModifiers = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var formatWithNullableModifier = formatWithoutModifiers.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
var formatWithBothModifiers = formatWithNullableModifier.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier);
var member = comp.GetMember("C.F1");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithoutModifiers),
"static object[,][] F1",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithNullableModifier),
"static object?[,][] F1",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithBothModifiers),
"static object?[]![,]! F1",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
member = comp.GetMember("C.F2");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithoutModifiers),
"static object[][,] F2");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithNullableModifier),
"static object[,]?[] F2");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithBothModifiers),
"static object![,]?[]! F2");
member = comp.GetMember("C.F3");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithoutModifiers),
"static object[,][] F3");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithNullableModifier),
"static object[,][]? F3");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithBothModifiers),
"static object![]![,]? F3");
}
[Fact]
public void AllowDefaultLiteral()
{
var source =
@"using System.Threading;
class C
{
void Method(CancellationToken cancellationToken = default(CancellationToken)) => throw null;
}
";
var compilation = (Compilation)CreateCompilation(source);
var formatWithoutAllowDefaultLiteral = SymbolDisplayFormat.MinimallyQualifiedFormat;
Assert.False(formatWithoutAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral));
var formatWithAllowDefaultLiteral = formatWithoutAllowDefaultLiteral.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral);
Assert.True(formatWithAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral));
var method = compilation.GetMember<IMethodSymbol>("C.Method");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutAllowDefaultLiteral),
"void C.Method(CancellationToken cancellationToken = default(CancellationToken))");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithAllowDefaultLiteral),
"void C.Method(CancellationToken cancellationToken = default)");
}
[Fact]
public void TypeParameterAnnotations_01()
{
var source =
@"#nullable enable
class C
{
T F0<T>() => default;
T? F1<T>() => default;
T F2<T>() where T : class => default;
T? F3<T>() where T : class => default;
T F4<T>() where T : class? => default;
T? F5<T>() where T : class? => default;
T F6<T>() where T : struct => default;
T? F7<T>() where T : struct => default;
T F8<T>() where T : notnull => default;
T F9<T>() where T : unmanaged => default;
}";
var comp = (Compilation)CreateCompilation(source, parseOptions: TestOptions.Regular8);
var formatWithoutModifiers = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var formatWithNullableModifier = formatWithoutModifiers.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
var formatWithBothModifiers = formatWithNullableModifier.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier);
verify("C.F0", "T F0<T>()", "T F0<T>()", "T F0<T>()");
verify("C.F1", "T F1<T>()", "T? F1<T>()", "T? F1<T>()");
verify("C.F2", "T F2<T>() where T : class", "T F2<T>() where T : class", "T! F2<T>() where T : class!");
verify("C.F3", "T F3<T>() where T : class", "T? F3<T>() where T : class", "T? F3<T>() where T : class!");
verify("C.F4", "T F4<T>() where T : class", "T F4<T>() where T : class?", "T F4<T>() where T : class?");
verify("C.F5", "T F5<T>() where T : class", "T? F5<T>() where T : class?", "T? F5<T>() where T : class?");
verify("C.F6", "T F6<T>() where T : struct", "T F6<T>() where T : struct", "T F6<T>() where T : struct");
verify("C.F7", "T? F7<T>() where T : struct", "T? F7<T>() where T : struct", "T? F7<T>() where T : struct");
verify("C.F8", "T F8<T>() where T : notnull", "T F8<T>() where T : notnull", "T F8<T>() where T : notnull");
verify("C.F9", "T F9<T>() where T : unmanaged", "T F9<T>() where T : unmanaged", "T F9<T>() where T : unmanaged");
void verify(string memberName, string withoutModifiers, string withNullableModifier, string withBothModifiers)
{
var member = comp.GetMember(memberName);
Verify(SymbolDisplay.ToDisplayParts(member, formatWithoutModifiers), withoutModifiers);
Verify(SymbolDisplay.ToDisplayParts(member, formatWithNullableModifier), withNullableModifier);
Verify(SymbolDisplay.ToDisplayParts(member, formatWithBothModifiers), withBothModifiers);
}
}
[Fact]
public void TypeParameterAnnotations_02()
{
var source =
@"#nullable enable
interface I<T> { }
class C
{
T? F<T>(T?[] x, I<T?> y) => default;
}";
var comp = (Compilation)CreateCompilation(source, parseOptions: TestOptions.Regular8);
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
var method = (IMethodSymbol)comp.GetMember("C.F");
Verify(
SymbolDisplay.ToDisplayParts(method, format),
"T? F<T>(T?[] x, I<T?> y)",
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.InterfaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
var type = method.GetSymbol<MethodSymbol>().ReturnTypeWithAnnotations;
Assert.Equal("T?", type.ToDisplayString(format));
}
[Theory]
[InlineData("int", "0")]
[InlineData("string", "null")]
public void AllowDefaultLiteralNotNeeded(string type, string defaultValue)
{
var source =
$@"
class C
{{
void Method1({type} parameter = {defaultValue}) => throw null;
void Method2({type} parameter = default({type})) => throw null;
void Method3({type} parameter = default) => throw null;
}}
";
var compilation = (Compilation)CreateCompilation(source);
var formatWithoutAllowDefaultLiteral = SymbolDisplayFormat.MinimallyQualifiedFormat;
Assert.False(formatWithoutAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral));
var formatWithAllowDefaultLiteral = formatWithoutAllowDefaultLiteral.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral);
Assert.True(formatWithAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral));
var method1 = compilation.GetMember<IMethodSymbol>("C.Method1");
Verify(
SymbolDisplay.ToDisplayParts(method1, formatWithoutAllowDefaultLiteral),
$"void C.Method1({type} parameter = {defaultValue})");
Verify(
SymbolDisplay.ToDisplayParts(method1, formatWithAllowDefaultLiteral),
$"void C.Method1({type} parameter = {defaultValue})");
var method2 = compilation.GetMember<IMethodSymbol>("C.Method2");
Verify(
SymbolDisplay.ToDisplayParts(method2, formatWithoutAllowDefaultLiteral),
$"void C.Method2({type} parameter = {defaultValue})");
Verify(
SymbolDisplay.ToDisplayParts(method2, formatWithAllowDefaultLiteral),
$"void C.Method2({type} parameter = {defaultValue})");
var method3 = compilation.GetMember<IMethodSymbol>("C.Method3");
Verify(
SymbolDisplay.ToDisplayParts(method3, formatWithoutAllowDefaultLiteral),
$"void C.Method3({type} parameter = {defaultValue})");
Verify(
SymbolDisplay.ToDisplayParts(method3, formatWithAllowDefaultLiteral),
$"void C.Method3({type} parameter = {defaultValue})");
}
[Theory]
[InlineData("int", "2")]
[InlineData("string", "\"value\"")]
public void AllowDefaultLiteralNotApplicable(string type, string defaultValue)
{
var source =
$@"
class C
{{
void Method({type} parameter = {defaultValue}) => throw null;
}}
";
var compilation = (Compilation)CreateCompilation(source);
var formatWithoutAllowDefaultLiteral = SymbolDisplayFormat.MinimallyQualifiedFormat;
Assert.False(formatWithoutAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral));
var formatWithAllowDefaultLiteral = formatWithoutAllowDefaultLiteral.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral);
Assert.True(formatWithAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral));
var method = compilation.GetMember<IMethodSymbol>("C.Method");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutAllowDefaultLiteral),
$"void C.Method({type} parameter = {defaultValue})");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithAllowDefaultLiteral),
$"void C.Method({type} parameter = {defaultValue})");
}
[Fact]
public void UseLongHandValueTuple()
{
var source =
@"
class B
{
static (int, (string, long)) F1((int, int)[] t) => throw null;
}";
var comp = (Compilation)CreateCompilation(source);
var formatWithoutLongHandValueTuple = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var formatWithLongHandValueTuple = formatWithoutLongHandValueTuple.WithCompilerInternalOptions(
SymbolDisplayCompilerInternalOptions.UseValueTuple);
var method = comp.GetMember<IMethodSymbol>("B.F1");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutLongHandValueTuple),
"static (int, (string, long)) F1((int, int)[] t)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithLongHandValueTuple),
"static ValueTuple<int, ValueTuple<string, long>> F1(ValueTuple<int, int>[] t)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public void LocalFunction()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
class C
{
void M()
{
void Local() {}
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilation(srcTree);
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var local = root.DescendantNodes()
.Where(n => n.Kind() == SyntaxKind.LocalFunctionStatement)
.Single();
var localSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(local);
Assert.Equal(MethodKind.LocalFunction, localSymbol.MethodKind);
Verify(localSymbol.ToDisplayParts(SymbolDisplayFormat.TestFormat),
"void Local()",
SymbolDisplayPartKind.Keyword, // void
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // Local
SymbolDisplayPartKind.Punctuation, // (
SymbolDisplayPartKind.Punctuation); // )
}
[Fact]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public void LocalFunctionForChangeSignature()
{
SymbolDisplayFormat changeSignatureFormat = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes,
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod,
memberOptions:
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeRef);
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
class C
{
void M()
{
void Local() {}
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilation(srcTree);
var semanticModel = comp.GetSemanticModel(srcTree);
var local = root.DescendantNodes()
.Where(n => n.Kind() == SyntaxKind.LocalFunctionStatement)
.Single();
var localSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(local);
Assert.Equal(MethodKind.LocalFunction, localSymbol.MethodKind);
Verify(localSymbol.ToDisplayParts(changeSignatureFormat),
"void Local",
SymbolDisplayPartKind.Keyword, // void
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName // Local
);
}
[Fact]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public void LocalFunction2()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
using System.Threading.Tasks;
class C
{
void M()
{
async unsafe Task<int> Local(ref int* x, out char? c)
{
}
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilationWithMscorlib45(new[] { srcTree });
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var local = root.DescendantNodes()
.Where(n => n.Kind() == SyntaxKind.LocalFunctionStatement)
.Single();
var localSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(local);
Assert.Equal(MethodKind.LocalFunction, localSymbol.MethodKind);
Verify(localSymbol.ToDisplayParts(SymbolDisplayFormat.TestFormat),
"System.Threading.Tasks.Task<System.Int32> Local(ref System.Int32* x, out System.Char? c)",
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.NamespaceName, // Threading
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.NamespaceName, // Tasks
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.ClassName, // Task
SymbolDisplayPartKind.Punctuation, // <
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.StructName, // Int32
SymbolDisplayPartKind.Punctuation, // >
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // Local
SymbolDisplayPartKind.Punctuation, // (
SymbolDisplayPartKind.Keyword, // ref
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.StructName, // Int32
SymbolDisplayPartKind.Punctuation, // *
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // x
SymbolDisplayPartKind.Punctuation, // ,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // out
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.StructName, // Char
SymbolDisplayPartKind.Punctuation, // ?
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // c
SymbolDisplayPartKind.Punctuation); // )
}
[Fact]
public void RangeVariable()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
using System.Linq;
class C
{
void M()
{
var q = from x in new[] { 1, 2, 3 } where x < 3 select x;
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilation(srcTree);
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var queryExpression = root.DescendantNodes().OfType<QueryExpressionSyntax>().First();
var fromClauseRangeVariableSymbol = (IRangeVariableSymbol)semanticModel.GetDeclaredSymbol(queryExpression.FromClause);
Verify(
fromClauseRangeVariableSymbol.ToMinimalDisplayParts(
semanticModel,
queryExpression.FromClause.Identifier.SpanStart,
SymbolDisplayFormat.MinimallyQualifiedFormat),
"int x",
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.RangeVariableName); // x
}
[Fact]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public void LocalFunction3()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
using System.Threading.Tasks;
class C
{
void M()
{
async unsafe Task<int> Local(in int* x, out char? c)
{
}
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilationWithMscorlib45(new[] { srcTree });
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var local = root.DescendantNodes()
.Where(n => n.Kind() == SyntaxKind.LocalFunctionStatement)
.Single();
var localSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(local);
Assert.Equal(MethodKind.LocalFunction, localSymbol.MethodKind);
Verify(localSymbol.ToDisplayParts(SymbolDisplayFormat.TestFormat),
"System.Threading.Tasks.Task<System.Int32> Local(in System.Int32* x, out System.Char? c)",
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.NamespaceName, // Threading
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.NamespaceName, // Tasks
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.ClassName, // Task
SymbolDisplayPartKind.Punctuation, // <
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.StructName, // Int32
SymbolDisplayPartKind.Punctuation, // >
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // Local
SymbolDisplayPartKind.Punctuation, // (
SymbolDisplayPartKind.Keyword, // in
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.StructName, // Int32
SymbolDisplayPartKind.Punctuation, // *
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // x
SymbolDisplayPartKind.Punctuation, // ,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // out
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.StructName, // Char
SymbolDisplayPartKind.Punctuation, // ?
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // c
SymbolDisplayPartKind.Punctuation); // )
}
[Fact]
public void LocalVariable_01()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
class C
{
void M()
{
int x = 0;
x++;
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilation(srcTree);
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declarator = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator);
Verify(
local.ToMinimalDisplayParts(
semanticModel,
declarator.SpanStart,
SymbolDisplayFormat.MinimallyQualifiedFormat.AddLocalOptions(SymbolDisplayLocalOptions.IncludeRef)),
"int x",
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.LocalName); // x
Assert.False(local.IsRef);
Assert.Equal(RefKind.None, local.RefKind);
}
[Fact]
public void LocalVariable_02()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
class C
{
void M(int y)
{
ref int x = y;
x++;
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilation(srcTree);
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declarator = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator);
Verify(
local.ToMinimalDisplayParts(
semanticModel,
declarator.SpanStart,
SymbolDisplayFormat.MinimallyQualifiedFormat.AddLocalOptions(SymbolDisplayLocalOptions.IncludeRef)),
"ref int x",
SymbolDisplayPartKind.Keyword, //ref
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.LocalName); // x
Verify(
local.ToMinimalDisplayParts(
semanticModel,
declarator.SpanStart,
SymbolDisplayFormat.MinimallyQualifiedFormat),
"int x",
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.LocalName); // x
Assert.True(local.IsRef);
Assert.Equal(RefKind.Ref, local.RefKind);
}
[Fact]
public void LocalVariable_03()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
class C
{
void M(int y)
{
ref readonly int x = y;
x++;
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilation(srcTree);
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declarator = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator);
Verify(
local.ToMinimalDisplayParts(
semanticModel,
declarator.SpanStart,
SymbolDisplayFormat.MinimallyQualifiedFormat.AddLocalOptions(SymbolDisplayLocalOptions.IncludeRef)),
"ref readonly int x",
SymbolDisplayPartKind.Keyword, //ref
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, //readonly
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.LocalName); // x
Verify(
local.ToMinimalDisplayParts(
semanticModel,
declarator.SpanStart,
SymbolDisplayFormat.MinimallyQualifiedFormat),
"int x",
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.LocalName); // x
Assert.True(local.IsRef);
Assert.Equal(RefKind.RefReadOnly, local.RefKind);
}
[Fact]
[WorkItem(22507, "https://github.com/dotnet/roslyn/issues/22507")]
public void EdgeCasesForEnumFieldComparer()
{
// A bad comparer could cause sorting the enum fields
// to throw an exception due to inconsistency. See Repro22507
// for an example of this problem.
var lhs = new EnumField("E1", 0);
var rhs = new EnumField("E2", 0x1000_0000_0000_0000);
// This is a "reverse" comparer, so if lhs < rhs, return
// value should be > 0
// If the comparer subtracts and converts, result will be zero since
// the bottom 32 bits are zero
Assert.InRange(EnumField.Comparer.Compare(lhs, rhs), 1, int.MaxValue);
lhs = new EnumField("E1", 0);
rhs = new EnumField("E2", 0x1000_0000_0000_0001);
Assert.InRange(EnumField.Comparer.Compare(lhs, rhs), 1, int.MaxValue);
lhs = new EnumField("E1", 0x1000_0000_0000_000);
rhs = new EnumField("E2", 0);
Assert.InRange(EnumField.Comparer.Compare(lhs, rhs), int.MinValue, -1);
lhs = new EnumField("E1", 0);
rhs = new EnumField("E2", 0x1000_0000_8000_0000);
Assert.InRange(EnumField.Comparer.Compare(lhs, rhs), 1, int.MaxValue);
}
[Fact]
[WorkItem(22507, "https://github.com/dotnet/roslyn/issues/22507")]
public void Repro22507()
{
var text = @"
using System;
[Flags]
enum E : long
{
A = 0x0,
B = 0x400,
C = 0x100000,
D = 0x200000,
E = 0x2000000,
F = 0x4000000,
G = 0x8000000,
H = 0x40000000,
I = 0x80000000,
J = 0x20000000000,
K = 0x40000000000,
L = 0x4000000000000,
M = 0x8000000000000,
N = 0x10000000000000,
O = 0x20000000000000,
P = 0x40000000000000,
Q = 0x2000000000000000,
}
";
TestSymbolDescription(
text,
g => g.GetTypeMembers("E").Single().GetField("A"),
SymbolDisplayFormat.MinimallyQualifiedFormat
.AddMemberOptions(SymbolDisplayMemberOptions.IncludeConstantValue),
"E.A = 0",
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NumericLiteral);
}
[Fact]
public void TestRefStructs()
{
var source = @"
ref struct X { }
namespace Nested
{
ref struct Y { }
}
";
var comp = CreateCompilation(source).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declarations = semanticModel.SyntaxTree.GetRoot().DescendantNodes().Where(n => n.Kind() == SyntaxKind.StructDeclaration).Cast<BaseTypeDeclarationSyntax>().ToArray();
Assert.Equal(2, declarations.Length);
var format = SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword);
Verify(semanticModel.GetDeclaredSymbol(declarations[0]).ToDisplayParts(format),
"ref struct X",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName);
Verify(semanticModel.GetDeclaredSymbol(declarations[1]).ToDisplayParts(format),
"ref struct Nested.Y",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName);
}
[Fact]
public void TestReadOnlyStructs()
{
var source = @"
readonly struct X { }
namespace Nested
{
readonly struct Y { }
}
";
var comp = CreateCompilation(source).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declarations = semanticModel.SyntaxTree.GetRoot().DescendantNodes().Where(n => n.Kind() == SyntaxKind.StructDeclaration).Cast<BaseTypeDeclarationSyntax>().ToArray();
Assert.Equal(2, declarations.Length);
var format = SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword);
Verify(semanticModel.GetDeclaredSymbol(declarations[0]).ToDisplayParts(format),
"readonly struct X",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName);
Verify(semanticModel.GetDeclaredSymbol(declarations[1]).ToDisplayParts(format),
"readonly struct Nested.Y",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName);
}
[Fact]
public void TestReadOnlyRefStructs()
{
var source = @"
readonly ref struct X { }
namespace Nested
{
readonly ref struct Y { }
}
";
var comp = CreateCompilation(source).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declarations = semanticModel.SyntaxTree.GetRoot().DescendantNodes().Where(n => n.Kind() == SyntaxKind.StructDeclaration).Cast<BaseTypeDeclarationSyntax>().ToArray();
Assert.Equal(2, declarations.Length);
var format = SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword);
Verify(semanticModel.GetDeclaredSymbol(declarations[0]).ToDisplayParts(format),
"readonly ref struct X",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName);
Verify(semanticModel.GetDeclaredSymbol(declarations[1]).ToDisplayParts(format),
"readonly ref struct Nested.Y",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName);
}
[Fact]
public void TestReadOnlyMembers_Malformed()
{
var source = @"
struct X
{
int P1 { }
readonly int P2 { }
readonly event System.Action E1 { }
readonly event System.Action E2 { remove { } }
}
";
var format = SymbolDisplayFormat.TestFormat
.AddMemberOptions(SymbolDisplayMemberOptions.IncludeModifiers)
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var comp = CreateCompilation(source).VerifyDiagnostics(
// (4,9): error CS0548: 'X.P1': property or indexer must have at least one accessor
// int P1 { }
Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "P1").WithArguments("X.P1").WithLocation(4, 9),
// (5,18): error CS0548: 'X.P2': property or indexer must have at least one accessor
// readonly int P2 { }
Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "P2").WithArguments("X.P2").WithLocation(5, 18),
// (6,34): error CS0065: 'X.E1': event property must have both add and remove accessors
// readonly event System.Action E1 { }
Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("X.E1").WithLocation(6, 34),
// (7,34): error CS0065: 'X.E2': event property must have both add and remove accessors
// readonly event System.Action E2 { remove { } }
Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E2").WithArguments("X.E2").WithLocation(7, 34));
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declaration = (BaseTypeDeclarationSyntax)semanticModel.SyntaxTree.GetRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.StructDeclaration);
var members = semanticModel.GetDeclaredSymbol(declaration).GetMembers();
Verify(members[0].ToDisplayParts(format), "int X.P1 { }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[1].ToDisplayParts(format), "int X.P2 { }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[2].ToDisplayParts(format), "event System.Action X.E1",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
Verify(members[3].ToDisplayParts(format), "readonly event System.Action X.E2",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
}
[Fact]
public void TestReadOnlyMembers()
{
var source = @"
struct X
{
readonly void M() { }
readonly int P1 { get => 123; }
readonly int P2 { set {} }
readonly int P3 { get => 123; set {} }
int P4 { readonly get => 123; set {} }
int P5 { get => 123; readonly set {} }
readonly event System.Action E { add {} remove {} }
}
";
var format = SymbolDisplayFormat.TestFormat
.AddMemberOptions(SymbolDisplayMemberOptions.IncludeModifiers)
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var comp = CreateCompilation(source).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declaration = (BaseTypeDeclarationSyntax)semanticModel.SyntaxTree.GetRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.StructDeclaration);
var members = semanticModel.GetDeclaredSymbol(declaration).GetMembers();
Verify(members[0].ToDisplayParts(format),
"readonly void X.M()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
Verify(members[1].ToDisplayParts(format),
"readonly int X.P1 { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[2].ToDisplayParts(format),
"readonly int X.P1.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[3].ToDisplayParts(format),
"readonly int X.P2 { set; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[4].ToDisplayParts(format),
"readonly void X.P2.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[5].ToDisplayParts(format),
"readonly int X.P3 { get; set; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[6].ToDisplayParts(format),
"readonly int X.P3.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[7].ToDisplayParts(format),
"readonly void X.P3.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[8].ToDisplayParts(format),
"int X.P4 { readonly get; set; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[9].ToDisplayParts(format),
"readonly int X.P4.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[10].ToDisplayParts(format),
"void X.P4.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[11].ToDisplayParts(format),
"int X.P5 { get; readonly set; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[12].ToDisplayParts(format),
"int X.P5.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[13].ToDisplayParts(format),
"readonly void X.P5.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[14].ToDisplayParts(format),
"readonly event System.Action X.E",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
Verify(members[15].ToDisplayParts(format),
"readonly void X.E.add",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[16].ToDisplayParts(format),
"readonly void X.E.remove",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[Fact]
public void TestReadOnlyStruct_Members()
{
var source = @"
readonly struct X
{
void M() { }
int P1 { get => 123; }
int P2 { set {} }
int P3 { get => 123; readonly set {} }
event System.Action E { add {} remove {} }
}
";
var format = SymbolDisplayFormat.TestFormat
.AddMemberOptions(SymbolDisplayMemberOptions.IncludeModifiers)
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var comp = CreateCompilation(source).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declaration = (BaseTypeDeclarationSyntax)semanticModel.SyntaxTree.GetRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.StructDeclaration);
var members = semanticModel.GetDeclaredSymbol(declaration).GetMembers();
Verify(members[0].ToDisplayParts(format),
"void X.M()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
Verify(members[1].ToDisplayParts(format),
"int X.P1 { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[2].ToDisplayParts(format),
"int X.P1.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[3].ToDisplayParts(format),
"int X.P2 { set; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[4].ToDisplayParts(format),
"void X.P2.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[5].ToDisplayParts(format),
"int X.P3 { get; set; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[6].ToDisplayParts(format),
"int X.P3.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[7].ToDisplayParts(format),
"void X.P3.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[8].ToDisplayParts(format),
"event System.Action X.E",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
Verify(members[9].ToDisplayParts(format),
"void X.E.add",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[10].ToDisplayParts(format),
"void X.E.remove",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[Theory, MemberData(nameof(FileScopedOrBracedNamespace))]
public void TestReadOnlyStruct_Nested(string ob, string cb)
{
var source = @"
namespace Nested
" + ob + @"
struct X
{
readonly void M() { }
}
" + cb + @"
";
var format = SymbolDisplayFormat.TestFormat
.AddMemberOptions(SymbolDisplayMemberOptions.IncludeModifiers)
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithFileScopedNamespaces).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declaration = (BaseTypeDeclarationSyntax)semanticModel.SyntaxTree.GetRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.StructDeclaration);
var members = semanticModel.GetDeclaredSymbol(declaration).GetMembers();
Verify(members[0].ToDisplayParts(format),
"readonly void Nested.X.M()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestPassingVBSymbolsToStructSymbolDisplay()
{
var source = @"
Structure X
End Structure";
var comp = CreateVisualBasicCompilation(source).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var structure = semanticModel.SyntaxTree.GetRoot().DescendantNodes().Single(n => n.RawKind == (int)VisualBasic.SyntaxKind.StructureStatement);
var format = SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword);
Verify(SymbolDisplay.ToDisplayParts(semanticModel.GetDeclaredSymbol(structure), format),
"struct X",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName);
}
[Fact]
public void EnumConstraint_Type()
{
TestSymbolDescription(
"class X<T> where T : System.Enum { }",
global => global.GetTypeMember("X"),
SymbolDisplayFormat.TestFormat.WithGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints),
"X<T> where T : System.Enum",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void EnumConstraint()
{
TestSymbolDescription(
"class X<T> where T : System.Enum { }",
global => global.GetTypeMember("X").TypeParameters.Single().ConstraintTypes().Single(),
SymbolDisplayFormat.TestFormat,
"System.Enum",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void DelegateConstraint_Type()
{
TestSymbolDescription(
"class X<T> where T : System.Delegate { }",
global => global.GetTypeMember("X"),
SymbolDisplayFormat.TestFormat.WithGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints),
"X<T> where T : System.Delegate",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void DelegateConstraint()
{
TestSymbolDescription(
"class X<T> where T : System.Delegate { }",
global => global.GetTypeMember("X").TypeParameters.Single().ConstraintTypes().Single(),
SymbolDisplayFormat.TestFormat,
"System.Delegate",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void MulticastDelegateConstraint_Type()
{
TestSymbolDescription(
"class X<T> where T : System.MulticastDelegate { }",
global => global.GetTypeMember("X"),
SymbolDisplayFormat.TestFormat.WithGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints),
"X<T> where T : System.MulticastDelegate",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void MulticastDelegateConstraint()
{
TestSymbolDescription(
"class X<T> where T : System.MulticastDelegate { }",
global => global.GetTypeMember("X").TypeParameters.Single().ConstraintTypes().Single(),
SymbolDisplayFormat.TestFormat,
"System.MulticastDelegate",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void UnmanagedConstraint_Type()
{
TestSymbolDescription(
"class X<T> where T : unmanaged { }",
global => global.GetTypeMember("X"),
SymbolDisplayFormat.TestFormat.AddGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeConstraints),
"X<T> where T : unmanaged",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword);
}
[Fact]
public void UnmanagedConstraint_Method()
{
TestSymbolDescription(@"
class X
{
void M<T>() where T : unmanaged, System.IDisposable { }
}",
global => global.GetTypeMember("X").GetMethod("M"),
SymbolDisplayFormat.TestFormat.AddGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeConstraints),
"void X.M<T>() where T : unmanaged, System.IDisposable",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.InterfaceName);
}
[Fact]
public void UnmanagedConstraint_Delegate()
{
TestSymbolDescription(
"delegate void D<T>() where T : unmanaged;",
global => global.GetTypeMember("D"),
SymbolDisplayFormat.TestFormat.AddGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeConstraints),
"D<T> where T : unmanaged",
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword);
}
[Fact, WorkItem(27104, "https://github.com/dotnet/roslyn/issues/27104")]
public void BadDiscardInForeachLoop_01()
{
var source = @"
class C
{
void M()
{
foreach(_ in """")
{
}
}
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,17): error CS8186: A foreach loop must declare its iteration variables.
// foreach(_ in "")
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "_").WithLocation(6, 17)
);
var tree = compilation.SyntaxTrees[0];
var variable = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single().Variable;
var model = compilation.GetSemanticModel(tree);
var symbol = model.GetSymbolInfo(variable).Symbol;
Verify(
symbol.ToMinimalDisplayParts(model, variable.SpanStart),
"var _",
SymbolDisplayPartKind.ErrorTypeName, // var
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation); // _
}
[Fact]
public void ClassConstructorDeclaration()
{
TestSymbolDescription(
@"class C
{
C() { }
}",
global => global.GetTypeMember("C").Constructors[0],
new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType),
"C.C",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void ClassDestructorDeclaration()
{
TestSymbolDescription(
@"class C
{
~C() { }
}",
global => global.GetTypeMember("C").GetMember("Finalize"),
new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType),
"C.~C",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void ClassStaticConstructorDeclaration()
{
TestSymbolDescription(
@"class C
{
static C() { }
}",
global => global.GetTypeMember("C").Constructors[0],
new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType),
"C.C",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void ClassStaticDestructorDeclaration()
{
TestSymbolDescription(
@"class C
{
static ~C() { }
}",
global => global.GetTypeMember("C").GetMember("Finalize"),
new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType),
"C.~C",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void ClassConstructorInvocation()
{
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType);
var source =
@"class C
{
C()
{
var c = new C();
}
}";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var constructor = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
var symbol = model.GetSymbolInfo(constructor).Symbol;
Verify(
symbol.ToMinimalDisplayParts(model, constructor.SpanStart, format),
"C.C",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void StructConstructorDeclaration()
{
TestSymbolDescription(
@"struct S
{
int i;
S(int i)
{
this.i = i;
}
}",
global => global.GetTypeMember("S").Constructors[0],
new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType),
"S.S",
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName);
}
[Fact]
public void StructConstructorInvocation()
{
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType);
var source =
@"struct S
{
int i;
public S(int i)
{
this.i = i;
}
}
class C
{
C()
{
var s = new S(1);
}
}";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var constructor = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
var symbol = model.GetSymbolInfo(constructor).Symbol;
Verify(
symbol.ToMinimalDisplayParts(model, constructor.SpanStart, format),
"S.S",
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName);
}
[Fact]
[WorkItem(38794, "https://github.com/dotnet/roslyn/issues/38794")]
public void LinqGroupVariableDeclaration()
{
var source =
@"using System.Linq;
class C
{
void M(string[] a)
{
var v = from x in a
group x by x.Length into g
select g;
}
}";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var continuation = tree.GetRoot().DescendantNodes().OfType<QueryContinuationSyntax>().Single();
var symbol = model.GetDeclaredSymbol(continuation);
Verify(
symbol.ToMinimalDisplayParts(model, continuation.Identifier.SpanStart),
"IGrouping<int, string> g",
SymbolDisplayPartKind.InterfaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.RangeVariableName);
}
[Fact]
public void NativeInt()
{
var source =
@"using System;
class A<T>
{
}
class B
{
static void F1(nint x, nuint y) { }
static void F2(nint x, IntPtr y) { }
static void F3(nint? x, UIntPtr? y) { }
static void F4(nint[] x, A<nuint> y) { }
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular9);
var formatWithoutOptions = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
var formatWithUnderlyingTypes = formatWithoutOptions.WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.UseNativeIntegerUnderlyingType);
var method = comp.GetMember<MethodSymbol>("B.F1");
Verify(
method.ToDisplayParts(formatWithUnderlyingTypes),
"static void F1(IntPtr x, UIntPtr y)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(
method.ToDisplayParts(formatWithoutOptions),
"static void F1(nint x, nuint y)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(
method.ToDisplayParts(formatWithoutOptions.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes)),
"static void F1(nint x, nuint y)");
method = comp.GetMember<MethodSymbol>("B.F2");
Verify(
method.ToDisplayParts(formatWithUnderlyingTypes),
"static void F2(IntPtr x, IntPtr y)");
Verify(
method.ToDisplayParts(formatWithoutOptions),
"static void F2(nint x, IntPtr y)");
method = comp.GetMember<MethodSymbol>("B.F3");
Verify(
method.ToDisplayParts(formatWithUnderlyingTypes),
"static void F3(IntPtr? x, UIntPtr? y)");
Verify(
method.ToDisplayParts(formatWithoutOptions),
"static void F3(nint? x, UIntPtr? y)");
method = comp.GetMember<MethodSymbol>("B.F4");
Verify(
method.ToDisplayParts(formatWithUnderlyingTypes),
"static void F4(IntPtr[] x, A<UIntPtr> y)");
Verify(
method.ToDisplayParts(formatWithoutOptions),
"static void F4(nint[] x, A<nuint> y)");
}
[Fact]
public void RecordDeclaration()
{
var text = @"
record Person(string First, string Last);
";
Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("Person").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType, kindOptions: SymbolDisplayKindOptions.IncludeTypeKeyword);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
"record Person",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.RecordClassName);
}
[Fact]
public void RecordClassDeclaration()
{
var text = @"
record class Person(string First, string Last);
";
Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("Person").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType, kindOptions: SymbolDisplayKindOptions.IncludeTypeKeyword);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
"record Person",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.RecordClassName);
}
[Fact]
public void RecordStructDeclaration()
{
var text = @"
record struct Person(string First, string Last);
";
Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("Person").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType, kindOptions: SymbolDisplayKindOptions.IncludeTypeKeyword);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular10,
"record struct Person",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.RecordStructName);
}
[Fact]
public void ReadOnlyRecordStructDeclaration()
{
var text = @"
readonly record struct Person(string First, string Last);
";
Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("Person").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType, kindOptions: SymbolDisplayKindOptions.IncludeTypeKeyword);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular10,
"readonly record struct Person",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.RecordStructName);
}
[Fact, WorkItem(51222, "https://github.com/dotnet/roslyn/issues/51222")]
public void TestFunctionPointerWithoutIncludeTypesInParameterOptions()
{
var text = @"
class A {
delegate*<int, string> f;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
((FieldSymbol)global.GetTypeMembers("A", 0).Single()
.GetMembers("f").Single()).Type;
var format = new SymbolDisplayFormat();
TestSymbolDescription(
text,
findSymbol,
format,
"delegate*<Int32, String>");
}
[Fact, WorkItem(51222, "https://github.com/dotnet/roslyn/issues/51222")]
public void TestFunctionPointerWithTupleParameter()
{
var text = @"
class A {
delegate*<(int, string), void> f;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
((FieldSymbol)global.GetTypeMembers("A", 0).Single()
.GetMembers("f").Single()).Type;
var format = new SymbolDisplayFormat();
TestSymbolDescription(
text,
findSymbol,
format,
"delegate*<(Int32, String), Void>");
}
[Fact, WorkItem(51222, "https://github.com/dotnet/roslyn/issues/51222")]
public void TestFunctionPointerWithTupleParameterWithNames()
{
var text = @"
class A {
delegate*<(int i, string s), (int i, string s)> f;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
((FieldSymbol)global.GetTypeMembers("A", 0).Single()
.GetMembers("f").Single()).Type;
var format = new SymbolDisplayFormat();
TestSymbolDescription(
text,
findSymbol,
format,
"delegate*<(Int32 i, String s), (Int32 i, String s)>");
}
[Fact, WorkItem(51222, "https://github.com/dotnet/roslyn/issues/51222")]
public void TestFunctionPointerWithRefParameters()
{
var text = @"
class A {
delegate*<in int, ref readonly string> f;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
((FieldSymbol)global.GetTypeMembers("A", 0).Single()
.GetMembers("f").Single()).Type;
var format = new SymbolDisplayFormat();
TestSymbolDescription(
text,
findSymbol,
format,
"delegate*<in Int32, ref readonly String>");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Globalization;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class SymbolDisplayTests : CSharpTestBase
{
[Fact]
public void TestClassNameOnlySimple()
{
var text = "class A {}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("A", 0).Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly);
TestSymbolDescription(
text,
findSymbol,
format,
"A",
SymbolDisplayPartKind.ClassName);
}
[Fact, WorkItem(46985, "https://github.com/dotnet/roslyn/issues/46985")]
public void TestRecordNameOnlySimple()
{
var text = "record A {}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("A", 0).Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly);
TestSymbolDescription(
text,
findSymbol,
format,
"A",
SymbolDisplayPartKind.RecordClassName);
}
[Fact, WorkItem(46985, "https://github.com/dotnet/roslyn/issues/46985")]
public void TestRecordNameOnlyComplex()
{
var text = @"
namespace N1 {
namespace N2.N3 {
record R1 {
record R2 {} } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("R1").Single().
GetTypeMembers("R2").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly);
TestSymbolDescription(
text,
findSymbol,
format,
"R2",
SymbolDisplayPartKind.RecordClassName);
}
[Fact]
public void TestClassNameOnlyComplex()
{
var text = @"
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {} } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly);
TestSymbolDescription(
text,
findSymbol,
format,
"C2",
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestFullyQualifiedFormat()
{
var text = @"
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {} } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single();
TestSymbolDescription(
text,
findSymbol,
SymbolDisplayFormat.FullyQualifiedFormat,
"global::N1.N2.N3.C1.C2",
SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestClassNameAndContainingTypesSimple()
{
var text = "class A {}";
Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("A", 0).Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"A",
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestClassNameAndContainingTypesComplex()
{
var text = @"
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {} } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"C1.C2",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestMethodNameOnlySimple()
{
var text = @"
class A {
void M() {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("A", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat();
TestSymbolDescription(
text,
findSymbol,
format,
"M",
SymbolDisplayPartKind.MethodName);
}
[Fact]
public void TestMethodNameOnlyComplex()
{
var text = @"
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {
public static int[] M(int? x, C1 c) {} } } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat();
TestSymbolDescription(
text,
findSymbol,
format,
"M",
SymbolDisplayPartKind.MethodName);
}
[Fact]
public void TestMethodAndParamsSimple()
{
var text = @"
class A {
void M() {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("A", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"private void M()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestMethodAndParamsComplex()
{
var text = @"
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {
public static int[] M(int? x, C1 c) {} } } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public static int[] M(int? x, C1 c)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //x
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //c
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestExtensionMethodAsStatic()
{
var text = @"
class C1<T> { }
class C2 {
public static TSource M<TSource>(this C1<TSource> source, int index) {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C2").Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public static TSource C2.M<TSource>(this C1<TSource> source, int index)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C2
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //source
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //index
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestExtensionMethodAsInstance()
{
var text = @"
class C1<T> { }
class C2 {
public static TSource M<TSource>(this C1<TSource> source, int index) {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C2").Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.InstanceMethod,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public TSource C1<TSource>.M<TSource>(int index)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ExtensionMethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //index
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestExtensionMethodAsDefault()
{
var text = @"
class C1<T> { }
class C2 {
public static TSource M<TSource>(this C1<TSource> source, int index) {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C2").Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.Default,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public static TSource C2.M<TSource>(this C1<TSource> source, int index)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C2
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //source
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //index
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestReducedExtensionMethodAsStatic()
{
var text = @"
class C1 { }
class C2 {
public static TSource M<TSource>(this C1 source, int index) {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
{
var type = global.GetTypeMember("C1");
var method = (MethodSymbol)global.GetTypeMember("C2").GetMember("M");
return method.ReduceExtensionMethod(type, null!);
};
var format = new SymbolDisplayFormat(
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public static TSource C2.M<TSource>(this C1 source, int index)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C2
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //source
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //index
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestReducedExtensionMethodAsInstance()
{
var text = @"
class C1 { }
class C2 {
public static TSource M<TSource>(this C1 source, int index) {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
{
var type = global.GetTypeMember("C1");
var method = (MethodSymbol)global.GetTypeMember("C2").GetMember("M");
return method.ReduceExtensionMethod(type, null!);
};
var format = new SymbolDisplayFormat(
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.InstanceMethod,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public TSource C1.M<TSource>(int index)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ExtensionMethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //index
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestReducedExtensionMethodAsDefault()
{
var text = @"
class C1 { }
class C2 {
public static TSource M<TSource>(this C1 source, int index) {} }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
{
var type = global.GetTypeMember("C1");
var method = (MethodSymbol)global.GetTypeMember("C2").GetMember("M");
return method.ReduceExtensionMethod(type, null!);
};
var format = new SymbolDisplayFormat(
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.Default,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"public TSource C1.M<TSource>(int index)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ExtensionMethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName, //TSource
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //index
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestPrivateProtected()
{
var text = @"class C2 { private protected void M() {} }";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C2").Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType);
TestSymbolDescription(
text,
findSymbol,
format,
"private protected void C2.M()",
SymbolDisplayPartKind.Keyword, // private
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // protected
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // void
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, //C2
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestNullParameters()
{
var text = @"
class A {
int[][,][,,] f; }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("A", 0).Single().
GetMembers("f").Single();
SymbolDisplayFormat format = null;
TestSymbolDescription(
text,
findSymbol,
format,
"A.f",
SymbolDisplayPartKind.ClassName, //A
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.FieldName); //f
}
[Fact]
public void TestArrayRank()
{
var text = @"
class A {
int[][,][,,] f; }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("A", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"int[][,][,,] f",
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Punctuation, //[
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation, //[
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation, //[
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName); //f
}
[Fact]
public void TestOptionalParameters_Bool()
{
var text = @"
using System.Runtime.InteropServices;
class C
{
void F([Optional]bool arg) { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"void F(bool arg)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // arg
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameters_String()
{
var text = @"
class C
{
void F(string s = ""f\t\r\noo"") { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
@"void F(string s = ""f\t\r\noo"")",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // s
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, // =
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StringLiteral,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameters_ReferenceType()
{
var text = @"
using System.Runtime.InteropServices;
class C
{
void F([Optional]C arg) { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"void F(C arg)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // arg
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameters_Constrained_Class()
{
var text = @"
using System.Runtime.InteropServices;
class C
{
void F<T>([Optional]T arg) where T : class { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"void F(T arg)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // arg
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameters_Constrained_Struct()
{
var text = @"
using System.Runtime.InteropServices;
class C
{
void F<T>([Optional]T arg) where T : struct { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"void F(T arg)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // arg
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameters_Unconstrained()
{
var text = @"
using System.Runtime.InteropServices;
class C
{
void F<T>([Optional]T arg) { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"void F(T arg)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // arg
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameters_ArrayAndType()
{
var text = @"
using System.Runtime.InteropServices;
class C
{
void F<T>(int a, [Optional]double[] arg, int b, [Optional]System.Type t) { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("F").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"void F(int a, double[] arg, int b, Type t)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // F
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword, // int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // a
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // double
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // arg
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // b
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, // Type
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // t
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestEscapeKeywordIdentifiers()
{
var text = @"
class @true {
@true @false(@true @true, bool @bool = true) { return @true; } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("true", 0).Single().
GetMembers("false").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"@true @false(@true @true, bool @bool = true)",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, //@false
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //@true
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //@bool
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestNoEscapeKeywordIdentifiers()
{
var text = @"
class @true {
@true @false(@true @true, bool @bool = true) { return @true; } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("true", 0).Single().
GetMembers("false").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"true false(true true, bool bool = true)",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // @false
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // @true
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // @bool
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestExplicitMethodImplNameOnly()
{
var text = @"
interface I {
void M(); }
class C : I {
void I.M() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("I.M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.None);
TestSymbolDescription(
text,
findSymbol,
format,
"M",
SymbolDisplayPartKind.MethodName); //M
}
[Fact]
public void TestExplicitMethodImplNameAndInterface()
{
var text = @"
interface I {
void M(); }
class C : I {
void I.M() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("I.M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface);
TestSymbolDescription(
text,
findSymbol,
format,
"I.M",
SymbolDisplayPartKind.InterfaceName, //I
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName); //M
}
[Fact]
public void TestExplicitMethodImplNameAndInterfaceAndType()
{
var text = @"
interface I {
void M(); }
class C : I {
void I.M() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("I.M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType);
TestSymbolDescription(
text,
findSymbol,
format,
"C.I.M",
SymbolDisplayPartKind.ClassName, //C
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.InterfaceName, //I
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName); //M
}
[Fact]
public void TestGlobalNamespaceCode()
{
var text = @"
class C { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included);
TestSymbolDescription(
text,
findSymbol,
format,
"global::C",
SymbolDisplayPartKind.Keyword, //global
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName); //C
}
[Fact]
public void TestGlobalNamespaceHumanReadable()
{
var text = @"
class C { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global;
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included);
TestSymbolDescription(
text,
findSymbol,
format,
"<global namespace>",
SymbolDisplayPartKind.Text);
}
[Fact]
public void TestSpecialTypes()
{
var text = @"
class C {
int f; }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"int f",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[Fact]
public void TestArrayAsterisks()
{
var text = @"
class C {
int[][,][,,] f; }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays);
TestSymbolDescription(
text,
findSymbol,
format,
"Int32[][*,*][*,*,*] f",
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[Fact]
public void TestMetadataMethodNames()
{
var text = @"
class C {
C() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers(".ctor").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames);
TestSymbolDescription(
text,
findSymbol,
format,
".ctor",
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestArityForGenericTypes()
{
var text = @"
class C<T, U, V> { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 3).Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"C`3",
SymbolDisplayPartKind.ClassName,
InternalSymbolDisplayPartKind.Arity);
}
[Fact]
public void TestGenericTypeParameters()
{
var text = @"
class C<in T, out U, V> { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 3).Single();
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
TestSymbolDescription(
text,
findSymbol,
format,
"C<T, U, V>",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestGenericTypeParametersAndVariance()
{
var text = @"
class C<in T, out U, V> { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 3).Single();
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance);
TestSymbolDescription(
text,
findSymbol,
format,
"C<in T, out U, V>",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestGenericTypeConstraints()
{
var text = @"
class C<T> where T : C<T> { }
";
Func<NamespaceSymbol, Symbol> findType = global =>
global.GetMember<NamedTypeSymbol>("C");
Func<NamespaceSymbol, Symbol> findTypeParameter = global =>
global.GetMember<NamedTypeSymbol>("C").TypeParameters.Single();
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints);
TestSymbolDescription(text, findType,
format,
"C<T> where T : C<T>",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation);
TestSymbolDescription(text, findTypeParameter,
format,
"T",
SymbolDisplayPartKind.TypeParameterName);
}
[Fact]
public void TestGenericMethodParameters()
{
var text = @"
class C {
void M<in T, out U, V>() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
TestSymbolDescription(
text,
findSymbol,
format,
"M<T, U, V>",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestGenericMethodParametersAndVariance()
{
var text = @"
class C {
void M<in T, out U, V>() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance);
TestSymbolDescription(
text,
findSymbol,
format,
"M<T, U, V>",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestGenericMethodConstraints()
{
var text = @"
class C<T>
{
void M<U, V>() where V : class, U, T {}
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M");
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints);
TestSymbolDescription(
text,
findSymbol,
format,
"M<U, V> where V : class, U, T",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName);
}
[Fact]
public void TestMemberMethodNone()
{
var text = @"
class C {
void M(int p) { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.None);
TestSymbolDescription(
text,
findSymbol,
format,
"M",
SymbolDisplayPartKind.MethodName);
}
[Fact]
public void TestMemberMethodAll()
{
var text = @"
class C {
void M(int p) { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private void C.M()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestMemberFieldNone()
{
var text = @"
class C {
int f; }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.None);
TestSymbolDescription(
text,
findSymbol,
format,
"f",
SymbolDisplayPartKind.FieldName);
}
[Fact]
public void TestMemberFieldAll()
{
var text =
@"class C {
int f;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private Int32 C.f",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.FieldName);
}
[Fact]
public void TestMemberPropertyNone()
{
var text = @"
class C {
int P { get; } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("P").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.None);
TestSymbolDescription(
text,
findSymbol,
format,
"P",
SymbolDisplayPartKind.PropertyName);
}
[Fact]
public void TestMemberPropertyAll()
{
var text = @"
class C {
int P { get; } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("P").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private Int32 C.P",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName);
}
[Fact]
public void TestMemberPropertyGetSet()
{
var text = @"
class C
{
int P { get; }
object Q { set; }
object R { get { return null; } set { } }
}
";
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor);
TestSymbolDescription(
text,
global => global.GetTypeMembers("C", 0).Single().GetMembers("P").Single(),
format,
"Int32 P { get; }",
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
TestSymbolDescription(
text,
global => global.GetTypeMembers("C", 0).Single().GetMembers("Q").Single(),
format,
"Object Q { set; }",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
TestSymbolDescription(
text,
global => global.GetTypeMembers("C", 0).Single().GetMembers("R").Single(),
format,
"Object R { get; set; }",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestPropertyGetAccessor()
{
var text = @"
class C {
int P { get; set; } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("get_P").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private Int32 C.P.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[Fact]
public void TestPropertySetAccessor()
{
var text = @"
class C {
int P { get; set; } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("set_P").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private void C.P.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[Fact]
public void TestMemberEventAll()
{
var text = @"
class C {
event System.Action E;
event System.Action F { add { } remove { } } }
";
Func<NamespaceSymbol, Symbol> findSymbol1 = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMembers("E").Where(m => m.Kind == SymbolKind.Event).Single();
Func<NamespaceSymbol, Symbol> findSymbol2 = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMember<EventSymbol>("F");
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol1,
format,
"private Action C.E",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
TestSymbolDescription(
text,
findSymbol2,
format,
"private Action C.F",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
}
[Fact]
public void TestMemberEventAddRemove()
{
var text = @"
class C {
event System.Action E;
event System.Action F { add { } remove { } } }
";
Func<NamespaceSymbol, Symbol> findSymbol1 = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMembers("E").Where(m => m.Kind == SymbolKind.Event).Single();
Func<NamespaceSymbol, Symbol> findSymbol2 = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMember<EventSymbol>("F");
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType,
propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor); // Does not affect events (did before rename).
TestSymbolDescription(
text,
findSymbol1,
format,
"Action E",
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EventName);
TestSymbolDescription(
text,
findSymbol2,
format,
"Action F",
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EventName);
}
[Fact]
public void TestEventAddAccessor()
{
var text = @"
class C {
event System.Action E { add { } remove { } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMembers("add_E").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private void C.E.add",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[Fact]
public void TestEventRemoveAccessor()
{
var text = @"
class C {
event System.Action E { add { } remove { } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMembers("remove_E").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"private void C.E.remove",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[Fact]
public void TestParameterMethodNone()
{
var text = @"
static class C {
static void M(this object obj, ref short s, int i = 1) { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.None);
TestSymbolDescription(
text,
findSymbol,
format,
"M()",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestMethodReturnType1()
{
var text = @"
static class C {
static int M() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"System.Int32 M()",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestMethodReturnType2()
{
var text = @"
static class C {
static void M() { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
"void M()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestParameterMethodNameTypeModifiers()
{
var text = @"
class C {
void M(ref short s, int i, params string[] args) { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions:
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName);
TestSymbolDescription(
text,
findSymbol,
format,
"M(ref Int16 s, Int32 i, params String[] args)",
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //s
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //i
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //args
SymbolDisplayPartKind.Punctuation);
// Without SymbolDisplayParameterOptions.IncludeParamsRefOut.
TestSymbolDescription(
text,
findSymbol,
format.WithParameterOptions(SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName),
"M(Int16 s, Int32 i, String[] args)",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
// Without SymbolDisplayParameterOptions.IncludeType, drops
// ref/out/params modifiers. (VB retains ByRef/ParamArray.)
TestSymbolDescription(
text,
findSymbol,
format.WithParameterOptions(SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeName),
"M(s, i, args)",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact()]
public void TestParameterMethodNameAll()
{
var text = @"
static class C {
static void M(this object self, ref short s, int i = 1, params string[] args) { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions:
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue);
TestSymbolDescription(
text,
findSymbol,
format,
"M(this Object self, ref Int16 s, Int32 i = 1, params String[] args)",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //self
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //s
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //i
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NumericLiteral,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //args
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestOptionalParameterBrackets()
{
var text = @"
class C {
void M(int i = 0) { } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("M").Single();
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions:
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeOptionalBrackets);
TestSymbolDescription(
text,
findSymbol,
format,
"M([Int32 i])",
SymbolDisplayPartKind.MethodName, //M
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, //i
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
/// <summary>
/// "public" and "abstract" should not be included for interface members.
/// </summary>
[Fact]
public void TestInterfaceMembers()
{
var text = @"
interface I
{
int P { get; }
object F();
}
abstract class C
{
public abstract object F();
interface I
{
void M();
}
}";
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType,
propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
global => global.GetTypeMembers("I", 0).Single().GetMembers("P").Single(),
format,
"int P { get; }");
TestSymbolDescription(
text,
global => global.GetTypeMembers("I", 0).Single().GetMembers("F").Single(),
format,
"object F()");
TestSymbolDescription(
text,
global => global.GetTypeMembers("C", 0).Single().GetMembers("F").Single(),
format,
"public abstract object F()");
TestSymbolDescription(
text,
global => global.GetTypeMembers("C", 0).Single().GetTypeMembers("I", 0).Single().GetMembers("M").Single(),
format,
"void M()");
}
[WorkItem(537447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537447")]
[Fact]
public void TestBug2239()
{
var text = @"
public class GC1<T> {}
public class X : GC1<BOGUS> {}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("X", 0).Single().
BaseType();
var format = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
TestSymbolDescription(
text,
findSymbol,
format,
"GC1<BOGUS>",
SymbolDisplayPartKind.ClassName, //GC1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ErrorTypeName, //BOGUS
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestAlias1()
{
var text = @"
using Goo = N1.N2.N3;
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {} } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces);
TestSymbolDescription(
text,
findSymbol,
format,
"Goo.C1.C2",
text.IndexOf("namespace", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.AliasName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestAlias2()
{
var text = @"
using Goo = N1.N2.N3.C1;
namespace N1 {
namespace N2.N3 {
class C1 {
class C2 {} } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3").
GetTypeMembers("C1").Single().
GetTypeMembers("C2").Single();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces);
TestSymbolDescription(
text,
findSymbol,
format,
"Goo.C2",
text.IndexOf("namespace", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.AliasName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Theory, MemberData(nameof(FileScopedOrBracedNamespace))]
public void TestAlias3(string ob, string cb)
{
var text = @"
using Goo = N1.C1;
namespace N1 " + ob + @"
class Goo { }
class C1 { }
" + cb + @"
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetTypeMembers("C1").Single();
var format = SymbolDisplayFormat.MinimallyQualifiedFormat;
TestSymbolDescription(
text,
findSymbol,
format,
"C1",
text.IndexOf("class Goo", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestMinimalNamespace1()
{
var text = @"
namespace N1 {
namespace N2 {
namespace N3 {
class C1 {
class C2 {} } } } }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetNestedNamespace("N1").
GetNestedNamespace("N2").
GetNestedNamespace("N3");
var format = new SymbolDisplayFormat();
TestSymbolDescription(text, findSymbol, format,
"N1.N2.N3",
text.IndexOf("N1", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName);
TestSymbolDescription(text, findSymbol, format,
"N2.N3",
text.IndexOf("N2", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName);
TestSymbolDescription(text, findSymbol, format,
"N3",
text.IndexOf("N3", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.NamespaceName);
TestSymbolDescription(text, findSymbol, format,
"N3",
text.IndexOf("C1", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.NamespaceName);
TestSymbolDescription(text, findSymbol, format,
"N3",
text.IndexOf("C2", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.NamespaceName);
}
public class ScriptGlobals
{
public void Method(int p) { Event.Invoke(); }
public delegate void MyDelegate(int x);
public int Field;
public int Property => 1;
public event Action Event;
public class NestedType
{
public void Method(int p) { Event.Invoke(); }
public delegate void MyDelegate(int x);
public int Field;
public int Property => 1;
public event Action Event;
}
}
[Fact]
public void TestMembersInScriptGlobals()
{
var text = @"1";
var tree = SyntaxFactory.ParseSyntaxTree(text, TestOptions.Script);
var hostReference = MetadataReference.CreateFromFile(typeof(ScriptGlobals).Assembly.Location);
var comp = CSharpCompilation.CreateScriptCompilation(
"submission1",
tree,
TargetFrameworkUtil.GetReferences(TargetFramework.Standard).Concat(hostReference),
returnType: typeof(object),
globalsType: typeof(ScriptGlobals));
var model = comp.GetSemanticModel(tree);
var hostTypeSymbol = comp.GetHostObjectTypeSymbol();
var methodSymbol = hostTypeSymbol.GetMember("Method");
var delegateSymbol = hostTypeSymbol.GetMember("MyDelegate");
var fieldSymbol = hostTypeSymbol.GetMember("Field");
var propertySymbol = hostTypeSymbol.GetMember("Property");
var eventSymbol = hostTypeSymbol.GetMember("Event");
var nestedTypeSymbol = (TypeSymbol)hostTypeSymbol.GetMember("NestedType");
var nestedMethodSymbol = nestedTypeSymbol.GetMember("Method");
var nestedDelegateSymbol = nestedTypeSymbol.GetMember("MyDelegate");
var nestedFieldSymbol = nestedTypeSymbol.GetMember("Field");
var nestedPropertySymbol = nestedTypeSymbol.GetMember("Property");
var nestedEventSymbol = nestedTypeSymbol.GetMember("Event");
Verify(methodSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"void Method(int p)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(delegateSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"MyDelegate(int x)",
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(fieldSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"int Field",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
Verify(propertySymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"int Property { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(eventSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"event System.Action Event",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EventName);
Verify(nestedTypeSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"NestedType",
SymbolDisplayPartKind.ClassName);
Verify(nestedMethodSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"void NestedType.Method(int p)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(nestedDelegateSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"NestedType.MyDelegate(int x)",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(nestedFieldSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"int NestedType.Field",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.FieldName);
Verify(nestedPropertySymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"int NestedType.Property { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(nestedEventSymbol.ToMinimalDisplayParts(model, position: 0, s_memberSignatureDisplayFormat),
"event System.Action NestedType.Event",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
}
private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions:
SymbolDisplayMemberOptions.IncludeRef |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeContainingType,
delegateStyle:
SymbolDisplayDelegateStyle.NameAndSignature,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
propertyStyle:
SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeOptionalBrackets,
localOptions:
SymbolDisplayLocalOptions.IncludeRef |
SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName |
SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier |
SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral);
[Fact]
public void TestRemoveAttributeSuffix1()
{
var text = @"
class class1Attribute : System.Attribute { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("class1Attribute").Single();
TestSymbolDescription(text, findSymbol,
new SymbolDisplayFormat(),
"class1Attribute",
SymbolDisplayPartKind.ClassName);
TestSymbolDescription(text, findSymbol,
new SymbolDisplayFormat(miscellaneousOptions: SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix),
"class1",
0,
true,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestRemoveAttributeSuffix2()
{
var text = @"
class classAttribute : System.Attribute { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("classAttribute").Single();
TestSymbolDescription(text, findSymbol,
new SymbolDisplayFormat(),
"classAttribute",
SymbolDisplayPartKind.ClassName);
TestSymbolDescription(text, findSymbol,
new SymbolDisplayFormat(miscellaneousOptions: SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix),
"classAttribute",
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestRemoveAttributeSuffix3()
{
var text = @"
class class1Attribute { }
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("class1Attribute").Single();
TestSymbolDescription(text, findSymbol,
new SymbolDisplayFormat(),
"class1Attribute",
SymbolDisplayPartKind.ClassName);
TestSymbolDescription(text, findSymbol,
new SymbolDisplayFormat(miscellaneousOptions: SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix),
"class1Attribute",
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void TestMinimalClass1()
{
var text = @"
using System.Collections.Generic;
class C1 {
private System.Collections.Generic.IDictionary<System.Collections.Generic.IList<System.Int32>, System.String> goo;
}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
((FieldSymbol)global.GetTypeMembers("C1").Single().GetMembers("goo").Single()).Type;
var format = SymbolDisplayFormat.MinimallyQualifiedFormat;
TestSymbolDescription(text, findSymbol, format,
"IDictionary<IList<int>, string>",
text.IndexOf("goo", StringComparison.Ordinal),
true,
SymbolDisplayPartKind.InterfaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.InterfaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestMethodCustomModifierPositions()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[]
{
TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll,
Net40.mscorlib
});
var globalNamespace = assemblies[0].GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("MethodCustomModifierCombinations");
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers);
Verify(@class.GetMember<MethodSymbol>("Method1111").ToDisplayParts(format),
"int modopt(IsConst) [] modopt(IsConst) Method1111(int modopt(IsConst) [] modopt(IsConst) a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(@class.GetMember<MethodSymbol>("Method1000").ToDisplayParts(format),
"int modopt(IsConst) [] Method1000(int[] a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(@class.GetMember<MethodSymbol>("Method0100").ToDisplayParts(format),
"int[] modopt(IsConst) Method0100(int[] a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(@class.GetMember<MethodSymbol>("Method0010").ToDisplayParts(format),
"int[] Method0010(int modopt(IsConst) [] a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(@class.GetMember<MethodSymbol>("Method0001").ToDisplayParts(format),
"int[] Method0001(int[] modopt(IsConst) a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(@class.GetMember<MethodSymbol>("Method0000").ToDisplayParts(format),
"int[] Method0000(int[] a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestPropertyCustomModifierPositions()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[]
{
TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll,
Net40.mscorlib
});
var globalNamespace = assemblies[0].GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("PropertyCustomModifierCombinations");
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers);
Verify(@class.GetMember<PropertySymbol>("Property11").ToDisplayParts(format),
"int modopt(IsConst) [] modopt(IsConst) Property11",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName);
Verify(@class.GetMember<PropertySymbol>("Property10").ToDisplayParts(format),
"int modopt(IsConst) [] Property10",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName);
Verify(@class.GetMember<PropertySymbol>("Property01").ToDisplayParts(format),
"int[] modopt(IsConst) Property01",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName);
Verify(@class.GetMember<PropertySymbol>("Property00").ToDisplayParts(format),
"int[] Property00",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName);
}
[Fact]
public void TestFieldCustomModifierPositions()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[]
{
TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll,
Net40.mscorlib
});
var globalNamespace = assemblies[0].GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("FieldCustomModifierCombinations");
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers);
Verify(@class.GetMember<FieldSymbol>("field11").ToDisplayParts(format),
"int modopt(IsConst) [] modopt(IsConst) field11",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
Verify(@class.GetMember<FieldSymbol>("field10").ToDisplayParts(format),
"int modopt(IsConst) [] field10",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
Verify(@class.GetMember<FieldSymbol>("field01").ToDisplayParts(format),
"int[] modopt(IsConst) field01",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
Verify(@class.GetMember<FieldSymbol>("field00").ToDisplayParts(format),
"int[] field00",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[Fact]
public void TestMultipleCustomModifier()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[]
{
TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll,
Net40.mscorlib
});
var globalNamespace = assemblies[0].GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("Modifiers");
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers);
Verify(@class.GetMember<MethodSymbol>("F3").ToDisplayParts(format),
"void F3(int modopt(int) modopt(IsConst) modopt(IsConst) p)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
}
private static void TestSymbolDescription(
string source,
Func<NamespaceSymbol, Symbol> findSymbol,
SymbolDisplayFormat format,
string expectedText,
int position,
bool minimal,
params SymbolDisplayPartKind[] expectedKinds)
{
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var global = comp.GlobalNamespace;
var symbol = findSymbol(global);
var description = minimal
? symbol.ToMinimalDisplayParts(model, position, format)
: symbol.ToDisplayParts(format);
Verify(description, expectedText, expectedKinds);
}
private static void TestSymbolDescription(
string source,
Func<NamespaceSymbol, Symbol> findSymbol,
SymbolDisplayFormat format,
string expectedText,
params SymbolDisplayPartKind[] expectedKinds)
{
TestSymbolDescription(source, findSymbol, format, null, expectedText, expectedKinds);
}
private static void TestSymbolDescription(
string source,
Func<NamespaceSymbol, Symbol> findSymbol,
SymbolDisplayFormat format,
CSharpParseOptions parseOptions,
string expectedText,
params SymbolDisplayPartKind[] expectedKinds)
{
var comp = CreateCompilation(source, parseOptions: parseOptions);
var global = comp.GlobalNamespace;
var symbol = findSymbol(global);
var description = symbol.ToDisplayParts(format);
Verify(description, expectedText, expectedKinds);
}
private static void Verify(ImmutableArray<SymbolDisplayPart> actualParts, string expectedText, params SymbolDisplayPartKind[] expectedKinds)
{
Assert.Equal(expectedText, actualParts.ToDisplayString());
if (expectedKinds.Length > 0)
{
AssertEx.Equal(expectedKinds, actualParts.Select(p => p.Kind), itemInspector: p => $" SymbolDisplayPartKind.{p}");
}
}
[Fact]
public void DelegateStyleRecursive()
{
var text = "public delegate void D(D param);";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("D", 0).Single();
var format = new SymbolDisplayFormat(globalNamespaceStyle: SymbolDisplayFormat.CSharpErrorMessageFormat.GlobalNamespaceStyle,
typeQualificationStyle: SymbolDisplayFormat.CSharpErrorMessageFormat.TypeQualificationStyle,
genericsOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.GenericsOptions,
memberOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.MemberOptions,
parameterOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.ParameterOptions,
propertyStyle: SymbolDisplayFormat.CSharpErrorMessageFormat.PropertyStyle,
localOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.LocalOptions,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
miscellaneousOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.MiscellaneousOptions);
TestSymbolDescription(
text,
findSymbol,
format,
"delegate void D(D)",
SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Punctuation);
format = new SymbolDisplayFormat(parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
miscellaneousOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.MiscellaneousOptions);
TestSymbolDescription(
text,
findSymbol,
format,
"void D(D param)",
SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void GlobalNamespace1()
{
var text = @"public class Test
{
public class System
{
public class Action
{
}
}
public global::System.Action field;
public System.Action field2;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
{
var field = global.GetTypeMembers("Test", 0).Single().GetMembers("field").Single() as FieldSymbol;
return field.Type;
};
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"global::System.Action",
text.IndexOf("global::System.Action", StringComparison.Ordinal),
true /* minimal */,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName);
}
[Fact]
public void GlobalNamespace2()
{
var text = @"public class Test
{
public class System
{
public class Action
{
}
}
public global::System.Action field;
public System.Action field2;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
{
var field = global.GetTypeMembers("Test", 0).Single().GetMembers("field").Single() as FieldSymbol;
return field.Type;
};
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"System.Action",
text.IndexOf("global::System.Action", StringComparison.Ordinal),
true /* minimal */,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName);
}
[Fact]
public void GlobalNamespace3()
{
var text = @"public class Test
{
public class System
{
public class Action
{
}
}
public System.Action field2;
public global::System.Action field;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
{
var field = global.GetTypeMembers("Test", 0).Single().GetMembers("field2").Single() as FieldSymbol;
return field.Type;
};
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
"System.Action",
text.IndexOf("System.Action", StringComparison.Ordinal),
true /* minimal */,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void DefaultParameterValues()
{
var text = @"
struct S
{
void M(
int i = 1,
string str = ""hello"",
object o = null
S s = default(S))
{
}
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("M");
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(text, findSymbol,
format,
@"void S.M(int i = 1, string str = ""hello"", object o = null, S s = default(S))",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NumericLiteral,
SymbolDisplayPartKind.Punctuation, //,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StringLiteral,
SymbolDisplayPartKind.Punctuation, //,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation, //,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //)
SymbolDisplayPartKind.Punctuation); //)
}
[Fact]
public void DefaultParameterValues_TypeParameter()
{
var text = @"
struct S
{
void M<T>(T t = default(T))
{
}
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("M");
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(text, findSymbol,
format,
@"void S.M<T>(T t = default(T))",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //<
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation, //>
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation, //)
SymbolDisplayPartKind.Punctuation); //)
}
[Fact]
public void DefaultParameterValues_Enum()
{
var text = @"
enum E
{
A = 1,
B = 2,
C = 5,
}
struct S
{
void P(E e = (E)1)
{
}
void Q(E e = (E)3)
{
}
void R(E e = (E)5)
{
}
}";
Func<NamespaceSymbol, Symbol> findSymbol1 = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("P");
Func<NamespaceSymbol, Symbol> findSymbol2 = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("Q");
Func<NamespaceSymbol, Symbol> findSymbol3 = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("R");
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(text, findSymbol1,
format,
@"void S.P(E e = E.A)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation); //)
TestSymbolDescription(text, findSymbol2,
format,
@"void S.Q(E e = (E)3)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //)
SymbolDisplayPartKind.NumericLiteral,
SymbolDisplayPartKind.Punctuation); //)
TestSymbolDescription(text, findSymbol3,
format,
@"void S.R(E e = E.C)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation); //)
}
[Fact]
public void DefaultParameterValues_FlagsEnum()
{
var text = @"
[System.FlagsAttribute]
enum E
{
A = 1,
B = 2,
C = 5,
}
struct S
{
void P(E e = (E)1)
{
}
void Q(E e = (E)3)
{
}
void R(E e = (E)5)
{
}
}";
Func<NamespaceSymbol, Symbol> findSymbol1 = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("P");
Func<NamespaceSymbol, Symbol> findSymbol2 = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("Q");
Func<NamespaceSymbol, Symbol> findSymbol3 = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("R");
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(text, findSymbol1,
format,
@"void S.P(E e = E.A)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation); //)
TestSymbolDescription(text, findSymbol2,
format,
@"void S.Q(E e = E.A | E.B)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //|
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation); //)
TestSymbolDescription(text, findSymbol3,
format,
@"void S.R(E e = E.C)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void DefaultParameterValues_NegativeEnum()
{
var text = @"
[System.FlagsAttribute]
enum E : sbyte
{
A = -2,
A1 = -2,
B = 1,
B1 = 1,
C = 0,
C1 = 0,
}
struct S
{
void P(E e = (E)(-2), E f = (E)(-1), E g = (E)0, E h = (E)(-3))
{
}
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("P");
var format =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeDefaultValue,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(text, findSymbol,
format,
@"void S.P(E e = E.A, E f = E.A | E.B, E g = E.C, E h = (E)-3)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation, //(
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation, //,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //|
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation, //,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, //=
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, //.
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Punctuation, //,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, // =
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation, // (
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation, // )
SymbolDisplayPartKind.NumericLiteral,
SymbolDisplayPartKind.Punctuation); //)
}
[Fact]
public void TestConstantFieldValue()
{
var text =
@"class C {
const int f = 1;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeConstantValue);
TestSymbolDescription(
text,
findSymbol,
format,
"private const Int32 C.f = 1",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ConstantName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NumericLiteral);
}
[Fact]
public void TestConstantFieldValue_EnumMember()
{
var text =
@"
enum E { A, B, C }
class C {
const E f = E.B;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeConstantValue);
TestSymbolDescription(
text,
findSymbol,
format,
"private const E C.f = E.B",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ConstantName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName);
}
[Fact]
public void TestConstantFieldValue_EnumMember_Flags()
{
var text =
@"
[System.FlagsAttribute]
enum E { A = 1, B = 2, C = 4, D = A | B | C }
class C {
const E f = E.D;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("C", 0).Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeConstantValue);
TestSymbolDescription(
text,
findSymbol,
format,
"private const E C.f = E.D",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ConstantName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName);
}
[Fact]
public void TestEnumMember()
{
var text =
@"enum E { A, B, C }";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("E", 0).Single().
GetMembers("B").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeConstantValue);
TestSymbolDescription(
text,
findSymbol,
format,
"E.B = 1",
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NumericLiteral);
}
[Fact]
public void TestEnumMember_Flags()
{
var text =
@"[System.FlagsAttribute]
enum E { A = 1, B = 2, C = 4, D = A | B | C }";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("E", 0).Single().
GetMembers("D").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeConstantValue);
TestSymbolDescription(
text,
findSymbol,
format,
"E.D = E.A | E.B | E.C",
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName);
}
[Fact]
public void TestEnumMember_FlagsWithoutAttribute()
{
var text =
@"enum E { A = 1, B = 2, C = 4, D = A | B | C }";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetTypeMembers("E", 0).Single().
GetMembers("D").Single();
var format = new SymbolDisplayFormat(
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeConstantValue);
TestSymbolDescription(
text,
findSymbol,
format,
"E.D = 7",
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NumericLiteral);
}
[Fact, WorkItem(545462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545462")]
public void DateTimeDefaultParameterValue()
{
var text = @"
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class C
{
static void Goo([Optional][DateTimeConstant(100)] DateTime d) { }
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("C").
GetMember<MethodSymbol>("Goo");
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeDefaultValue);
TestSymbolDescription(
text,
findSymbol,
format,
"Goo(DateTime d)",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact, WorkItem(545681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545681")]
public void TypeParameterFromMetadata()
{
var src1 = @"
public class LibG<T>
{
}
";
var src2 = @"
public class Gen<V>
{
public void M(LibG<V> p)
{
}
}
";
var complib = CreateCompilation(src1, assemblyName: "Lib");
var compref = new CSharpCompilationReference(complib);
var comp1 = CreateCompilation(src2, references: new MetadataReference[] { compref }, assemblyName: "Comp1");
var mtdata = comp1.EmitToArray();
var mtref = MetadataReference.CreateFromImage(mtdata);
var comp2 = CreateCompilation("", references: new MetadataReference[] { mtref }, assemblyName: "Comp2");
var tsym1 = comp1.SourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("Gen");
Assert.NotNull(tsym1);
var msym1 = tsym1.GetMember<MethodSymbol>("M");
Assert.NotNull(msym1);
Assert.Equal("Gen<V>.M(LibG<V>)", msym1.ToDisplayString());
var tsym2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("Gen");
Assert.NotNull(tsym2);
var msym2 = tsym2.GetMember<MethodSymbol>("M");
Assert.NotNull(msym2);
Assert.Equal(msym1.ToDisplayString(), msym2.ToDisplayString());
}
[Fact, WorkItem(545625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545625")]
public void ReverseArrayRankSpecifiers()
{
var text = @"
public class C
{
C[][,] F;
}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.GetMember<NamedTypeSymbol>("C").GetMember<FieldSymbol>("F").Type;
var normalFormat = new SymbolDisplayFormat();
var reverseFormat = new SymbolDisplayFormat(
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.ReverseArrayRankSpecifiers);
TestSymbolDescription(
text,
findSymbol,
normalFormat,
"C[][,]",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
TestSymbolDescription(
text,
findSymbol,
reverseFormat,
"C[,][]",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact, WorkItem(546638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546638")]
public void InvariantCultureNegatives()
{
var text = @"
public class C
{
void M(
sbyte p1 = (sbyte)-1,
short p2 = (short)-1,
int p3 = (int)-1,
long p4 = (long)-1,
float p5 = (float)-0.5,
double p6 = (double)-0.5,
decimal p7 = (decimal)-0.5)
{
}
}
";
var newCulture = (CultureInfo)CultureInfo.CurrentUICulture.Clone();
newCulture.NumberFormat.NegativeSign = "~";
newCulture.NumberFormat.NumberDecimalSeparator = ",";
using (new CultureContext(newCulture))
{
var compilation = CreateCompilation(text);
compilation.VerifyDiagnostics();
var symbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M");
Assert.Equal("void C.M(" +
"[System.SByte p1 = -1], " +
"[System.Int16 p2 = -1], " +
"[System.Int32 p3 = -1], " +
"[System.Int64 p4 = -1], " +
"[System.Single p5 = -0.5], " +
"[System.Double p6 = -0.5], " +
"[System.Decimal p7 = -0.5])", symbol.ToTestDisplayString());
}
}
[Fact]
public void TestMethodVB()
{
var text = @"
Class A
Public Sub Goo(a As Integer)
End Sub
End Class";
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var comp = CreateVisualBasicCompilation("c", text);
var a = (ITypeSymbol)comp.GlobalNamespace.GetMembers("A").Single();
var goo = a.GetMembers("Goo").Single();
var parts = Microsoft.CodeAnalysis.CSharp.SymbolDisplay.ToDisplayParts(goo, format);
Verify(
parts,
"public void Goo(int a)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestWindowsRuntimeEvent()
{
var source = @"
class C
{
event System.Action E;
}
";
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface);
var comp = CreateEmptyCompilation(source, WinRtRefs, TestOptions.ReleaseWinMD);
var eventSymbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<EventSymbol>("E");
Assert.True(eventSymbol.IsWindowsRuntimeEvent);
Verify(
eventSymbol.ToDisplayParts(format),
"Action C.E",
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
Verify(
eventSymbol.AddMethod.ToDisplayParts(format),
"EventRegistrationToken C.E.add",
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(
eventSymbol.RemoveMethod.ToDisplayParts(format),
"void C.E.remove",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[WorkItem(791756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/791756")]
[Theory]
[MemberData(nameof(FileScopedOrBracedNamespace))]
public void KindOptions(string ob, string cb)
{
var source = @"
namespace N
" + ob + @"
class C
{
event System.Action E;
}
" + cb + @"
";
var memberFormat = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword);
var typeFormat = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
kindOptions: SymbolDisplayKindOptions.IncludeTypeKeyword);
var namespaceFormat = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword);
var comp = CreateCompilation(source);
var namespaceSymbol = comp.GlobalNamespace.GetMember<NamespaceSymbol>("N");
var typeSymbol = namespaceSymbol.GetMember<NamedTypeSymbol>("C");
var eventSymbol = typeSymbol.GetMember<EventSymbol>("E");
Verify(
namespaceSymbol.ToDisplayParts(memberFormat),
"N",
SymbolDisplayPartKind.NamespaceName);
Verify(
namespaceSymbol.ToDisplayParts(typeFormat),
"N",
SymbolDisplayPartKind.NamespaceName);
Verify(
namespaceSymbol.ToDisplayParts(namespaceFormat),
"namespace N",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName);
Verify(
typeSymbol.ToDisplayParts(memberFormat),
"N.C",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
Verify(
typeSymbol.ToDisplayParts(typeFormat),
"class N.C",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
Verify(
typeSymbol.ToDisplayParts(namespaceFormat),
"N.C",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
Verify(
eventSymbol.ToDisplayParts(memberFormat),
"event N.C.E",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
Verify(
eventSymbol.ToDisplayParts(typeFormat),
"N.C.E",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
Verify(
eventSymbol.ToDisplayParts(namespaceFormat),
"N.C.E",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
}
[WorkItem(765287, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/765287")]
[Fact]
public void TestVbSymbols()
{
var vbComp = CreateVisualBasicCompilation(@"
Class Outer
Class Inner(Of T)
End Class
Sub M(Of U)()
End Sub
WriteOnly Property P() As String
Set(value)
End Set
End Property
Private F As Integer
Event E()
Delegate Sub D()
Function [Error]() As Missing
End Function
End Class
", assemblyName: "VB");
var outer = (INamedTypeSymbol)vbComp.GlobalNamespace.GetMembers("Outer").Single();
var type = outer.GetMembers("Inner").Single();
var method = outer.GetMembers("M").Single();
var property = outer.GetMembers("P").Single();
var field = outer.GetMembers("F").Single();
var @event = outer.GetMembers("E").Single();
var @delegate = outer.GetMembers("D").Single();
var error = outer.GetMembers("Error").Single();
Assert.False(type is Symbol);
Assert.False(method is Symbol);
Assert.False(property is Symbol);
Assert.False(field is Symbol);
Assert.False(@event is Symbol);
Assert.False(@delegate is Symbol);
Assert.False(error is Symbol);
// 1) Looks like C#.
// 2) Doesn't blow up.
Assert.Equal("Outer.Inner<T>", CSharp.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat));
Assert.Equal("void Outer.M<U>()", CSharp.SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat));
Assert.Equal("System.String Outer.P { set; }", CSharp.SymbolDisplay.ToDisplayString(property, SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Int32 Outer.F", CSharp.SymbolDisplay.ToDisplayString(field, SymbolDisplayFormat.TestFormat));
Assert.Equal("event Outer.EEventHandler Outer.E", CSharp.SymbolDisplay.ToDisplayString(@event, SymbolDisplayFormat.TestFormat));
Assert.Equal("Outer.D", CSharp.SymbolDisplay.ToDisplayString(@delegate, SymbolDisplayFormat.TestFormat));
Assert.Equal("Missing Outer.Error()", CSharp.SymbolDisplay.ToDisplayString(error, SymbolDisplayFormat.TestFormat));
}
[Fact]
public void FormatPrimitive()
{
// basic tests, more cases are covered by ObjectFormatterTests
Assert.Equal("1", SymbolDisplay.FormatPrimitive(1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((uint)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((byte)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((sbyte)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((short)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((ushort)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((long)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1", SymbolDisplay.FormatPrimitive((ulong)1, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("x", SymbolDisplay.FormatPrimitive('x', quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("true", SymbolDisplay.FormatPrimitive(true, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1.5", SymbolDisplay.FormatPrimitive(1.5, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1.5", SymbolDisplay.FormatPrimitive((float)1.5, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("1.5", SymbolDisplay.FormatPrimitive((decimal)1.5, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("null", SymbolDisplay.FormatPrimitive(null, quoteStrings: false, useHexadecimalNumbers: false));
Assert.Equal("abc", SymbolDisplay.FormatPrimitive("abc", quoteStrings: false, useHexadecimalNumbers: false));
Assert.Null(SymbolDisplay.FormatPrimitive(SymbolDisplayFormat.TestFormat, quoteStrings: false, useHexadecimalNumbers: false));
}
[WorkItem(879984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879984")]
[Fact]
public void EnumAmbiguityResolution()
{
var source = @"
using System;
class Program
{
static void M(E1 e1 = (E1)1, E2 e2 = (E2)1)
{
}
}
enum E1
{
B = 1,
A = 1,
}
[Flags]
enum E2 // Identical to E1, but has [Flags]
{
B = 1,
A = 1,
}
";
var comp = CreateCompilation(source);
var method = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").GetMember<MethodSymbol>("M");
var memberFormat = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue);
Assert.Equal("M(e1 = A, e2 = A)", method.ToDisplayString(memberFormat)); // Alphabetically first candidate chosen for both enums.
}
[Fact, WorkItem(1028003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1028003")]
public void UnconventionalExplicitInterfaceImplementation()
{
var il = @"
.class public auto ansi sealed DTest
extends [mscorlib]System.MulticastDelegate
{
.method public hidebysig specialname rtspecialname
instance void .ctor(object 'object',
native int 'method') runtime managed
{
} // end of method DTest::.ctor
.method public hidebysig newslot virtual
instance void Invoke() runtime managed
{
} // end of method DTest::Invoke
.method public hidebysig newslot virtual
instance class [mscorlib]System.IAsyncResult
BeginInvoke(class [mscorlib]System.AsyncCallback callback,
object 'object') runtime managed
{
} // end of method DTest::BeginInvoke
.method public hidebysig newslot virtual
instance void EndInvoke(class [mscorlib]System.IAsyncResult result) runtime managed
{
} // end of method DTest::EndInvoke
} // end of class DTest
.class interface public abstract auto ansi ITest
{
.method public hidebysig newslot abstract virtual
instance void M1() cil managed
{
} // end of method ITest::M1
.method public hidebysig newslot specialname abstract virtual
instance int32 get_P1() cil managed
{
} // end of method ITest::get_P1
.method public hidebysig newslot specialname abstract virtual
instance void set_P1(int32 'value') cil managed
{
} // end of method ITest::set_P1
.method public hidebysig newslot specialname abstract virtual
instance void add_E1(class DTest 'value') cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
} // end of method ITest::add_E1
.method public hidebysig newslot specialname abstract virtual
instance void remove_E1(class DTest 'value') cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
} // end of method ITest::remove_E1
.event DTest E1
{
.addon instance void ITest::add_E1(class DTest)
.removeon instance void ITest::remove_E1(class DTest)
} // end of event ITest::E1
.property instance int32 P1()
{
.get instance int32 ITest::get_P1()
.set instance void ITest::set_P1(int32)
} // end of property ITest::P1
} // end of class ITest
.class public auto ansi beforefieldinit CTest
extends [mscorlib]System.Object
implements ITest
{
.method public hidebysig newslot specialname virtual final
instance int32 get_P1() cil managed
{
.override ITest::get_P1
// Code size 7 (0x7)
.maxstack 8
IL_0000: nop
IL_0001: newobj instance void [mscorlib]System.NotImplementedException::.ctor()
IL_0006: throw
} // end of method CTest::ITest.get_P1
.method public hidebysig newslot specialname virtual final
instance void set_P1(int32 'value') cil managed
{
.override ITest::set_P1
// Code size 7 (0x7)
.maxstack 8
IL_0000: nop
IL_0001: newobj instance void [mscorlib]System.NotImplementedException::.ctor()
IL_0006: throw
} // end of method CTest::ITest.set_P1
.method public hidebysig newslot specialname virtual final
instance void add_E1(class DTest 'value') cil managed
{
.override ITest::add_E1
// Code size 7 (0x7)
.maxstack 8
IL_0000: nop
IL_0001: newobj instance void [mscorlib]System.NotImplementedException::.ctor()
IL_0006: throw
} // end of method CTest::ITest.add_E1
.method public hidebysig newslot specialname virtual final
instance void remove_E1(class DTest 'value') cil managed
{
.override ITest::remove_E1
// Code size 7 (0x7)
.maxstack 8
IL_0000: nop
IL_0001: newobj instance void [mscorlib]System.NotImplementedException::.ctor()
IL_0006: throw
} // end of method CTest::ITest.remove_E1
.method public hidebysig newslot virtual final
instance void M1() cil managed
{
.override ITest::M1
// Code size 7 (0x7)
.maxstack 8
IL_0000: nop
IL_0001: newobj instance void [mscorlib]System.NotImplementedException::.ctor()
IL_0006: throw
} // end of method CTest::ITest.M1
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method CTest::.ctor
.event DTest E1
{
.addon instance void CTest::add_E1(class DTest)
.removeon instance void CTest::remove_E1(class DTest)
} // end of event CTest::ITest.E1
.property instance int32 P1()
{
.get instance int32 CTest::get_P1()
.set instance void CTest::set_P1(int32)
} // end of property CTest::ITest.P1
} // end of class CTest
";
var text = @"";
var comp = CreateCompilationWithILAndMscorlib40(text, il);
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface);
var cTest = comp.GetTypeByMetadataName("CTest");
var m1 = cTest.GetMember("M1");
Assert.Equal("M1", m1.Name);
Assert.Equal("M1", m1.ToDisplayString(format));
var p1 = cTest.GetMember("P1");
Assert.Equal("P1", p1.Name);
Assert.Equal("P1", p1.ToDisplayString(format));
var e1 = cTest.GetMember("E1");
Assert.Equal("E1", e1.Name);
Assert.Equal("E1", e1.ToDisplayString(format));
}
[WorkItem(6262, "https://github.com/dotnet/roslyn/issues/6262")]
[Fact]
public void FormattedSymbolEquality()
{
var source =
@"class A { }
class B { }
class C<T> { }";
var compilation = CreateCompilation(source);
var sA = compilation.GetMember<NamedTypeSymbol>("A");
var sB = compilation.GetMember<NamedTypeSymbol>("B");
var sC = compilation.GetMember<NamedTypeSymbol>("C");
var f1 = new SymbolDisplayFormat();
var f2 = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeParameters);
Assert.False(new FormattedSymbol(sA, f1).Equals((object)sA));
Assert.False(new FormattedSymbol(sA, f1).Equals(null));
Assert.True(new FormattedSymbol(sA, f1).Equals(new FormattedSymbol(sA, f1)));
Assert.False(new FormattedSymbol(sA, f1).Equals(new FormattedSymbol(sA, f2)));
Assert.False(new FormattedSymbol(sA, f1).Equals(new FormattedSymbol(sB, f1)));
Assert.False(new FormattedSymbol(sA, f1).Equals(new FormattedSymbol(sB, f2)));
Assert.False(new FormattedSymbol(sC, f1).Equals(new FormattedSymbol(sC.Construct(sA), f1)));
Assert.True(new FormattedSymbol(sC.Construct(sA), f1).Equals(new FormattedSymbol(sC.Construct(sA), f1)));
Assert.False(new FormattedSymbol(sA, new SymbolDisplayFormat()).Equals(new FormattedSymbol(sA, new SymbolDisplayFormat())));
Assert.True(new FormattedSymbol(sA, f1).GetHashCode().Equals(new FormattedSymbol(sA, f1).GetHashCode()));
}
[Fact, CompilerTrait(CompilerFeature.Tuples)]
public void Tuple()
{
var text = @"
public class C
{
public (int, string) f;
}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.
GetTypeMembers("C").Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular,
"(Int32, String) f",
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName, // Int32
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, // String
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, CompilerTrait(CompilerFeature.Tuples)]
public void TupleWith1Arity()
{
var text = @"
using System;
public class C
{
public ValueTuple<int> f;
}
" + TestResources.NetFX.ValueTuple.tuplelib_cs;
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.
GetTypeMembers("C").Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular,
"ValueTuple<Int32> f",
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[Fact, CompilerTrait(CompilerFeature.Tuples)]
public void TupleWithNames()
{
var text = @"
public class C
{
public (int x, string y) f;
}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.
GetTypeMembers("C").Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular,
"(Int32 x, String y) f",
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName, // Int32
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName, // x
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName, // String
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName, // y
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[Fact, CompilerTrait(CompilerFeature.Tuples)]
public void LongTupleWithSpecialTypes()
{
var text = @"
public class C
{
public (int, string, bool, byte, long, ulong, short, ushort) f;
}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.
GetTypeMembers("C").Single().
GetMembers("f").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular,
"(int, string, bool, byte, long, ulong, short, ushort) f",
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword, // int
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // string
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // bool
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // byte
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // long
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // ulong
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // short
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // ushort
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
}
[Fact, CompilerTrait(CompilerFeature.Tuples)]
public void TupleProperty()
{
var text = @"
class C
{
(int Item1, string Item2) P { get; set; }
}
";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
global.
GetTypeMembers("C").Single().
GetMembers("P").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular,
"(int Item1, string Item2) P",
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword, // int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName, // Item1
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // string
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName, // Item2
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName);
}
[Fact, CompilerTrait(CompilerFeature.Tuples)]
public void TupleQualifiedNames()
{
var text =
@"using NAB = N.A.B;
namespace N
{
class A
{
internal class B {}
}
class C<T>
{
// offset 1
}
}
class C
{
#pragma warning disable CS0169
(int One, N.C<(object[], NAB Two)>, int, object Four, int, object, int, object, N.A Nine) f;
#pragma warning restore CS0169
// offset 2
}";
var format = new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions: SymbolDisplayMemberOptions.IncludeType,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var comp = (Compilation)CreateCompilationWithMscorlib46(text, references: new[] { SystemRuntimeFacadeRef, ValueTupleRef });
comp.VerifyDiagnostics();
var symbol = comp.GetMember("C.f");
// Fully qualified format.
Verify(
SymbolDisplay.ToDisplayParts(symbol, format),
"(int One, global::N.C<(object[], global::N.A.B Two)>, int, object Four, int, object, int, object, global::N.A Nine) f");
// Minimally qualified format.
Verify(
SymbolDisplay.ToDisplayParts(symbol, SymbolDisplayFormat.MinimallyQualifiedFormat),
"(int One, C<(object[], B Two)>, int, object Four, int, object, int, object, A Nine) C.f");
// ToMinimalDisplayParts.
var model = comp.GetSemanticModel(comp.SyntaxTrees.First());
Verify(
SymbolDisplay.ToMinimalDisplayParts(symbol, model, text.IndexOf("offset 1"), format),
"(int One, C<(object[], NAB Two)>, int, object Four, int, object, int, object, A Nine) f");
Verify(
SymbolDisplay.ToMinimalDisplayParts(symbol, model, text.IndexOf("offset 2"), format),
"(int One, N.C<(object[], NAB Two)>, int, object Four, int, object, int, object, N.A Nine) f");
}
[Fact]
[WorkItem(23970, "https://github.com/dotnet/roslyn/pull/23970")]
public void ThisDisplayParts()
{
var text =
@"
class A
{
void M(int @this)
{
this.M(@this);
}
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single();
Assert.Equal("this.M(@this)", invocation.ToString());
var actualThis = ((MemberAccessExpressionSyntax)invocation.Expression).Expression;
Assert.Equal("this", actualThis.ToString());
Verify(
SymbolDisplay.ToDisplayParts(model.GetSymbolInfo(actualThis).Symbol, SymbolDisplayFormat.MinimallyQualifiedFormat),
"A this",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword);
var escapedThis = invocation.ArgumentList.Arguments[0].Expression;
Assert.Equal("@this", escapedThis.ToString());
Verify(
SymbolDisplay.ToDisplayParts(model.GetSymbolInfo(escapedThis).Symbol, SymbolDisplayFormat.MinimallyQualifiedFormat),
"int @this",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName);
}
[WorkItem(11356, "https://github.com/dotnet/roslyn/issues/11356")]
[Fact]
public void RefReturn()
{
var sourceA =
@"public delegate ref int D();
public class C
{
public ref int F(ref int i) => ref i;
int _p;
public ref int P => ref _p;
public ref int this[int i] => ref _p;
}";
var compA = CreateEmptyCompilation(sourceA, new[] { MscorlibRef });
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
// From C# symbols.
RefReturnInternal(compA);
var compB = CreateVisualBasicCompilation(GetUniqueName(), "", referencedAssemblies: new[] { MscorlibRef, refA });
compB.VerifyDiagnostics();
// From VB symbols.
RefReturnInternal(compB);
}
private static void RefReturnInternal(Compilation comp)
{
var formatBase = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut,
propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var formatWithoutRef = formatBase.WithMemberOptions(
SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType);
var formatWithRef = formatBase.WithMemberOptions(
SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef);
var formatWithoutTypeWithRef = formatBase.WithMemberOptions(
SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeRef);
var global = comp.GlobalNamespace;
var type = global.GetTypeMembers("C").Single();
var method = type.GetMembers("F").Single();
var property = type.GetMembers("P").Single();
var indexer = type.GetMembers().Where(m => m.Kind == SymbolKind.Property && ((IPropertySymbol)m).IsIndexer).Single();
var @delegate = global.GetTypeMembers("D").Single();
// Method without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutRef),
"int F(ref int)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
// Property without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(property, formatWithoutRef),
"int P { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Indexer without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(indexer, formatWithoutRef),
"int this[int] { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Delegate without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(@delegate, formatWithoutRef),
"int D()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
// Method with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithRef),
"ref int F(ref int)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
// Property with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(property, formatWithRef),
"ref int P { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Indexer with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(indexer, formatWithRef),
"ref int this[int] { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Delegate with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(@delegate, formatWithRef),
"ref int D()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
// Method without IncludeType, with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutTypeWithRef),
"F(ref int)",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public void RefReadonlyReturn()
{
var sourceA =
@"public delegate ref readonly int D();
public class C
{
public ref readonly int F(in int i) => ref i;
int _p;
public ref readonly int P => ref _p;
public ref readonly int this[in int i] => ref _p;
}";
var compA = CreateCompilation(sourceA);
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
// From C# symbols.
RefReadonlyReturnInternal(compA);
var compB = CreateVisualBasicCompilation(GetUniqueName(), "", referencedAssemblies: new[] { MscorlibRef, refA });
compB.VerifyDiagnostics();
// From VB symbols.
//RefReadonlyReturnInternal(compB);
}
[Fact]
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public void RefReadonlyReturn1()
{
var sourceA =
@"public delegate ref readonly int D();
public class C
{
public ref readonly int F(in int i) => ref i;
int _p;
public ref readonly int P => ref _p;
public ref readonly int this[in int i] => ref _p;
}";
var compA = CreateCompilation(sourceA);
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
// From C# symbols.
RefReadonlyReturnInternal(compA);
var compB = CreateVisualBasicCompilation(GetUniqueName(), "", referencedAssemblies: new[] { MscorlibRef, refA });
compB.VerifyDiagnostics();
// From VB symbols.
//RefReadonlyReturnInternal(compB);
}
private static void RefReadonlyReturnInternal(Compilation comp)
{
var formatBase = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut,
propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var formatWithoutRef = formatBase.WithMemberOptions(
SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType);
var formatWithRef = formatBase.WithMemberOptions(
SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef);
var formatWithoutTypeWithRef = formatBase.WithMemberOptions(
SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeRef);
var global = comp.GlobalNamespace;
var type = global.GetTypeMembers("C").Single();
var method = type.GetMembers("F").Single();
var property = type.GetMembers("P").Single();
var indexer = type.GetMembers().Where(m => m.Kind == SymbolKind.Property && ((IPropertySymbol)m).IsIndexer).Single();
var @delegate = global.GetTypeMembers("D").Single();
// Method without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutRef),
"int F(in int)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
// Property without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(property, formatWithoutRef),
"int P { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Indexer without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(indexer, formatWithoutRef),
"int this[in int] { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Delegate without IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(@delegate, formatWithoutRef),
"int D()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
// Method with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithRef),
"ref readonly int F(in int)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
// Property with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(property, formatWithRef),
"ref readonly int P { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Indexer with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(indexer, formatWithRef),
"ref readonly int this[in int] { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
// Delegate with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(@delegate, formatWithRef),
"ref readonly int D()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
// Method without IncludeType, with IncludeRef.
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutTypeWithRef),
"F(in int)",
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
}
[WorkItem(5002, "https://github.com/dotnet/roslyn/issues/5002")]
[Fact]
public void AliasInSpeculativeSemanticModel()
{
var text =
@"using A = N.M;
namespace N.M
{
class B
{
}
}
class C
{
static void M()
{
}
}";
var comp = CreateCompilation(text);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
int position = methodDecl.Body.SpanStart;
tree = CSharpSyntaxTree.ParseText(@"
class C
{
static void M()
{
}
}");
methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(position, methodDecl, out model));
var symbol = comp.GetMember<NamedTypeSymbol>("N.M.B");
position = methodDecl.Body.SpanStart;
var description = symbol.ToMinimalDisplayParts(model, position, SymbolDisplayFormat.MinimallyQualifiedFormat);
Verify(description, "A.B", SymbolDisplayPartKind.AliasName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName);
}
[Fact]
public void NullableReferenceTypes()
{
var source = @"
class A<T>
{
}
class B
{
static object F1(object? o) => null!;
static object?[] F2(object[]? o) => null;
static A<object>? F3(A<object?> o) => null;
}";
var comp = (Compilation)CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable());
var formatWithoutNonNullableModifier = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
var formatWithNonNullableModifier = formatWithoutNonNullableModifier
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier)
.WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None);
var method = comp.GetMember<IMethodSymbol>("B.F1");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutNonNullableModifier),
"static object F1(object? o)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithNonNullableModifier),
"static object! F1(object? o)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
method = comp.GetMember<IMethodSymbol>("B.F2");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutNonNullableModifier),
"static object?[] F2(object[]? o)");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithNonNullableModifier),
"static object?[]! F2(object![]? o)");
method = comp.GetMember<IMethodSymbol>("B.F3");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutNonNullableModifier),
"static A<object>? F3(A<object?> o)");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithNonNullableModifier),
"static A<object!>? F3(A<object?>! o)");
}
[Fact]
public void NullableReferenceTypes2()
{
var source =
@"class A<T>
{
}
class B
{
static object F1(object? o) => null!;
static object?[] F2(object[]? o) => null;
static A<object>? F3(A<object?> o) => null;
}";
var comp = (Compilation)CreateCompilation(source, parseOptions: TestOptions.Regular8);
var formatWithoutNullableModifier = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var formatWithNullableModifier = formatWithoutNullableModifier
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier)
.WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None);
var method = comp.GetMember<IMethodSymbol>("B.F1");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutNullableModifier),
"static object F1(object o)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithNullableModifier),
"static object F1(object? o)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
method = comp.GetMember<IMethodSymbol>("B.F2");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutNullableModifier),
"static object[] F2(object[] o)");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithNullableModifier),
"static object?[] F2(object[]? o)");
method = comp.GetMember<IMethodSymbol>("B.F3");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutNullableModifier),
"static A<object> F3(A<object> o)");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithNullableModifier),
"static A<object>? F3(A<object?> o)");
}
[WorkItem(31700, "https://github.com/dotnet/roslyn/issues/31700")]
[Fact]
public void NullableArrays()
{
var source =
@"#nullable enable
class C
{
static object?[,][] F1;
static object[,]?[] F2;
static object[,][]? F3;
}";
var comp = (Compilation)CreateCompilation(source, parseOptions: TestOptions.Regular8);
var formatWithoutModifiers = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var formatWithNullableModifier = formatWithoutModifiers.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
var formatWithBothModifiers = formatWithNullableModifier.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier);
var member = comp.GetMember("C.F1");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithoutModifiers),
"static object[,][] F1",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithNullableModifier),
"static object?[,][] F1",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithBothModifiers),
"static object?[]![,]! F1",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.FieldName);
member = comp.GetMember("C.F2");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithoutModifiers),
"static object[][,] F2");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithNullableModifier),
"static object[,]?[] F2");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithBothModifiers),
"static object![,]?[]! F2");
member = comp.GetMember("C.F3");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithoutModifiers),
"static object[,][] F3");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithNullableModifier),
"static object[,][]? F3");
Verify(
SymbolDisplay.ToDisplayParts(member, formatWithBothModifiers),
"static object![]![,]? F3");
}
[Fact]
public void AllowDefaultLiteral()
{
var source =
@"using System.Threading;
class C
{
void Method(CancellationToken cancellationToken = default(CancellationToken)) => throw null;
}
";
var compilation = (Compilation)CreateCompilation(source);
var formatWithoutAllowDefaultLiteral = SymbolDisplayFormat.MinimallyQualifiedFormat;
Assert.False(formatWithoutAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral));
var formatWithAllowDefaultLiteral = formatWithoutAllowDefaultLiteral.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral);
Assert.True(formatWithAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral));
var method = compilation.GetMember<IMethodSymbol>("C.Method");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutAllowDefaultLiteral),
"void C.Method(CancellationToken cancellationToken = default(CancellationToken))");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithAllowDefaultLiteral),
"void C.Method(CancellationToken cancellationToken = default)");
}
[Fact]
public void TypeParameterAnnotations_01()
{
var source =
@"#nullable enable
class C
{
T F0<T>() => default;
T? F1<T>() => default;
T F2<T>() where T : class => default;
T? F3<T>() where T : class => default;
T F4<T>() where T : class? => default;
T? F5<T>() where T : class? => default;
T F6<T>() where T : struct => default;
T? F7<T>() where T : struct => default;
T F8<T>() where T : notnull => default;
T F9<T>() where T : unmanaged => default;
}";
var comp = (Compilation)CreateCompilation(source, parseOptions: TestOptions.Regular8);
var formatWithoutModifiers = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var formatWithNullableModifier = formatWithoutModifiers.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
var formatWithBothModifiers = formatWithNullableModifier.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier);
verify("C.F0", "T F0<T>()", "T F0<T>()", "T F0<T>()");
verify("C.F1", "T F1<T>()", "T? F1<T>()", "T? F1<T>()");
verify("C.F2", "T F2<T>() where T : class", "T F2<T>() where T : class", "T! F2<T>() where T : class!");
verify("C.F3", "T F3<T>() where T : class", "T? F3<T>() where T : class", "T? F3<T>() where T : class!");
verify("C.F4", "T F4<T>() where T : class", "T F4<T>() where T : class?", "T F4<T>() where T : class?");
verify("C.F5", "T F5<T>() where T : class", "T? F5<T>() where T : class?", "T? F5<T>() where T : class?");
verify("C.F6", "T F6<T>() where T : struct", "T F6<T>() where T : struct", "T F6<T>() where T : struct");
verify("C.F7", "T? F7<T>() where T : struct", "T? F7<T>() where T : struct", "T? F7<T>() where T : struct");
verify("C.F8", "T F8<T>() where T : notnull", "T F8<T>() where T : notnull", "T F8<T>() where T : notnull");
verify("C.F9", "T F9<T>() where T : unmanaged", "T F9<T>() where T : unmanaged", "T F9<T>() where T : unmanaged");
void verify(string memberName, string withoutModifiers, string withNullableModifier, string withBothModifiers)
{
var member = comp.GetMember(memberName);
Verify(SymbolDisplay.ToDisplayParts(member, formatWithoutModifiers), withoutModifiers);
Verify(SymbolDisplay.ToDisplayParts(member, formatWithNullableModifier), withNullableModifier);
Verify(SymbolDisplay.ToDisplayParts(member, formatWithBothModifiers), withBothModifiers);
}
}
[Fact]
public void TypeParameterAnnotations_02()
{
var source =
@"#nullable enable
interface I<T> { }
class C
{
T? F<T>(T?[] x, I<T?> y) => default;
}";
var comp = (Compilation)CreateCompilation(source, parseOptions: TestOptions.Regular8);
var format = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
var method = (IMethodSymbol)comp.GetMember("C.F");
Verify(
SymbolDisplay.ToDisplayParts(method, format),
"T? F<T>(T?[] x, I<T?> y)",
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.InterfaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
var type = method.GetSymbol<MethodSymbol>().ReturnTypeWithAnnotations;
Assert.Equal("T?", type.ToDisplayString(format));
}
[Theory]
[InlineData("int", "0")]
[InlineData("string", "null")]
public void AllowDefaultLiteralNotNeeded(string type, string defaultValue)
{
var source =
$@"
class C
{{
void Method1({type} parameter = {defaultValue}) => throw null;
void Method2({type} parameter = default({type})) => throw null;
void Method3({type} parameter = default) => throw null;
}}
";
var compilation = (Compilation)CreateCompilation(source);
var formatWithoutAllowDefaultLiteral = SymbolDisplayFormat.MinimallyQualifiedFormat;
Assert.False(formatWithoutAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral));
var formatWithAllowDefaultLiteral = formatWithoutAllowDefaultLiteral.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral);
Assert.True(formatWithAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral));
var method1 = compilation.GetMember<IMethodSymbol>("C.Method1");
Verify(
SymbolDisplay.ToDisplayParts(method1, formatWithoutAllowDefaultLiteral),
$"void C.Method1({type} parameter = {defaultValue})");
Verify(
SymbolDisplay.ToDisplayParts(method1, formatWithAllowDefaultLiteral),
$"void C.Method1({type} parameter = {defaultValue})");
var method2 = compilation.GetMember<IMethodSymbol>("C.Method2");
Verify(
SymbolDisplay.ToDisplayParts(method2, formatWithoutAllowDefaultLiteral),
$"void C.Method2({type} parameter = {defaultValue})");
Verify(
SymbolDisplay.ToDisplayParts(method2, formatWithAllowDefaultLiteral),
$"void C.Method2({type} parameter = {defaultValue})");
var method3 = compilation.GetMember<IMethodSymbol>("C.Method3");
Verify(
SymbolDisplay.ToDisplayParts(method3, formatWithoutAllowDefaultLiteral),
$"void C.Method3({type} parameter = {defaultValue})");
Verify(
SymbolDisplay.ToDisplayParts(method3, formatWithAllowDefaultLiteral),
$"void C.Method3({type} parameter = {defaultValue})");
}
[Theory]
[InlineData("int", "2")]
[InlineData("string", "\"value\"")]
public void AllowDefaultLiteralNotApplicable(string type, string defaultValue)
{
var source =
$@"
class C
{{
void Method({type} parameter = {defaultValue}) => throw null;
}}
";
var compilation = (Compilation)CreateCompilation(source);
var formatWithoutAllowDefaultLiteral = SymbolDisplayFormat.MinimallyQualifiedFormat;
Assert.False(formatWithoutAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral));
var formatWithAllowDefaultLiteral = formatWithoutAllowDefaultLiteral.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral);
Assert.True(formatWithAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral));
var method = compilation.GetMember<IMethodSymbol>("C.Method");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutAllowDefaultLiteral),
$"void C.Method({type} parameter = {defaultValue})");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithAllowDefaultLiteral),
$"void C.Method({type} parameter = {defaultValue})");
}
[Fact]
public void UseLongHandValueTuple()
{
var source =
@"
class B
{
static (int, (string, long)) F1((int, int)[] t) => throw null;
}";
var comp = (Compilation)CreateCompilation(source);
var formatWithoutLongHandValueTuple = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var formatWithLongHandValueTuple = formatWithoutLongHandValueTuple.WithCompilerInternalOptions(
SymbolDisplayCompilerInternalOptions.UseValueTuple);
var method = comp.GetMember<IMethodSymbol>("B.F1");
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithoutLongHandValueTuple),
"static (int, (string, long)) F1((int, int)[] t)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(
SymbolDisplay.ToDisplayParts(method, formatWithLongHandValueTuple),
"static ValueTuple<int, ValueTuple<string, long>> F1(ValueTuple<int, int>[] t)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public void LocalFunction()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
class C
{
void M()
{
void Local() {}
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilation(srcTree);
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var local = root.DescendantNodes()
.Where(n => n.Kind() == SyntaxKind.LocalFunctionStatement)
.Single();
var localSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(local);
Assert.Equal(MethodKind.LocalFunction, localSymbol.MethodKind);
Verify(localSymbol.ToDisplayParts(SymbolDisplayFormat.TestFormat),
"void Local()",
SymbolDisplayPartKind.Keyword, // void
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // Local
SymbolDisplayPartKind.Punctuation, // (
SymbolDisplayPartKind.Punctuation); // )
}
[Fact]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public void LocalFunctionForChangeSignature()
{
SymbolDisplayFormat changeSignatureFormat = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes,
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod,
memberOptions:
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeRef);
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
class C
{
void M()
{
void Local() {}
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilation(srcTree);
var semanticModel = comp.GetSemanticModel(srcTree);
var local = root.DescendantNodes()
.Where(n => n.Kind() == SyntaxKind.LocalFunctionStatement)
.Single();
var localSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(local);
Assert.Equal(MethodKind.LocalFunction, localSymbol.MethodKind);
Verify(localSymbol.ToDisplayParts(changeSignatureFormat),
"void Local",
SymbolDisplayPartKind.Keyword, // void
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName // Local
);
}
[Fact]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public void LocalFunction2()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
using System.Threading.Tasks;
class C
{
void M()
{
async unsafe Task<int> Local(ref int* x, out char? c)
{
}
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilationWithMscorlib45(new[] { srcTree });
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var local = root.DescendantNodes()
.Where(n => n.Kind() == SyntaxKind.LocalFunctionStatement)
.Single();
var localSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(local);
Assert.Equal(MethodKind.LocalFunction, localSymbol.MethodKind);
Verify(localSymbol.ToDisplayParts(SymbolDisplayFormat.TestFormat),
"System.Threading.Tasks.Task<System.Int32> Local(ref System.Int32* x, out System.Char? c)",
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.NamespaceName, // Threading
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.NamespaceName, // Tasks
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.ClassName, // Task
SymbolDisplayPartKind.Punctuation, // <
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.StructName, // Int32
SymbolDisplayPartKind.Punctuation, // >
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // Local
SymbolDisplayPartKind.Punctuation, // (
SymbolDisplayPartKind.Keyword, // ref
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.StructName, // Int32
SymbolDisplayPartKind.Punctuation, // *
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // x
SymbolDisplayPartKind.Punctuation, // ,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // out
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.StructName, // Char
SymbolDisplayPartKind.Punctuation, // ?
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // c
SymbolDisplayPartKind.Punctuation); // )
}
[Fact]
public void RangeVariable()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
using System.Linq;
class C
{
void M()
{
var q = from x in new[] { 1, 2, 3 } where x < 3 select x;
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilation(srcTree);
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var queryExpression = root.DescendantNodes().OfType<QueryExpressionSyntax>().First();
var fromClauseRangeVariableSymbol = (IRangeVariableSymbol)semanticModel.GetDeclaredSymbol(queryExpression.FromClause);
Verify(
fromClauseRangeVariableSymbol.ToMinimalDisplayParts(
semanticModel,
queryExpression.FromClause.Identifier.SpanStart,
SymbolDisplayFormat.MinimallyQualifiedFormat),
"int x",
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.RangeVariableName); // x
}
[Fact]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public void LocalFunction3()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
using System.Threading.Tasks;
class C
{
void M()
{
async unsafe Task<int> Local(in int* x, out char? c)
{
}
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilationWithMscorlib45(new[] { srcTree });
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var local = root.DescendantNodes()
.Where(n => n.Kind() == SyntaxKind.LocalFunctionStatement)
.Single();
var localSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(local);
Assert.Equal(MethodKind.LocalFunction, localSymbol.MethodKind);
Verify(localSymbol.ToDisplayParts(SymbolDisplayFormat.TestFormat),
"System.Threading.Tasks.Task<System.Int32> Local(in System.Int32* x, out System.Char? c)",
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.NamespaceName, // Threading
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.NamespaceName, // Tasks
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.ClassName, // Task
SymbolDisplayPartKind.Punctuation, // <
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.StructName, // Int32
SymbolDisplayPartKind.Punctuation, // >
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName, // Local
SymbolDisplayPartKind.Punctuation, // (
SymbolDisplayPartKind.Keyword, // in
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.StructName, // Int32
SymbolDisplayPartKind.Punctuation, // *
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // x
SymbolDisplayPartKind.Punctuation, // ,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, // out
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName, // System
SymbolDisplayPartKind.Punctuation, // .
SymbolDisplayPartKind.StructName, // Char
SymbolDisplayPartKind.Punctuation, // ?
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName, // c
SymbolDisplayPartKind.Punctuation); // )
}
[Fact]
public void LocalVariable_01()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
class C
{
void M()
{
int x = 0;
x++;
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilation(srcTree);
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declarator = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator);
Verify(
local.ToMinimalDisplayParts(
semanticModel,
declarator.SpanStart,
SymbolDisplayFormat.MinimallyQualifiedFormat.AddLocalOptions(SymbolDisplayLocalOptions.IncludeRef)),
"int x",
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.LocalName); // x
Assert.False(local.IsRef);
Assert.Equal(RefKind.None, local.RefKind);
}
[Fact]
public void LocalVariable_02()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
class C
{
void M(int y)
{
ref int x = y;
x++;
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilation(srcTree);
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declarator = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator);
Verify(
local.ToMinimalDisplayParts(
semanticModel,
declarator.SpanStart,
SymbolDisplayFormat.MinimallyQualifiedFormat.AddLocalOptions(SymbolDisplayLocalOptions.IncludeRef)),
"ref int x",
SymbolDisplayPartKind.Keyword, //ref
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.LocalName); // x
Verify(
local.ToMinimalDisplayParts(
semanticModel,
declarator.SpanStart,
SymbolDisplayFormat.MinimallyQualifiedFormat),
"int x",
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.LocalName); // x
Assert.True(local.IsRef);
Assert.Equal(RefKind.Ref, local.RefKind);
}
[Fact]
public void LocalVariable_03()
{
var srcTree = SyntaxFactory.ParseSyntaxTree(@"
class C
{
void M(int y)
{
ref readonly int x = y;
x++;
}
}");
var root = srcTree.GetRoot();
var comp = CreateCompilation(srcTree);
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declarator = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator);
Verify(
local.ToMinimalDisplayParts(
semanticModel,
declarator.SpanStart,
SymbolDisplayFormat.MinimallyQualifiedFormat.AddLocalOptions(SymbolDisplayLocalOptions.IncludeRef)),
"ref readonly int x",
SymbolDisplayPartKind.Keyword, //ref
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, //readonly
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.LocalName); // x
Verify(
local.ToMinimalDisplayParts(
semanticModel,
declarator.SpanStart,
SymbolDisplayFormat.MinimallyQualifiedFormat),
"int x",
SymbolDisplayPartKind.Keyword, //int
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.LocalName); // x
Assert.True(local.IsRef);
Assert.Equal(RefKind.RefReadOnly, local.RefKind);
}
[Fact]
[WorkItem(22507, "https://github.com/dotnet/roslyn/issues/22507")]
public void EdgeCasesForEnumFieldComparer()
{
// A bad comparer could cause sorting the enum fields
// to throw an exception due to inconsistency. See Repro22507
// for an example of this problem.
var lhs = new EnumField("E1", 0);
var rhs = new EnumField("E2", 0x1000_0000_0000_0000);
// This is a "reverse" comparer, so if lhs < rhs, return
// value should be > 0
// If the comparer subtracts and converts, result will be zero since
// the bottom 32 bits are zero
Assert.InRange(EnumField.Comparer.Compare(lhs, rhs), 1, int.MaxValue);
lhs = new EnumField("E1", 0);
rhs = new EnumField("E2", 0x1000_0000_0000_0001);
Assert.InRange(EnumField.Comparer.Compare(lhs, rhs), 1, int.MaxValue);
lhs = new EnumField("E1", 0x1000_0000_0000_000);
rhs = new EnumField("E2", 0);
Assert.InRange(EnumField.Comparer.Compare(lhs, rhs), int.MinValue, -1);
lhs = new EnumField("E1", 0);
rhs = new EnumField("E2", 0x1000_0000_8000_0000);
Assert.InRange(EnumField.Comparer.Compare(lhs, rhs), 1, int.MaxValue);
}
[Fact]
[WorkItem(22507, "https://github.com/dotnet/roslyn/issues/22507")]
public void Repro22507()
{
var text = @"
using System;
[Flags]
enum E : long
{
A = 0x0,
B = 0x400,
C = 0x100000,
D = 0x200000,
E = 0x2000000,
F = 0x4000000,
G = 0x8000000,
H = 0x40000000,
I = 0x80000000,
J = 0x20000000000,
K = 0x40000000000,
L = 0x4000000000000,
M = 0x8000000000000,
N = 0x10000000000000,
O = 0x20000000000000,
P = 0x40000000000000,
Q = 0x2000000000000000,
}
";
TestSymbolDescription(
text,
g => g.GetTypeMembers("E").Single().GetField("A"),
SymbolDisplayFormat.MinimallyQualifiedFormat
.AddMemberOptions(SymbolDisplayMemberOptions.IncludeConstantValue),
"E.A = 0",
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EnumMemberName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NumericLiteral);
}
[Fact]
public void TestRefStructs()
{
var source = @"
ref struct X { }
namespace Nested
{
ref struct Y { }
}
";
var comp = CreateCompilation(source).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declarations = semanticModel.SyntaxTree.GetRoot().DescendantNodes().Where(n => n.Kind() == SyntaxKind.StructDeclaration).Cast<BaseTypeDeclarationSyntax>().ToArray();
Assert.Equal(2, declarations.Length);
var format = SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword);
Verify(semanticModel.GetDeclaredSymbol(declarations[0]).ToDisplayParts(format),
"ref struct X",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName);
Verify(semanticModel.GetDeclaredSymbol(declarations[1]).ToDisplayParts(format),
"ref struct Nested.Y",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName);
}
[Fact]
public void TestReadOnlyStructs()
{
var source = @"
readonly struct X { }
namespace Nested
{
readonly struct Y { }
}
";
var comp = CreateCompilation(source).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declarations = semanticModel.SyntaxTree.GetRoot().DescendantNodes().Where(n => n.Kind() == SyntaxKind.StructDeclaration).Cast<BaseTypeDeclarationSyntax>().ToArray();
Assert.Equal(2, declarations.Length);
var format = SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword);
Verify(semanticModel.GetDeclaredSymbol(declarations[0]).ToDisplayParts(format),
"readonly struct X",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName);
Verify(semanticModel.GetDeclaredSymbol(declarations[1]).ToDisplayParts(format),
"readonly struct Nested.Y",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName);
}
[Fact]
public void TestReadOnlyRefStructs()
{
var source = @"
readonly ref struct X { }
namespace Nested
{
readonly ref struct Y { }
}
";
var comp = CreateCompilation(source).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declarations = semanticModel.SyntaxTree.GetRoot().DescendantNodes().Where(n => n.Kind() == SyntaxKind.StructDeclaration).Cast<BaseTypeDeclarationSyntax>().ToArray();
Assert.Equal(2, declarations.Length);
var format = SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword);
Verify(semanticModel.GetDeclaredSymbol(declarations[0]).ToDisplayParts(format),
"readonly ref struct X",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName);
Verify(semanticModel.GetDeclaredSymbol(declarations[1]).ToDisplayParts(format),
"readonly ref struct Nested.Y",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName);
}
[Fact]
public void TestReadOnlyMembers_Malformed()
{
var source = @"
struct X
{
int P1 { }
readonly int P2 { }
readonly event System.Action E1 { }
readonly event System.Action E2 { remove { } }
}
";
var format = SymbolDisplayFormat.TestFormat
.AddMemberOptions(SymbolDisplayMemberOptions.IncludeModifiers)
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var comp = CreateCompilation(source).VerifyDiagnostics(
// (4,9): error CS0548: 'X.P1': property or indexer must have at least one accessor
// int P1 { }
Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "P1").WithArguments("X.P1").WithLocation(4, 9),
// (5,18): error CS0548: 'X.P2': property or indexer must have at least one accessor
// readonly int P2 { }
Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "P2").WithArguments("X.P2").WithLocation(5, 18),
// (6,34): error CS0065: 'X.E1': event property must have both add and remove accessors
// readonly event System.Action E1 { }
Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("X.E1").WithLocation(6, 34),
// (7,34): error CS0065: 'X.E2': event property must have both add and remove accessors
// readonly event System.Action E2 { remove { } }
Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E2").WithArguments("X.E2").WithLocation(7, 34));
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declaration = (BaseTypeDeclarationSyntax)semanticModel.SyntaxTree.GetRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.StructDeclaration);
var members = semanticModel.GetDeclaredSymbol(declaration).GetMembers();
Verify(members[0].ToDisplayParts(format), "int X.P1 { }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[1].ToDisplayParts(format), "int X.P2 { }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[2].ToDisplayParts(format), "event System.Action X.E1",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
Verify(members[3].ToDisplayParts(format), "readonly event System.Action X.E2",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
}
[Fact]
public void TestReadOnlyMembers()
{
var source = @"
struct X
{
readonly void M() { }
readonly int P1 { get => 123; }
readonly int P2 { set {} }
readonly int P3 { get => 123; set {} }
int P4 { readonly get => 123; set {} }
int P5 { get => 123; readonly set {} }
readonly event System.Action E { add {} remove {} }
}
";
var format = SymbolDisplayFormat.TestFormat
.AddMemberOptions(SymbolDisplayMemberOptions.IncludeModifiers)
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var comp = CreateCompilation(source).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declaration = (BaseTypeDeclarationSyntax)semanticModel.SyntaxTree.GetRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.StructDeclaration);
var members = semanticModel.GetDeclaredSymbol(declaration).GetMembers();
Verify(members[0].ToDisplayParts(format),
"readonly void X.M()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
Verify(members[1].ToDisplayParts(format),
"readonly int X.P1 { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[2].ToDisplayParts(format),
"readonly int X.P1.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[3].ToDisplayParts(format),
"readonly int X.P2 { set; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[4].ToDisplayParts(format),
"readonly void X.P2.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[5].ToDisplayParts(format),
"readonly int X.P3 { get; set; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[6].ToDisplayParts(format),
"readonly int X.P3.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[7].ToDisplayParts(format),
"readonly void X.P3.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[8].ToDisplayParts(format),
"int X.P4 { readonly get; set; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[9].ToDisplayParts(format),
"readonly int X.P4.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[10].ToDisplayParts(format),
"void X.P4.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[11].ToDisplayParts(format),
"int X.P5 { get; readonly set; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[12].ToDisplayParts(format),
"int X.P5.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[13].ToDisplayParts(format),
"readonly void X.P5.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[14].ToDisplayParts(format),
"readonly event System.Action X.E",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
Verify(members[15].ToDisplayParts(format),
"readonly void X.E.add",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[16].ToDisplayParts(format),
"readonly void X.E.remove",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[Fact]
public void TestReadOnlyStruct_Members()
{
var source = @"
readonly struct X
{
void M() { }
int P1 { get => 123; }
int P2 { set {} }
int P3 { get => 123; readonly set {} }
event System.Action E { add {} remove {} }
}
";
var format = SymbolDisplayFormat.TestFormat
.AddMemberOptions(SymbolDisplayMemberOptions.IncludeModifiers)
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var comp = CreateCompilation(source).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declaration = (BaseTypeDeclarationSyntax)semanticModel.SyntaxTree.GetRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.StructDeclaration);
var members = semanticModel.GetDeclaredSymbol(declaration).GetMembers();
Verify(members[0].ToDisplayParts(format),
"void X.M()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
Verify(members[1].ToDisplayParts(format),
"int X.P1 { get; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[2].ToDisplayParts(format),
"int X.P1.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[3].ToDisplayParts(format),
"int X.P2 { set; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[4].ToDisplayParts(format),
"void X.P2.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[5].ToDisplayParts(format),
"int X.P3 { get; set; }",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation);
Verify(members[6].ToDisplayParts(format),
"int X.P3.get",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[7].ToDisplayParts(format),
"void X.P3.set",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[8].ToDisplayParts(format),
"event System.Action X.E",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName);
Verify(members[9].ToDisplayParts(format),
"void X.E.add",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
Verify(members[10].ToDisplayParts(format),
"void X.E.remove",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword);
}
[Theory, MemberData(nameof(FileScopedOrBracedNamespace))]
public void TestReadOnlyStruct_Nested(string ob, string cb)
{
var source = @"
namespace Nested
" + ob + @"
struct X
{
readonly void M() { }
}
" + cb + @"
";
var format = SymbolDisplayFormat.TestFormat
.AddMemberOptions(SymbolDisplayMemberOptions.IncludeModifiers)
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithFileScopedNamespaces).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var declaration = (BaseTypeDeclarationSyntax)semanticModel.SyntaxTree.GetRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.StructDeclaration);
var members = semanticModel.GetDeclaredSymbol(declaration).GetMembers();
Verify(members[0].ToDisplayParts(format),
"readonly void Nested.X.M()",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation);
}
[Fact]
public void TestPassingVBSymbolsToStructSymbolDisplay()
{
var source = @"
Structure X
End Structure";
var comp = CreateVisualBasicCompilation(source).VerifyDiagnostics();
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var structure = semanticModel.SyntaxTree.GetRoot().DescendantNodes().Single(n => n.RawKind == (int)VisualBasic.SyntaxKind.StructureStatement);
var format = SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword);
Verify(SymbolDisplay.ToDisplayParts(semanticModel.GetDeclaredSymbol(structure), format),
"struct X",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName);
}
[Fact]
public void EnumConstraint_Type()
{
TestSymbolDescription(
"class X<T> where T : System.Enum { }",
global => global.GetTypeMember("X"),
SymbolDisplayFormat.TestFormat.WithGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints),
"X<T> where T : System.Enum",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void EnumConstraint()
{
TestSymbolDescription(
"class X<T> where T : System.Enum { }",
global => global.GetTypeMember("X").TypeParameters.Single().ConstraintTypes().Single(),
SymbolDisplayFormat.TestFormat,
"System.Enum",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void DelegateConstraint_Type()
{
TestSymbolDescription(
"class X<T> where T : System.Delegate { }",
global => global.GetTypeMember("X"),
SymbolDisplayFormat.TestFormat.WithGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints),
"X<T> where T : System.Delegate",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void DelegateConstraint()
{
TestSymbolDescription(
"class X<T> where T : System.Delegate { }",
global => global.GetTypeMember("X").TypeParameters.Single().ConstraintTypes().Single(),
SymbolDisplayFormat.TestFormat,
"System.Delegate",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void MulticastDelegateConstraint_Type()
{
TestSymbolDescription(
"class X<T> where T : System.MulticastDelegate { }",
global => global.GetTypeMember("X"),
SymbolDisplayFormat.TestFormat.WithGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints),
"X<T> where T : System.MulticastDelegate",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void MulticastDelegateConstraint()
{
TestSymbolDescription(
"class X<T> where T : System.MulticastDelegate { }",
global => global.GetTypeMember("X").TypeParameters.Single().ConstraintTypes().Single(),
SymbolDisplayFormat.TestFormat,
"System.MulticastDelegate",
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void UnmanagedConstraint_Type()
{
TestSymbolDescription(
"class X<T> where T : unmanaged { }",
global => global.GetTypeMember("X"),
SymbolDisplayFormat.TestFormat.AddGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeConstraints),
"X<T> where T : unmanaged",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword);
}
[Fact]
public void UnmanagedConstraint_Method()
{
TestSymbolDescription(@"
class X
{
void M<T>() where T : unmanaged, System.IDisposable { }
}",
global => global.GetTypeMember("X").GetMethod("M"),
SymbolDisplayFormat.TestFormat.AddGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeConstraints),
"void X.M<T>() where T : unmanaged, System.IDisposable",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.InterfaceName);
}
[Fact]
public void UnmanagedConstraint_Delegate()
{
TestSymbolDescription(
"delegate void D<T>() where T : unmanaged;",
global => global.GetTypeMember("D"),
SymbolDisplayFormat.TestFormat.AddGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeConstraints),
"D<T> where T : unmanaged",
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword);
}
[Fact, WorkItem(27104, "https://github.com/dotnet/roslyn/issues/27104")]
public void BadDiscardInForeachLoop_01()
{
var source = @"
class C
{
void M()
{
foreach(_ in """")
{
}
}
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,17): error CS8186: A foreach loop must declare its iteration variables.
// foreach(_ in "")
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "_").WithLocation(6, 17)
);
var tree = compilation.SyntaxTrees[0];
var variable = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single().Variable;
var model = compilation.GetSemanticModel(tree);
var symbol = model.GetSymbolInfo(variable).Symbol;
Verify(
symbol.ToMinimalDisplayParts(model, variable.SpanStart),
"var _",
SymbolDisplayPartKind.ErrorTypeName, // var
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Punctuation); // _
}
[Fact]
public void ClassConstructorDeclaration()
{
TestSymbolDescription(
@"class C
{
C() { }
}",
global => global.GetTypeMember("C").Constructors[0],
new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType),
"C.C",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void ClassDestructorDeclaration()
{
TestSymbolDescription(
@"class C
{
~C() { }
}",
global => global.GetTypeMember("C").GetMember("Finalize"),
new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType),
"C.~C",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void ClassStaticConstructorDeclaration()
{
TestSymbolDescription(
@"class C
{
static C() { }
}",
global => global.GetTypeMember("C").Constructors[0],
new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType),
"C.C",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void ClassStaticDestructorDeclaration()
{
TestSymbolDescription(
@"class C
{
static ~C() { }
}",
global => global.GetTypeMember("C").GetMember("Finalize"),
new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType),
"C.~C",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void ClassConstructorInvocation()
{
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType);
var source =
@"class C
{
C()
{
var c = new C();
}
}";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var constructor = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
var symbol = model.GetSymbolInfo(constructor).Symbol;
Verify(
symbol.ToMinimalDisplayParts(model, constructor.SpanStart, format),
"C.C",
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.ClassName);
}
[Fact]
public void StructConstructorDeclaration()
{
TestSymbolDescription(
@"struct S
{
int i;
S(int i)
{
this.i = i;
}
}",
global => global.GetTypeMember("S").Constructors[0],
new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType),
"S.S",
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName);
}
[Fact]
public void StructConstructorInvocation()
{
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeContainingType);
var source =
@"struct S
{
int i;
public S(int i)
{
this.i = i;
}
}
class C
{
C()
{
var s = new S(1);
}
}";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var constructor = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
var symbol = model.GetSymbolInfo(constructor).Symbol;
Verify(
symbol.ToMinimalDisplayParts(model, constructor.SpanStart, format),
"S.S",
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName);
}
[Fact]
[WorkItem(38794, "https://github.com/dotnet/roslyn/issues/38794")]
public void LinqGroupVariableDeclaration()
{
var source =
@"using System.Linq;
class C
{
void M(string[] a)
{
var v = from x in a
group x by x.Length into g
select g;
}
}";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var continuation = tree.GetRoot().DescendantNodes().OfType<QueryContinuationSyntax>().Single();
var symbol = model.GetDeclaredSymbol(continuation);
Verify(
symbol.ToMinimalDisplayParts(model, continuation.Identifier.SpanStart),
"IGrouping<int, string> g",
SymbolDisplayPartKind.InterfaceName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.RangeVariableName);
}
[Fact]
public void NativeInt()
{
var source =
@"using System;
class A<T>
{
}
class B
{
static void F1(nint x, nuint y) { }
static void F2(nint x, IntPtr y) { }
static void F3(nint? x, UIntPtr? y) { }
static void F4(nint[] x, A<nuint> y) { }
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular9);
var formatWithoutOptions = new SymbolDisplayFormat(
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
var formatWithUnderlyingTypes = formatWithoutOptions.WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.UseNativeIntegerUnderlyingType);
var method = comp.GetMember<MethodSymbol>("B.F1");
Verify(
method.ToDisplayParts(formatWithUnderlyingTypes),
"static void F1(IntPtr x, UIntPtr y)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(
method.ToDisplayParts(formatWithoutOptions),
"static void F1(nint x, nuint y)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.Punctuation);
Verify(
method.ToDisplayParts(formatWithoutOptions.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes)),
"static void F1(nint x, nuint y)");
method = comp.GetMember<MethodSymbol>("B.F2");
Verify(
method.ToDisplayParts(formatWithUnderlyingTypes),
"static void F2(IntPtr x, IntPtr y)");
Verify(
method.ToDisplayParts(formatWithoutOptions),
"static void F2(nint x, IntPtr y)");
method = comp.GetMember<MethodSymbol>("B.F3");
Verify(
method.ToDisplayParts(formatWithUnderlyingTypes),
"static void F3(IntPtr? x, UIntPtr? y)");
Verify(
method.ToDisplayParts(formatWithoutOptions),
"static void F3(nint? x, UIntPtr? y)");
method = comp.GetMember<MethodSymbol>("B.F4");
Verify(
method.ToDisplayParts(formatWithUnderlyingTypes),
"static void F4(IntPtr[] x, A<UIntPtr> y)");
Verify(
method.ToDisplayParts(formatWithoutOptions),
"static void F4(nint[] x, A<nuint> y)");
}
[Fact]
public void RecordDeclaration()
{
var text = @"
record Person(string First, string Last);
";
Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("Person").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType, kindOptions: SymbolDisplayKindOptions.IncludeTypeKeyword);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
"record Person",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.RecordClassName);
}
[Fact]
public void RecordClassDeclaration()
{
var text = @"
record class Person(string First, string Last);
";
Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("Person").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType, kindOptions: SymbolDisplayKindOptions.IncludeTypeKeyword);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
"record Person",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.RecordClassName);
}
[Fact]
public void RecordStructDeclaration()
{
var text = @"
record struct Person(string First, string Last);
";
Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("Person").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType, kindOptions: SymbolDisplayKindOptions.IncludeTypeKeyword);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular10,
"record struct Person",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.RecordStructName);
}
[Fact]
public void ReadOnlyRecordStructDeclaration()
{
var text = @"
readonly record struct Person(string First, string Last);
";
Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("Person").Single();
var format = new SymbolDisplayFormat(memberOptions: SymbolDisplayMemberOptions.IncludeType, kindOptions: SymbolDisplayKindOptions.IncludeTypeKeyword);
TestSymbolDescription(
text,
findSymbol,
format,
TestOptions.Regular10,
"readonly record struct Person",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.RecordStructName);
}
[Fact, WorkItem(51222, "https://github.com/dotnet/roslyn/issues/51222")]
public void TestFunctionPointerWithoutIncludeTypesInParameterOptions()
{
var text = @"
class A {
delegate*<int, string> f;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
((FieldSymbol)global.GetTypeMembers("A", 0).Single()
.GetMembers("f").Single()).Type;
var format = new SymbolDisplayFormat();
TestSymbolDescription(
text,
findSymbol,
format,
"delegate*<Int32, String>");
}
[Fact, WorkItem(51222, "https://github.com/dotnet/roslyn/issues/51222")]
public void TestFunctionPointerWithTupleParameter()
{
var text = @"
class A {
delegate*<(int, string), void> f;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
((FieldSymbol)global.GetTypeMembers("A", 0).Single()
.GetMembers("f").Single()).Type;
var format = new SymbolDisplayFormat();
TestSymbolDescription(
text,
findSymbol,
format,
"delegate*<(Int32, String), Void>");
}
[Fact, WorkItem(51222, "https://github.com/dotnet/roslyn/issues/51222")]
public void TestFunctionPointerWithTupleParameterWithNames()
{
var text = @"
class A {
delegate*<(int i, string s), (int i, string s)> f;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
((FieldSymbol)global.GetTypeMembers("A", 0).Single()
.GetMembers("f").Single()).Type;
var format = new SymbolDisplayFormat();
TestSymbolDescription(
text,
findSymbol,
format,
"delegate*<(Int32 i, String s), (Int32 i, String s)>");
}
[Fact, WorkItem(51222, "https://github.com/dotnet/roslyn/issues/51222")]
public void TestFunctionPointerWithRefParameters()
{
var text = @"
class A {
delegate*<in int, ref readonly string> f;
}";
Func<NamespaceSymbol, Symbol> findSymbol = global =>
((FieldSymbol)global.GetTypeMembers("A", 0).Single()
.GetMembers("f").Single()).Type;
var format = new SymbolDisplayFormat();
TestSymbolDescription(
text,
findSymbol,
format,
"delegate*<in Int32, ref readonly String>");
}
[Fact]
public void TestSynthesizedAnonymousDelegateType1()
{
var source = @"
class C
{
void M()
{
var v = (ref int i) => i.ToString();
}
}
";
var comp = CreateCompilation(source);
var semanticModel = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var syntaxTree = semanticModel.SyntaxTree;
var declaration = (LocalDeclarationStatementSyntax)semanticModel.SyntaxTree.GetRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.LocalDeclarationStatement);
var type = semanticModel.GetTypeInfo(declaration.Declaration.Type).Type;
Verify(type.ToDisplayParts(), "<anonymous delegate>",
SymbolDisplayPartKind.DelegateName);
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword);
Verify(type.ToDisplayParts(format), "delegate string <anonymous delegate>(ref int)",
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.Punctuation,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Space,
SymbolDisplayPartKind.Keyword,
SymbolDisplayPartKind.Punctuation);
}
}
}
| 1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/EditorFeatures/CSharpTest/QuickInfo/SemanticQuickInfoSourceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo
{
public class SemanticQuickInfoSourceTests : AbstractSemanticQuickInfoSourceTests
{
private static async Task TestWithOptionsAsync(CSharpParseOptions options, string markup, params Action<QuickInfoItem>[] expectedResults)
{
using var workspace = TestWorkspace.CreateCSharp(markup, options);
await TestWithOptionsAsync(workspace, expectedResults);
}
private static async Task TestWithOptionsAsync(CSharpCompilationOptions options, string markup, params Action<QuickInfoItem>[] expectedResults)
{
using var workspace = TestWorkspace.CreateCSharp(markup, compilationOptions: options);
await TestWithOptionsAsync(workspace, expectedResults);
}
private static async Task TestWithOptionsAsync(TestWorkspace workspace, params Action<QuickInfoItem>[] expectedResults)
{
var testDocument = workspace.DocumentWithCursor;
var position = testDocument.CursorPosition.GetValueOrDefault();
var documentId = workspace.GetDocumentId(testDocument);
var document = workspace.CurrentSolution.GetDocument(documentId);
var service = QuickInfoService.GetService(document);
await TestWithOptionsAsync(document, service, position, expectedResults);
// speculative semantic model
if (await CanUseSpeculativeSemanticModelAsync(document, position))
{
var buffer = testDocument.GetTextBuffer();
using (var edit = buffer.CreateEdit())
{
var currentSnapshot = buffer.CurrentSnapshot;
edit.Replace(0, currentSnapshot.Length, currentSnapshot.GetText());
edit.Apply();
}
await TestWithOptionsAsync(document, service, position, expectedResults);
}
}
private static async Task TestWithOptionsAsync(Document document, QuickInfoService service, int position, Action<QuickInfoItem>[] expectedResults)
{
var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None);
if (expectedResults.Length == 0)
{
Assert.Null(info);
}
else
{
Assert.NotNull(info);
foreach (var expected in expectedResults)
{
expected(info);
}
}
}
private static async Task VerifyWithMscorlib45Async(string markup, Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""C#"" CommonReferencesNet45=""true"">
<Document FilePath=""SourceDocument"">
{0}
</Document>
</Project>
</Workspace>", SecurityElement.Escape(markup));
using var workspace = TestWorkspace.Create(xmlString);
var position = workspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = workspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id;
var document = workspace.CurrentSolution.GetDocument(documentId);
var service = QuickInfoService.GetService(document);
var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None);
if (expectedResults.Length == 0)
{
Assert.Null(info);
}
else
{
Assert.NotNull(info);
foreach (var expected in expectedResults)
{
expected(info);
}
}
}
protected override async Task TestAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
await TestWithOptionsAsync(Options.Regular, markup, expectedResults);
await TestWithOptionsAsync(Options.Script, markup, expectedResults);
}
private async Task TestWithUsingsAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
var markupWithUsings =
@"using System;
using System.Collections.Generic;
using System.Linq;
" + markup;
await TestAsync(markupWithUsings, expectedResults);
}
private Task TestInClassAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
var markupInClass = "class C { " + markup + " }";
return TestWithUsingsAsync(markupInClass, expectedResults);
}
private Task TestInMethodAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
var markupInMethod = "class C { void M() { " + markup + " } }";
return TestWithUsingsAsync(markupInMethod, expectedResults);
}
private static async Task TestWithReferenceAsync(string sourceCode,
string referencedCode,
string sourceLanguage,
string referencedLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
await TestWithMetadataReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults);
await TestWithProjectReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults);
// Multi-language projects are not supported.
if (sourceLanguage == referencedLanguage)
{
await TestInSameProjectHelperAsync(sourceCode, referencedCode, sourceLanguage, expectedResults);
}
}
private static async Task TestWithMetadataReferenceHelperAsync(
string sourceCode,
string referencedCode,
string sourceLanguage,
string referencedLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</MetadataReferenceFromSource>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyWithReferenceWorkerAsync(xmlString, expectedResults);
}
private static async Task TestWithProjectReferenceHelperAsync(
string sourceCode,
string referencedCode,
string sourceLanguage,
string referencedLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<ProjectReference>ReferencedProject</ProjectReference>
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
<Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyWithReferenceWorkerAsync(xmlString, expectedResults);
}
private static async Task TestInSameProjectHelperAsync(
string sourceCode,
string referencedCode,
string sourceLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<Document FilePath=""ReferencedDocument"">
{2}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode));
await VerifyWithReferenceWorkerAsync(xmlString, expectedResults);
}
private static async Task VerifyWithReferenceWorkerAsync(string xmlString, params Action<QuickInfoItem>[] expectedResults)
{
using var workspace = TestWorkspace.Create(xmlString);
var position = workspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = workspace.Documents.First(d => d.Name == "SourceDocument").Id;
var document = workspace.CurrentSolution.GetDocument(documentId);
var service = QuickInfoService.GetService(document);
var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None);
if (expectedResults.Length == 0)
{
Assert.Null(info);
}
else
{
Assert.NotNull(info);
foreach (var expected in expectedResults)
{
expected(info);
}
}
}
protected async Task TestInvalidTypeInClassAsync(string code)
{
var codeInClass = "class C { " + code + " }";
await TestAsync(codeInClass);
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirective()
{
await TestAsync(
@"using $$System;",
MainDescription("namespace System"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirective2()
{
await TestAsync(
@"using System.Coll$$ections.Generic;",
MainDescription("namespace System.Collections"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirective3()
{
await TestAsync(
@"using System.L$$inq;",
MainDescription("namespace System.Linq"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirectiveWithAlias()
{
await TestAsync(
@"using Goo = Sys$$tem.Console;",
MainDescription("namespace System"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeInUsingDirectiveWithAlias()
{
await TestAsync(
@"using Goo = System.Con$$sole;",
MainDescription("class System.Console"));
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationInUsingDirectiveWithAlias()
{
var markup =
@"using I$$ = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation("summary for interface IGoo"));
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationInUsingDirectiveWithAlias2()
{
var markup =
@"using I = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo { }
class C : I$$ { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation("summary for interface IGoo"));
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationInUsingDirectiveWithAlias3()
{
var markup =
@"using I = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo
{
void Goo();
}
class C : I$$ { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation("summary for interface IGoo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestThis()
{
var markup =
@"
///<summary>summary for Class C</summary>
class C { string M() { return thi$$s.ToString(); } }";
await TestWithUsingsAsync(markup,
MainDescription("class C"),
Documentation("summary for Class C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestClassWithDocComment()
{
var markup =
@"
///<summary>Hello!</summary>
class C { void M() { $$C obj; } }";
await TestAsync(markup,
MainDescription("class C"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestSingleLineDocComments()
{
// Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedSingleLineComment
// SingleLine doc comment with leading whitespace
await TestAsync(
@"///<summary>Hello!</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with space before opening tag
await TestAsync(
@"/// <summary>Hello!</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with space before opening tag and leading whitespace
await TestAsync(
@"/// <summary>Hello!</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with leading whitespace and blank line
await TestAsync(
@"///<summary>Hello!
///</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with '\r' line separators
await TestAsync("///<summary>Hello!\r///</summary>\rclass C { void M() { $$C obj; } }",
MainDescription("class C"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMultiLineDocComments()
{
// Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedMultiLineComment
// Multiline doc comment with leading whitespace
await TestAsync(
@"/**<summary>Hello!</summary>*/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with space before opening tag
await TestAsync(
@"/** <summary>Hello!</summary>
**/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with space before opening tag and leading whitespace
await TestAsync(
@"/**
** <summary>Hello!</summary>
**/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with no per-line prefix
await TestAsync(
@"/**
<summary>
Hello!
</summary>
*/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with inconsistent per-line prefix
await TestAsync(
@"/**
** <summary>
Hello!</summary>
**
**/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with closing comment on final line
await TestAsync(
@"/**
<summary>Hello!
</summary>*/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with '\r' line separators
await TestAsync("/**\r* <summary>\r* Hello!\r* </summary>\r*/\rclass C { void M() { $$C obj; } }",
MainDescription("class C"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMethodWithDocComment()
{
var markup =
@"
///<summary>Hello!</summary>
void M() { M$$() }";
await TestInClassAsync(markup,
MainDescription("void C.M()"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInt32()
{
await TestInClassAsync(
@"$$Int32 i;",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInInt()
{
await TestInClassAsync(
@"$$int i;",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestString()
{
await TestInClassAsync(
@"$$String s;",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInString()
{
await TestInClassAsync(
@"$$string s;",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInStringAtEndOfToken()
{
await TestInClassAsync(
@"string$$ s;",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBoolean()
{
await TestInClassAsync(
@"$$Boolean b;",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInBool()
{
await TestInClassAsync(
@"$$bool b;",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestSingle()
{
await TestInClassAsync(
@"$$Single s;",
MainDescription("struct System.Single"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInFloat()
{
await TestInClassAsync(
@"$$float f;",
MainDescription("struct System.Single"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVoidIsInvalid()
{
await TestInvalidTypeInClassAsync(
@"$$void M()
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidPointer1_931958()
{
await TestInvalidTypeInClassAsync(
@"$$T* i;");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidPointer2_931958()
{
await TestInvalidTypeInClassAsync(
@"T$$* i;");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidPointer3_931958()
{
await TestInvalidTypeInClassAsync(
@"T*$$ i;");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestListOfString()
{
await TestInClassAsync(
@"$$List<string> l;",
MainDescription("class System.Collections.Generic.List<T>"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} string"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestListOfSomethingFromSource()
{
var markup =
@"
///<summary>Generic List</summary>
public class GenericList<T> { Generic$$List<int> t; }";
await TestAsync(markup,
MainDescription("class GenericList<T>"),
Documentation("Generic List"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestListOfT()
{
await TestInMethodAsync(
@"class C<T>
{
$$List<T> l;
}",
MainDescription("class System.Collections.Generic.List<T>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDictionaryOfIntAndString()
{
await TestInClassAsync(
@"$$Dictionary<int, string> d;",
MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"),
TypeParameterMap(
Lines($"\r\nTKey {FeaturesResources.is_} int",
$"TValue {FeaturesResources.is_} string")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDictionaryOfTAndU()
{
await TestInMethodAsync(
@"class C<T, U>
{
$$Dictionary<T, U> d;
}",
MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"),
TypeParameterMap(
Lines($"\r\nTKey {FeaturesResources.is_} T",
$"TValue {FeaturesResources.is_} U")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIEnumerableOfInt()
{
await TestInClassAsync(
@"$$IEnumerable<int> M()
{
yield break;
}",
MainDescription("interface System.Collections.Generic.IEnumerable<out T>"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventHandler()
{
await TestInClassAsync(
@"event $$EventHandler e;",
MainDescription("delegate void System.EventHandler(object sender, System.EventArgs e)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter()
{
await TestAsync(
@"class C<T>
{
$$T t;
}",
MainDescription($"T {FeaturesResources.in_} C<T>"));
}
[WorkItem(538636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538636")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameterWithDocComment()
{
var markup =
@"
///<summary>Hello!</summary>
///<typeparam name=""T"">T is Type Parameter</typeparam>
class C<T> { $$T t; }";
await TestAsync(markup,
MainDescription($"T {FeaturesResources.in_} C<T>"),
Documentation("T is Type Parameter"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter1_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
$$T11 t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter2_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
T$$11 t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter3_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
T1$$1 t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter4_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
T11$$ t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullableOfInt()
{
await TestInClassAsync(@"$$Nullable<int> i; }",
MainDescription("struct System.Nullable<T> where T : struct"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeDeclaredOnMethod1_Bug1946()
{
await TestAsync(
@"class C
{
static void Meth1<T1>($$T1 i) where T1 : struct
{
T1 i;
}
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeDeclaredOnMethod2_Bug1946()
{
await TestAsync(
@"class C
{
static void Meth1<T1>(T1 i) where $$T1 : struct
{
T1 i;
}
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeDeclaredOnMethod3_Bug1946()
{
await TestAsync(
@"class C
{
static void Meth1<T1>(T1 i) where T1 : struct
{
$$T1 i;
}
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Class()
{
await TestAsync(
@"class C<T> where $$T : class
{
}",
MainDescription($"T {FeaturesResources.in_} C<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Struct()
{
await TestAsync(
@"struct S<T> where $$T : class
{
}",
MainDescription($"T {FeaturesResources.in_} S<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Interface()
{
await TestAsync(
@"interface I<T> where $$T : class
{
}",
MainDescription($"T {FeaturesResources.in_} I<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Delegate()
{
await TestAsync(
@"delegate void D<T>() where $$T : class;",
MainDescription($"T {FeaturesResources.in_} D<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMinimallyQualifiedConstraint()
{
await TestAsync(@"class C<T> where $$T : IEnumerable<int>",
MainDescription($"T {FeaturesResources.in_} C<T> where T : IEnumerable<int>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FullyQualifiedConstraint()
{
await TestAsync(@"class C<T> where $$T : System.Collections.Generic.IEnumerable<int>",
MainDescription($"T {FeaturesResources.in_} C<T> where T : System.Collections.Generic.IEnumerable<int>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMethodReferenceInSameMethod()
{
await TestAsync(
@"class C
{
void M()
{
M$$();
}
}",
MainDescription("void C.M()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMethodReferenceInSameMethodWithDocComment()
{
var markup =
@"
///<summary>Hello World</summary>
void M() { M$$(); }";
await TestInClassAsync(markup,
MainDescription("void C.M()"),
Documentation("Hello World"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodBuiltIn()
{
var markup =
@"int field;
void M()
{
field$$
}";
await TestInClassAsync(markup,
MainDescription($"({FeaturesResources.field}) int C.field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodBuiltIn2()
{
await TestInClassAsync(
@"int field;
void M()
{
int f = field$$;
}",
MainDescription($"({FeaturesResources.field}) int C.field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodBuiltInWithFieldInitializer()
{
await TestInClassAsync(
@"int field = 1;
void M()
{
int f = field $$;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn()
{
await TestInMethodAsync(
@"int x;
x = x$$+1;",
MainDescription("int int.operator +(int left, int right)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn1()
{
await TestInMethodAsync(
@"int x;
x = x$$ + 1;",
MainDescription($"({FeaturesResources.local_variable}) int x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn2()
{
await TestInMethodAsync(
@"int x;
x = x+$$x;",
MainDescription($"({FeaturesResources.local_variable}) int x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn3()
{
await TestInMethodAsync(
@"int x;
x = x +$$ x;",
MainDescription("int int.operator +(int left, int right)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn4()
{
await TestInMethodAsync(
@"int x;
x = x + $$x;",
MainDescription($"({FeaturesResources.local_variable}) int x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorCustomTypeBuiltIn()
{
var markup =
@"class C
{
static void M() { C c; c = c +$$ c; }
}";
await TestAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorCustomTypeOverload()
{
var markup =
@"class C
{
static void M() { C c; c = c +$$ c; }
static C operator+(C a, C b) { return a; }
}";
await TestAsync(markup,
MainDescription("C C.operator +(C a, C b)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodMinimal()
{
var markup =
@"DateTime field;
void M()
{
field$$
}";
await TestInClassAsync(markup,
MainDescription($"({FeaturesResources.field}) DateTime C.field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodQualified()
{
var markup =
@"System.IO.FileInfo file;
void M()
{
file$$
}";
await TestInClassAsync(markup,
MainDescription($"({FeaturesResources.field}) System.IO.FileInfo C.file"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructFromSource()
{
var markup =
@"struct MyStruct {
public static int SomeField; }
static class Test { int a = MyStruct.Some$$Field; }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"));
}
[WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructFromSourceWithDocComment()
{
var markup =
@"struct MyStruct {
///<summary>My Field</summary>
public static int SomeField; }
static class Test { int a = MyStruct.Some$$Field; }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"),
Documentation("My Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructInsideMethodFromSource()
{
var markup =
@"struct MyStruct {
public static int SomeField; }
static class Test { static void Method() { int a = MyStruct.Some$$Field; } }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"));
}
[WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructInsideMethodFromSourceWithDocComment()
{
var markup =
@"struct MyStruct {
///<summary>My Field</summary>
public static int SomeField; }
static class Test { static void Method() { int a = MyStruct.Some$$Field; } }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"),
Documentation("My Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldMinimal()
{
await TestInMethodAsync(@"DateTime dt = DateTime.MaxValue$$",
MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldQualified1()
{
// NOTE: we qualify the field type, but not the type that contains the field in Dev10
var markup =
@"class C {
void M()
{
DateTime dt = System.DateTime.MaxValue$$
}
}";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldQualified2()
{
await TestAsync(
@"class C
{
void M()
{
DateTime dt = System.DateTime.MaxValue$$
}
}",
MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldQualified3()
{
await TestAsync(
@"using System;
class C
{
void M()
{
DateTime dt = System.DateTime.MaxValue$$
}
}",
MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ConstructedGenericField()
{
await TestAsync(
@"class C<T>
{
public T Field;
}
class D
{
void M()
{
new C<int>().Fi$$eld.ToString();
}
}",
MainDescription($"({FeaturesResources.field}) int C<int>.Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnconstructedGenericField()
{
await TestAsync(
@"class C<T>
{
public T Field;
void M()
{
Fi$$eld.ToString();
}
}",
MainDescription($"({FeaturesResources.field}) T C<T>.Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIntegerLiteral()
{
await TestInMethodAsync(@"int f = 37$$",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTrueKeyword()
{
await TestInMethodAsync(@"bool f = true$$",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFalseKeyword()
{
await TestInMethodAsync(@"bool f = false$$",
MainDescription("struct System.Boolean"));
}
[WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullLiteral()
{
await TestInMethodAsync(@"string f = null$$",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullLiteralWithVar()
=> await TestInMethodAsync(@"var f = null$$");
[WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDefaultLiteral()
{
await TestInMethodAsync(@"string f = default$$",
MainDescription("class System.String"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitKeywordOnGenericTaskReturningAsync()
{
var markup = @"using System.Threading.Tasks;
class C
{
public async Task<int> Calc()
{
aw$$ait Calc();
return 5;
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32")));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitKeywordInDeclarationStatement()
{
var markup = @"using System.Threading.Tasks;
class C
{
public async Task<int> Calc()
{
var x = $$await Calc();
return 5;
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32")));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitKeywordOnTaskReturningAsync()
{
var markup = @"using System.Threading.Tasks;
class C
{
public async void Calc()
{
aw$$ait Task.Delay(100);
}
}";
await TestAsync(markup, MainDescription(FeaturesResources.Awaited_task_returns_no_value));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNestedAwaitKeywords1()
{
var markup = @"using System;
using System.Threading.Tasks;
class AsyncExample2
{
async Task<Task<int>> AsyncMethod()
{
return NewMethod();
}
private static Task<int> NewMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await await AsyncMethod();
};
int result = await await AsyncMethod();
Task<Task<int>> resultTask = AsyncMethod();
result = await awa$$it resultTask;
result = await lambda();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, $"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>")),
TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNestedAwaitKeywords2()
{
var markup = @"using System;
using System.Threading.Tasks;
class AsyncExample2
{
async Task<Task<int>> AsyncMethod()
{
return NewMethod();
}
private static Task<int> NewMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await await AsyncMethod();
};
int result = await await AsyncMethod();
Task<Task<int>> resultTask = AsyncMethod();
result = awa$$it await resultTask;
result = await lambda();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32")));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitablePrefixOnCustomAwaiter()
{
var markup = @"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Z = $$C;
class C
{
public MyAwaiter GetAwaiter() { throw new NotImplementedException(); }
}
class MyAwaiter : INotifyCompletion
{
public void OnCompleted(Action continuation)
{
throw new NotImplementedException();
}
public bool IsCompleted { get { throw new NotImplementedException(); } }
public void GetResult() { }
}";
await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class C"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTaskType()
{
var markup = @"using System.Threading.Tasks;
class C
{
public void Calc()
{
Task$$ v1;
}
}";
await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTaskOfTType()
{
var markup = @"using System;
using System.Threading.Tasks;
class C
{
public void Calc()
{
Task$$<int> v1;
}
}";
await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>"),
TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int"));
}
[WorkItem(7100, "https://github.com/dotnet/roslyn/issues/7100")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDynamicIsntAwaitable()
{
var markup = @"
class C
{
dynamic D() { return null; }
void M()
{
D$$();
}
}
";
await TestAsync(markup, MainDescription("dynamic C.D()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStringLiteral()
{
await TestInMethodAsync(@"string f = ""Goo""$$",
MainDescription("class System.String"));
}
[WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVerbatimStringLiteral()
{
await TestInMethodAsync(@"string f = @""cat""$$",
MainDescription("class System.String"));
}
[WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInterpolatedStringLiteral()
{
await TestInMethodAsync(@"string f = $""cat""$$", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $""c$$at""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $""$$cat""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $""cat {1$$ + 2} dog""", MainDescription("struct System.Int32"));
}
[WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVerbatimInterpolatedStringLiteral()
{
await TestInMethodAsync(@"string f = $@""cat""$$", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $@""c$$at""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $@""$$cat""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $@""cat {1$$ + 2} dog""", MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCharLiteral()
{
await TestInMethodAsync(@"string f = 'x'$$",
MainDescription("struct System.Char"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DynamicKeyword()
{
await TestInMethodAsync(
@"dyn$$amic dyn;",
MainDescription("dynamic"),
Documentation(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DynamicField()
{
await TestInClassAsync(
@"dynamic dyn;
void M()
{
d$$yn.Goo();
}",
MainDescription($"({FeaturesResources.field}) dynamic C.dyn"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Minimal()
{
await TestInClassAsync(
@"DateTime Prop { get; set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("DateTime C.Prop { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Minimal_PrivateSet()
{
await TestInClassAsync(
@"public DateTime Prop { get; private set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("DateTime C.Prop { get; private set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Minimal_PrivateSet1()
{
await TestInClassAsync(
@"protected internal int Prop { get; private set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("int C.Prop { get; private set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Qualified()
{
await TestInClassAsync(
@"System.IO.FileInfo Prop { get; set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("System.IO.FileInfo C.Prop { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NonLocalProperty_Minimal()
{
await TestInMethodAsync(@"DateTime.No$$w.ToString();",
MainDescription("DateTime DateTime.Now { get; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NonLocalProperty_Qualified()
{
await TestInMethodAsync(
@"System.IO.FileInfo f;
f.Att$$ributes.ToString();",
MainDescription("System.IO.FileAttributes System.IO.FileSystemInfo.Attributes { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ConstructedGenericProperty()
{
await TestAsync(
@"class C<T>
{
public T Property { get; set }
}
class D
{
void M()
{
new C<int>().Pro$$perty.ToString();
}
}",
MainDescription("int C<int>.Property { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnconstructedGenericProperty()
{
await TestAsync(
@"class C<T>
{
public T Property { get; set}
void M()
{
Pro$$perty.ToString();
}
}",
MainDescription("T C<T>.Property { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueInProperty()
{
await TestInClassAsync(
@"public DateTime Property
{
set
{
goo = val$$ue;
}
}",
MainDescription($"({FeaturesResources.parameter}) DateTime value"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumTypeName()
{
await TestInMethodAsync(@"Consol$$eColor c",
MainDescription("enum System.ConsoleColor"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_Definition()
{
await TestInClassAsync(@"enum E$$ : byte { A, B }",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsField()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private E$$ _E;
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsProperty()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private E$$ E{ get; set; };
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsParameter()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M(E$$ e) { }
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsReturnType()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private E$$ M() { }
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsLocal()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M()
{
E$$ e = default;
}
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_OnMemberAccessOnType()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M()
{
var ea = E$$.A;
}
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_NotOnMemberAccessOnMember()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M()
{
var ea = E.A$$;
}
",
MainDescription("E.A = 0"));
}
[Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
[InlineData("byte", "byte")]
[InlineData("byte", "System.Byte")]
[InlineData("sbyte", "sbyte")]
[InlineData("sbyte", "System.SByte")]
[InlineData("short", "short")]
[InlineData("short", "System.Int16")]
[InlineData("ushort", "ushort")]
[InlineData("ushort", "System.UInt16")]
// int is the default type and is not shown
[InlineData("uint", "uint")]
[InlineData("uint", "System.UInt32")]
[InlineData("long", "long")]
[InlineData("long", "System.Int64")]
[InlineData("ulong", "ulong")]
[InlineData("ulong", "System.UInt64")]
public async Task EnumNonDefaultUnderlyingType_ShowForNonDefaultTypes(string displayTypeName, string underlyingTypeName)
{
await TestInClassAsync(@$"
enum E$$ : {underlyingTypeName}
{{
A, B
}}",
MainDescription($"enum C.E : {displayTypeName}"));
}
[Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
[InlineData("")]
[InlineData(": int")]
[InlineData(": System.Int32")]
public async Task EnumNonDefaultUnderlyingType_DontShowForDefaultType(string defaultType)
{
await TestInClassAsync(@$"
enum E$$ {defaultType}
{{
A, B
}}",
MainDescription("enum C.E"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumMemberNameFromMetadata()
{
await TestInMethodAsync(@"ConsoleColor c = ConsoleColor.Bla$$ck",
MainDescription("ConsoleColor.Black = 0"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FlagsEnumMemberNameFromMetadata1()
{
await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.Cl$$ass",
MainDescription("AttributeTargets.Class = 4"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FlagsEnumMemberNameFromMetadata2()
{
await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.A$$ll",
MainDescription("AttributeTargets.All = AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumMemberNameFromSource1()
{
await TestAsync(
@"enum E
{
A = 1 << 0,
B = 1 << 1,
C = 1 << 2
}
class C
{
void M()
{
var e = E.B$$;
}
}",
MainDescription("E.B = 1 << 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumMemberNameFromSource2()
{
await TestAsync(
@"enum E
{
A,
B,
C
}
class C
{
void M()
{
var e = E.B$$;
}
}",
MainDescription("E.B = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_InMethod_Minimal()
{
await TestInClassAsync(
@"void M(DateTime dt)
{
d$$t.ToString();",
MainDescription($"({FeaturesResources.parameter}) DateTime dt"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_InMethod_Qualified()
{
await TestInClassAsync(
@"void M(System.IO.FileInfo fileInfo)
{
file$$Info.ToString();",
MainDescription($"({FeaturesResources.parameter}) System.IO.FileInfo fileInfo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_FromReferenceToNamedParameter()
{
await TestInMethodAsync(@"Console.WriteLine(va$$lue: ""Hi"");",
MainDescription($"({FeaturesResources.parameter}) string value"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_DefaultValue()
{
// NOTE: Dev10 doesn't show the default value, but it would be nice if we did.
// NOTE: The "DefaultValue" property isn't implemented yet.
await TestInClassAsync(
@"void M(int param = 42)
{
para$$m.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) int param = 42"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_Params()
{
await TestInClassAsync(
@"void M(params DateTime[] arg)
{
ar$$g.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) params DateTime[] arg"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_Ref()
{
await TestInClassAsync(
@"void M(ref DateTime arg)
{
ar$$g.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) ref DateTime arg"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_Out()
{
await TestInClassAsync(
@"void M(out DateTime arg)
{
ar$$g.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) out DateTime arg"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Local_Minimal()
{
await TestInMethodAsync(
@"DateTime dt;
d$$t.ToString();",
MainDescription($"({FeaturesResources.local_variable}) DateTime dt"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Local_Qualified()
{
await TestInMethodAsync(
@"System.IO.FileInfo fileInfo;
file$$Info.ToString();",
MainDescription($"({FeaturesResources.local_variable}) System.IO.FileInfo fileInfo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_MetadataOverload()
{
await TestInMethodAsync("Console.Write$$Line();",
MainDescription($"void Console.WriteLine() (+ 18 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_SimpleWithOverload()
{
await TestInClassAsync(
@"void Method()
{
Met$$hod();
}
void Method(int i)
{
}",
MainDescription($"void C.Method() (+ 1 {FeaturesResources.overload})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_MoreOverloads()
{
await TestInClassAsync(
@"void Method()
{
Met$$hod(null);
}
void Method(int i)
{
}
void Method(DateTime dt)
{
}
void Method(System.IO.FileInfo fileInfo)
{
}",
MainDescription($"void C.Method(System.IO.FileInfo fileInfo) (+ 3 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_SimpleInSameClass()
{
await TestInClassAsync(
@"DateTime GetDate(System.IO.FileInfo ft)
{
Get$$Date(null);
}",
MainDescription("DateTime C.GetDate(System.IO.FileInfo ft)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_OptionalParameter()
{
await TestInClassAsync(
@"void M()
{
Met$$hod();
}
void Method(int i = 0)
{
}",
MainDescription("void C.Method([int i = 0])"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_OptionalDecimalParameter()
{
await TestInClassAsync(
@"void Goo(decimal x$$yz = 10)
{
}",
MainDescription($"({FeaturesResources.parameter}) decimal xyz = 10"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_Generic()
{
// Generic method don't get the instantiation info yet. NOTE: We don't display
// constraint info in Dev10. Should we?
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>
{
Go$$o<int, DateTime>(37);
}",
MainDescription("DateTime C.Goo<int, DateTime>(int arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_UnconstructedGeneric()
{
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg)
{
Go$$o<TIn, TOut>(default(TIn);
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_Inferred()
{
await TestInClassAsync(
@"void Goo<TIn>(TIn arg)
{
Go$$o(42);
}",
MainDescription("void C.Goo<int>(int arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_MultipleParams()
{
await TestInClassAsync(
@"void Goo(DateTime dt, System.IO.FileInfo fi, int number)
{
Go$$o(DateTime.Now, null, 32);
}",
MainDescription("void C.Goo(DateTime dt, System.IO.FileInfo fi, int number)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_OptionalParam()
{
// NOTE - Default values aren't actually returned by symbols yet.
await TestInClassAsync(
@"void Goo(int num = 42)
{
Go$$o();
}",
MainDescription("void C.Goo([int num = 42])"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_ParameterModifiers()
{
// NOTE - Default values aren't actually returned by symbols yet.
await TestInClassAsync(
@"void Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)
{
Go$$o(DateTime.Now, null, 32);
}",
MainDescription("void C.Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor()
{
await TestInClassAsync(
@"public C()
{
}
void M()
{
new C$$().ToString();
}",
MainDescription("C.C()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_Overloads()
{
await TestInClassAsync(
@"public C()
{
}
public C(DateTime dt)
{
}
public C(int i)
{
}
void M()
{
new C$$(DateTime.MaxValue).ToString();
}",
MainDescription($"C.C(DateTime dt) (+ 2 {FeaturesResources.overloads_})"));
}
/// <summary>
/// Regression for 3923
/// </summary>
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_OverloadFromStringLiteral()
{
await TestInMethodAsync(
@"new InvalidOperatio$$nException("""");",
MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})"));
}
/// <summary>
/// Regression for 3923
/// </summary>
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_UnknownType()
{
await TestInvalidTypeInClassAsync(
@"void M()
{
new G$$oo();
}");
}
/// <summary>
/// Regression for 3923
/// </summary>
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_OverloadFromProperty()
{
await TestInMethodAsync(
@"new InvalidOperatio$$nException(this.GetType().Name);",
MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_Metadata()
{
await TestInMethodAsync(
@"new Argument$$NullException();",
MainDescription($"ArgumentNullException.ArgumentNullException() (+ 3 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_MetadataQualified()
{
await TestInMethodAsync(@"new System.IO.File$$Info(null);",
MainDescription("System.IO.FileInfo.FileInfo(string fileName)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task InterfaceProperty()
{
await TestInMethodAsync(
@"interface I
{
string Name$$ { get; set; }
}",
MainDescription("string I.Name { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExplicitInterfacePropertyImplementation()
{
await TestInMethodAsync(
@"interface I
{
string Name { get; set; }
}
class C : I
{
string IEmployee.Name$$
{
get
{
return """";
}
set
{
}
}
}",
MainDescription("string C.Name { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Operator()
{
await TestInClassAsync(
@"public static C operator +(C left, C right)
{
return null;
}
void M(C left, C right)
{
return left +$$ right;
}",
MainDescription("C C.operator +(C left, C right)"));
}
#pragma warning disable CA2243 // Attribute string literals should parse correctly
[WorkItem(792629, "generic type parameter constraints for methods in quick info")]
#pragma warning restore CA2243 // Attribute string literals should parse correctly
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericMethodWithConstraintsAtDeclaration()
{
await TestInClassAsync(
@"TOut G$$oo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>
{
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>"));
}
#pragma warning disable CA2243 // Attribute string literals should parse correctly
[WorkItem(792629, "generic type parameter constraints for methods in quick info")]
#pragma warning restore CA2243 // Attribute string literals should parse correctly
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericMethodWithMultipleConstraintsAtDeclaration()
{
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee, new()
{
Go$$o<TIn, TOut>(default(TIn);
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee, new()"));
}
#pragma warning disable CA2243 // Attribute string literals should parse correctly
[WorkItem(792629, "generic type parameter constraints for methods in quick info")]
#pragma warning restore CA2243 // Attribute string literals should parse correctly
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnConstructedGenericMethodWithConstraintsAtInvocation()
{
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee
{
Go$$o<TIn, TOut>(default(TIn);
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericTypeWithConstraintsAtDeclaration()
{
await TestAsync(
@"public class Employee : IComparable<Employee>
{
public int CompareTo(Employee other)
{
throw new NotImplementedException();
}
}
class Emplo$$yeeList<T> : IEnumerable<T> where T : Employee, System.IComparable<T>, new()
{
}",
MainDescription("class EmployeeList<T> where T : Employee, System.IComparable<T>, new()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericType()
{
await TestAsync(
@"class T1<T11>
{
$$T11 i;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericMethod()
{
await TestInClassAsync(
@"static void Meth1<T1>(T1 i) where T1 : struct
{
$$T1 i;
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Var()
{
await TestInMethodAsync(
@"var x = new Exception();
var y = $$x;",
MainDescription($"({FeaturesResources.local_variable}) Exception x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableReference()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8),
@"class A<T>
{
}
class B
{
static void M()
{
A<B?>? x = null!;
var y = x;
$$y.ToString();
}
}",
// https://github.com/dotnet/roslyn/issues/26198 public API should show inferred nullability
MainDescription($"({FeaturesResources.local_variable}) A<B?> y"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26648, "https://github.com/dotnet/roslyn/issues/26648")]
public async Task NullableReference_InMethod()
{
var code = @"
class G
{
void M()
{
C c;
c.Go$$o();
}
}
public class C
{
public string? Goo(IEnumerable<object?> arg)
{
}
}";
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8),
code, MainDescription("string? C.Goo(IEnumerable<object?> arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NestedInGeneric()
{
await TestInMethodAsync(
@"List<int>.Enu$$merator e;",
MainDescription("struct System.Collections.Generic.List<T>.Enumerator"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NestedGenericInGeneric()
{
await TestAsync(
@"class Outer<T>
{
class Inner<U>
{
}
static void M()
{
Outer<int>.I$$nner<string> e;
}
}",
MainDescription("class Outer<T>.Inner<U>"),
TypeParameterMap(
Lines($"\r\nT {FeaturesResources.is_} int",
$"U {FeaturesResources.is_} string")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ObjectInitializer1()
{
await TestInClassAsync(
@"void M()
{
var x = new test() { $$z = 5 };
}
class test
{
public int z;
}",
MainDescription($"({FeaturesResources.field}) int test.z"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ObjectInitializer2()
{
await TestInMethodAsync(
@"class C
{
void M()
{
var x = new test() { z = $$5 };
}
class test
{
public int z;
}
}",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(537880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537880")]
public async Task TypeArgument()
{
await TestAsync(
@"class C<T, Y>
{
void M()
{
C<int, DateTime> variable;
$$variable = new C<int, DateTime>();
}
}",
MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ForEachLoop_1()
{
await TestInMethodAsync(
@"int bb = 555;
bb = bb + 1;
foreach (int cc in new int[]{ 1,2,3}){
c$$c = 1;
bb = bb + 21;
}",
MainDescription($"({FeaturesResources.local_variable}) int cc"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_1()
{
await TestInMethodAsync(
@"try
{
int aa = 555;
a$$a = aa + 1;
}
catch (Exception ex)
{
}
finally
{
}",
MainDescription($"({FeaturesResources.local_variable}) int aa"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_2()
{
await TestInMethodAsync(
@"try
{
}
catch (Exception ex)
{
var y = e$$x;
var z = y;
}
finally
{
}",
MainDescription($"({FeaturesResources.local_variable}) Exception ex"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_3()
{
await TestInMethodAsync(
@"try
{
}
catch (Exception ex)
{
var aa = 555;
aa = a$$a + 1;
}
finally
{
}",
MainDescription($"({FeaturesResources.local_variable}) int aa"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_4()
{
await TestInMethodAsync(
@"try
{
}
catch (Exception ex)
{
}
finally
{
int aa = 555;
aa = a$$a + 1;
}",
MainDescription($"({FeaturesResources.local_variable}) int aa"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericVariable()
{
await TestAsync(
@"class C<T, Y>
{
void M()
{
C<int, DateTime> variable;
var$$iable = new C<int, DateTime>();
}
}",
MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInstantiation()
{
await TestAsync(
@"using System.Collections.Generic;
class Program<T>
{
static void Main(string[] args)
{
var p = new Dictio$$nary<int, string>();
}
}",
MainDescription($"Dictionary<int, string>.Dictionary() (+ 5 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUsingAlias_Bug4141()
{
await TestAsync(
@"using X = A.C;
class A
{
public class C
{
}
}
class D : X$$
{
}",
MainDescription(@"class A.C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldOnDeclaration()
{
await TestInClassAsync(
@"DateTime fie$$ld;",
MainDescription($"({FeaturesResources.field}) DateTime C.field"));
}
[WorkItem(538767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538767")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericErrorFieldOnDeclaration()
{
await TestInClassAsync(
@"NonExistentType<int> fi$$eld;",
MainDescription($"({FeaturesResources.field}) NonExistentType<int> C.field"));
}
[WorkItem(538822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538822")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDelegateType()
{
await TestInClassAsync(
@"Fun$$c<int, string> field;",
MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"),
TypeParameterMap(
Lines($"\r\nT {FeaturesResources.is_} int",
$"TResult {FeaturesResources.is_} string")));
}
[WorkItem(538824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538824")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOnDelegateInvocation()
{
await TestAsync(
@"class Program
{
delegate void D1();
static void Main()
{
D1 d = Main;
$$d();
}
}",
MainDescription($"({FeaturesResources.local_variable}) D1 d"));
}
[WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOnArrayCreation1()
{
await TestAsync(
@"class Program
{
static void Main()
{
int[] a = n$$ew int[0];
}
}", MainDescription("int[]"));
}
[WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOnArrayCreation2()
{
await TestAsync(
@"class Program
{
static void Main()
{
int[] a = new i$$nt[0];
}
}",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_ImplicitObjectCreation()
{
await TestAsync(
@"class C
{
static void Main()
{
C c = ne$$w();
}
}
",
MainDescription("C.C()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_ImplicitObjectCreation_WithParameters()
{
await TestAsync(
@"class C
{
C(int i) { }
C(string s) { }
static void Main()
{
C c = ne$$w(1);
}
}
",
MainDescription($"C.C(int i) (+ 1 {FeaturesResources.overload})"));
}
[WorkItem(539841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539841")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIsNamedTypeAccessibleForErrorTypes()
{
await TestAsync(
@"sealed class B<T1, T2> : A<B<T1, T2>>
{
protected sealed override B<A<T>, A$$<T>> N()
{
}
}
internal class A<T>
{
}",
MainDescription("class A<T>"));
}
[WorkItem(540075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540075")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType()
{
await TestAsync(
@"using Goo = Goo;
class C
{
void Main()
{
$$Goo
}
}",
MainDescription("Goo"));
}
[WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestShortDiscardInAssignment()
{
await TestAsync(
@"class C
{
int M()
{
$$_ = M();
}
}",
MainDescription($"({FeaturesResources.discard}) int _"));
}
[WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnderscoreLocalInAssignment()
{
await TestAsync(
@"class C
{
int M()
{
var $$_ = M();
}
}",
MainDescription($"({FeaturesResources.local_variable}) int _"));
}
[WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestShortDiscardInOutVar()
{
await TestAsync(
@"class C
{
void M(out int i)
{
M(out $$_);
i = 0;
}
}",
MainDescription($"({FeaturesResources.discard}) int _"));
}
[WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDiscardInOutVar()
{
await TestAsync(
@"class C
{
void M(out int i)
{
M(out var $$_);
i = 0;
}
}"); // No quick info (see issue #16667)
}
[WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDiscardInIsPattern()
{
await TestAsync(
@"class C
{
void M()
{
if (3 is int $$_) { }
}
}"); // No quick info (see issue #16667)
}
[WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDiscardInSwitchPattern()
{
await TestAsync(
@"class C
{
void M()
{
switch (3)
{
case int $$_:
return;
}
}
}"); // No quick info (see issue #16667)
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLambdaDiscardParameter_FirstDiscard()
{
await TestAsync(
@"class C
{
void M()
{
System.Func<string, int, int> f = ($$_, _) => 1;
}
}",
MainDescription($"({FeaturesResources.discard}) string _"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLambdaDiscardParameter_SecondDiscard()
{
await TestAsync(
@"class C
{
void M()
{
System.Func<string, int, int> f = (_, $$_) => 1;
}
}",
MainDescription($"({FeaturesResources.discard}) int _"));
}
[WorkItem(540871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540871")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLiterals()
{
await TestAsync(
@"class MyClass
{
MyClass() : this($$10)
{
intI = 2;
}
public MyClass(int i)
{
}
static int intI = 1;
public static int Main()
{
return 1;
}
}",
MainDescription("struct System.Int32"));
}
[WorkItem(541444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541444")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorInForeach()
{
await TestAsync(
@"class C
{
void Main()
{
foreach (int cc in null)
{
$$cc = 1;
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) int cc"));
}
[WorkItem(541678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541678")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnEvent()
{
await TestAsync(
@"using System;
public class SampleEventArgs
{
public SampleEventArgs(string s)
{
Text = s;
}
public String Text { get; private set; }
}
public class Publisher
{
public delegate void SampleEventHandler(object sender, SampleEventArgs e);
public event SampleEventHandler SampleEvent;
protected virtual void RaiseSampleEvent()
{
if (Sam$$pleEvent != null)
SampleEvent(this, new SampleEventArgs(""Hello""));
}
}",
MainDescription("SampleEventHandler Publisher.SampleEvent"));
}
[WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEvent()
{
await TestInMethodAsync(@"System.Console.CancelKeyPres$$s += null;",
MainDescription("ConsoleCancelEventHandler Console.CancelKeyPress"));
}
[WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventPlusEqualsOperator()
{
await TestInMethodAsync(@"System.Console.CancelKeyPress +$$= null;",
MainDescription("void Console.CancelKeyPress.add"));
}
[WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventMinusEqualsOperator()
{
await TestInMethodAsync(@"System.Console.CancelKeyPress -$$= null;",
MainDescription("void Console.CancelKeyPress.remove"));
}
[WorkItem(541885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541885")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnExtensionMethod()
{
await TestWithOptionsAsync(Options.Regular,
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] values = {
1
};
bool isArray = 7.I$$n(values);
}
}
public static class MyExtensions
{
public static bool In<T>(this T o, IEnumerable<T> items)
{
return true;
}
}",
MainDescription($"({CSharpFeaturesResources.extension}) bool int.In<int>(IEnumerable<int> items)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnExtensionMethodOverloads()
{
await TestWithOptionsAsync(Options.Regular,
@"using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
""1"".Test$$Ext();
}
}
public static class Ex
{
public static void TestExt<T>(this T ex)
{
}
public static void TestExt<T>(this T ex, T arg)
{
}
public static void TestExt(this string ex, int arg)
{
}
}",
MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 2 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnExtensionMethodOverloads2()
{
await TestWithOptionsAsync(Options.Regular,
@"using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
""1"".Test$$Ext();
}
}
public static class Ex
{
public static void TestExt<T>(this T ex)
{
}
public static void TestExt<T>(this T ex, T arg)
{
}
public static void TestExt(this int ex, int arg)
{
}
}",
MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 1 {FeaturesResources.overload})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query1()
{
await TestAsync(
@"using System.Linq;
class C
{
void M()
{
var q = from n in new int[] { 1, 2, 3, 4, 5 }
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query2()
{
await TestAsync(
@"using System.Linq;
class C
{
void M()
{
var q = from n$$ in new int[] { 1, 2, 3, 4, 5 }
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query3()
{
await TestAsync(
@"class C
{
void M()
{
var q = from n in new int[] { 1, 2, 3, 4, 5 }
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) ? n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query4()
{
await TestAsync(
@"class C
{
void M()
{
var q = from n$$ in new int[] { 1, 2, 3, 4, 5 }
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) ? n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query5()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from n in new List<object>()
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) object n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query6()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from n$$ in new List<object>()
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) object n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query7()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from int n in new List<object>()
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query8()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from int n$$ in new List<object>()
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query9()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x$$ in new List<List<int>>()
from y in x
select y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) List<int> x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query10()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x in new List<List<int>>()
from y in $$x
select y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) List<int> x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query11()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x in new List<List<int>>()
from y$$ in x
select y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int y"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query12()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x in new List<List<int>>()
from y in x
select $$y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int y"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMappedEnumerable()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Select<int, int>(Func<int, int> selector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMappedQueryable()
{
await TestInMethodAsync(
@"
var q = from i in new int[0].AsQueryable()
$$select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IQueryable<int> IQueryable<int>.Select<int, int>(System.Linq.Expressions.Expression<Func<int, int>> selector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMappedCustom()
{
await TestAsync(
@"
using System;
using System.Linq;
namespace N {
public static class LazyExt
{
public static Lazy<U> Select<T, U>(this Lazy<T> source, Func<T, U> selector) => new Lazy<U>(() => selector(source.Value));
}
public class C
{
public void M()
{
var lazy = new Lazy<object>();
var q = from i in lazy
$$select i;
}
}
}
",
MainDescription($"({CSharpFeaturesResources.extension}) Lazy<object> Lazy<object>.Select<object, object>(Func<object, object> selector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectNotMapped()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
where true
$$select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoLet()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$let j = true
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<'a> IEnumerable<int>.Select<int, 'a>(Func<int, 'a> selector)"),
AnonymousTypes($@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ int i, bool j }}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoWhere()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$where true
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Where<int>(Func<int, bool> predicate)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByOneProperty()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByOnePropertyWithOrdering1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i $$ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByOnePropertyWithOrdering2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithComma1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i$$, i
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithComma2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i, i
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i, i ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i,$$ i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering3()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i, i $$ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i ascending, i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i $$ascending, i ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach3()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i ascending ,$$ i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach4()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i ascending, i $$ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByIncomplete()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
where i > 0
orderby$$
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, ?>(Func<int, ?> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMany1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$from i2 in new int[0]
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMany2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
from i2 $$in new int[0]
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoGroupBy1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$group i by i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoGroupBy2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
group i $$by i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoGroupByInto()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$group i by i into g
select g;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$join i2 in new int[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 $$in new int[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin3()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 in new int[0] $$on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin4()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 in new int[0] on i1 $$equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoinInto1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$join i2 in new int[0] on i1 equals i2 into g
select g;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IEnumerable<int>> IEnumerable<int>.GroupJoin<int, int, int, IEnumerable<int>>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, IEnumerable<int>, IEnumerable<int>> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoinInto2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 in new int[0] on i1 equals i2 $$into g
select g;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoFromMissing()
{
await TestInMethodAsync(
@"
var q = $$from i in new int[0]
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSimple1()
{
await TestInMethodAsync(
@"
var q = $$from double i in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSimple2()
{
await TestInMethodAsync(
@"
var q = from double i $$in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSelectMany1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$from double d in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, double, int>(Func<int, IEnumerable<double>> collectionSelector, Func<int, double, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSelectMany2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
from double d $$in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$join int i2 in new double[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join int i2 $$in new double[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> System.Collections.IEnumerable.Cast<int>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin3()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join int i2 in new double[0] $$on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin4()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join int i2 in new double[0] on i1 $$equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[WorkItem(543205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543205")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorGlobal()
{
await TestAsync(
@"extern alias global;
class myClass
{
static int Main()
{
$$global::otherClass oc = new global::otherClass();
return 0;
}
}",
MainDescription("<global namespace>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DontRemoveAttributeSuffixAndProduceInvalidIdentifier1()
{
await TestAsync(
@"using System;
class classAttribute : Attribute
{
private classAttribute x$$;
}",
MainDescription($"({FeaturesResources.field}) classAttribute classAttribute.x"));
}
[WorkItem(544026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544026")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DontRemoveAttributeSuffix2()
{
await TestAsync(
@"using System;
class class1Attribute : Attribute
{
private class1Attribute x$$;
}",
MainDescription($"({FeaturesResources.field}) class1Attribute class1Attribute.x"));
}
[WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AttributeQuickInfoBindsToClassTest()
{
await TestAsync(
@"using System;
/// <summary>
/// class comment
/// </summary>
[Some$$]
class SomeAttribute : Attribute
{
/// <summary>
/// ctor comment
/// </summary>
public SomeAttribute()
{
}
}",
Documentation("class comment"));
}
[WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AttributeConstructorQuickInfo()
{
await TestAsync(
@"using System;
/// <summary>
/// class comment
/// </summary>
class SomeAttribute : Attribute
{
/// <summary>
/// ctor comment
/// </summary>
public SomeAttribute()
{
var s = new Some$$Attribute();
}
}",
Documentation("ctor comment"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLabel()
{
await TestInClassAsync(
@"void M()
{
Goo:
int Goo;
goto Goo$$;
}",
MainDescription($"({FeaturesResources.label}) Goo"));
}
[WorkItem(542613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542613")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnboundGeneric()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class C
{
void M()
{
Type t = typeof(L$$ist<>);
}
}",
MainDescription("class System.Collections.Generic.List<T>"),
NoTypeParameterMap);
}
[WorkItem(543113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543113")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAnonymousTypeNew1()
{
await TestAsync(
@"class C
{
void M()
{
var v = $$new { };
}
}",
MainDescription(@"AnonymousType 'a"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ }}"));
}
[WorkItem(543873, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543873")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNestedAnonymousType()
{
// verify nested anonymous types are listed in the same order for different properties
// verify first property
await TestInMethodAsync(
@"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } };
x[0].$$Address",
MainDescription(@"'b 'a.Address { get; }"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ string Name, 'b Address }}
'b {FeaturesResources.is_} new {{ string Street, string Zip }}"));
// verify second property
await TestInMethodAsync(
@"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } };
x[0].$$Name",
MainDescription(@"string 'a.Name { get; }"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ string Name, 'b Address }}
'b {FeaturesResources.is_} new {{ string Street, string Zip }}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(543183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543183")]
public async Task TestAssignmentOperatorInAnonymousType()
{
await TestAsync(
@"class C
{
void M()
{
var a = new { A $$= 0 };
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(10731, "DevDiv_Projects/Roslyn")]
public async Task TestErrorAnonymousTypeDoesntShow()
{
await TestInMethodAsync(
@"var a = new { new { N = 0 }.N, new { } }.$$N;",
MainDescription(@"int 'a.N { get; }"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ int N }}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(543553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543553")]
public async Task TestArrayAssignedToVar()
{
await TestAsync(
@"class C
{
static void M(string[] args)
{
v$$ar a = args;
}
}",
MainDescription("string[]"));
}
[WorkItem(529139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529139")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ColorColorRangeVariable()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
namespace N1
{
class yield
{
public static IEnumerable<yield> Bar()
{
foreach (yield yield in from yield in new yield[0]
select y$$ield)
{
yield return yield;
}
}
}
}",
MainDescription($"({FeaturesResources.range_variable}) N1.yield yield"));
}
[WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoOnOperator()
{
await TestAsync(
@"using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var v = new Program() $$+ string.Empty;
}
public static implicit operator Program(string s)
{
return null;
}
public static IEnumerable<Program> operator +(Program p1, Program p2)
{
yield return p1;
yield return p2;
}
}",
MainDescription("IEnumerable<Program> Program.operator +(Program p1, Program p2)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantField()
{
await TestAsync(
@"class C
{
const int $$F = 1;",
MainDescription($"({FeaturesResources.constant}) int C.F = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMultipleConstantFields()
{
await TestAsync(
@"class C
{
public const double X = 1.0, Y = 2.0, $$Z = 3.5;",
MainDescription($"({FeaturesResources.constant}) double C.Z = 3.5"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantDependencies()
{
await TestAsync(
@"class A
{
public const int $$X = B.Z + 1;
public const int Y = 10;
}
class B
{
public const int Z = A.Y + 1;
}",
MainDescription($"({FeaturesResources.constant}) int A.X = B.Z + 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantCircularDependencies()
{
await TestAsync(
@"class A
{
public const int X = B.Z + 1;
}
class B
{
public const int Z$$ = A.X + 1;
}",
MainDescription($"({FeaturesResources.constant}) int B.Z = A.X + 1"));
}
[WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantOverflow()
{
await TestAsync(
@"class B
{
public const int Z$$ = int.MaxValue + 1;
}",
MainDescription($"({FeaturesResources.constant}) int B.Z = int.MaxValue + 1"));
}
[WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantOverflowInUncheckedContext()
{
await TestAsync(
@"class B
{
public const int Z$$ = unchecked(int.MaxValue + 1);
}",
MainDescription($"({FeaturesResources.constant}) int B.Z = unchecked(int.MaxValue + 1)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEnumInConstantField()
{
await TestAsync(
@"public class EnumTest
{
enum Days
{
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
};
static void Main()
{
const int $$x = (int)Days.Sun;
}
}",
MainDescription($"({FeaturesResources.local_constant}) int x = (int)Days.Sun"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantInDefaultExpression()
{
await TestAsync(
@"public class EnumTest
{
enum Days
{
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
};
static void Main()
{
const Days $$x = default(Days);
}
}",
MainDescription($"({FeaturesResources.local_constant}) Days x = default(Days)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantParameter()
{
await TestAsync(
@"class C
{
void Bar(int $$b = 1);
}",
MainDescription($"({FeaturesResources.parameter}) int b = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantLocal()
{
await TestAsync(
@"class C
{
void Bar()
{
const int $$loc = 1;
}",
MainDescription($"({FeaturesResources.local_constant}) int loc = 1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType1()
{
await TestInMethodAsync(
@"var $$v1 = new Goo();",
MainDescription($"({FeaturesResources.local_variable}) Goo v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType2()
{
await TestInMethodAsync(
@"var $$v1 = v1;",
MainDescription($"({FeaturesResources.local_variable}) var v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType3()
{
await TestInMethodAsync(
@"var $$v1 = new Goo<Bar>();",
MainDescription($"({FeaturesResources.local_variable}) Goo<Bar> v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType4()
{
await TestInMethodAsync(
@"var $$v1 = &(x => x);",
MainDescription($"({FeaturesResources.local_variable}) ?* v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType5()
{
await TestInMethodAsync("var $$v1 = &v1",
MainDescription($"({FeaturesResources.local_variable}) var* v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType6()
{
await TestInMethodAsync("var $$v1 = new Goo[1]",
MainDescription($"({FeaturesResources.local_variable}) Goo[] v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType7()
{
await TestInClassAsync(
@"class C
{
void Method()
{
}
void Goo()
{
var $$v1 = MethodGroup;
}
}",
MainDescription($"({FeaturesResources.local_variable}) ? v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType8()
{
await TestInMethodAsync("var $$v1 = Unknown",
MainDescription($"({FeaturesResources.local_variable}) ? v1"));
}
[WorkItem(545072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545072")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDelegateSpecialTypes()
{
await TestAsync(
@"delegate void $$F(int x);",
MainDescription("delegate void F(int x)"));
}
[WorkItem(545108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545108")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullPointerParameter()
{
await TestAsync(
@"class C
{
unsafe void $$Goo(int* x = null)
{
}
}",
MainDescription("void C.Goo([int* x = null])"));
}
[WorkItem(545098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545098")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLetIdentifier1()
{
await TestInMethodAsync("var q = from e in \"\" let $$y = 1 let a = new { y } select a;",
MainDescription($"({FeaturesResources.range_variable}) int y"));
}
[WorkItem(545295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545295")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullableDefaultValue()
{
await TestAsync(
@"class Test
{
void $$Method(int? t1 = null)
{
}
}",
MainDescription("void Test.Method([int? t1 = null])"));
}
[WorkItem(529586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529586")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidParameterInitializer()
{
await TestAsync(
@"class Program
{
void M1(float $$j1 = ""Hello""
+
""World"")
{
}
}",
MainDescription($@"({FeaturesResources.parameter}) float j1 = ""Hello"" + ""World"""));
}
[WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestComplexConstLocal()
{
await TestAsync(
@"class Program
{
void Main()
{
const int MEGABYTE = 1024 *
1024 + true;
Blah($$MEGABYTE);
}
}",
MainDescription($@"({FeaturesResources.local_constant}) int MEGABYTE = 1024 * 1024 + true"));
}
[WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestComplexConstField()
{
await TestAsync(
@"class Program
{
const int a = true
-
false;
void Main()
{
Goo($$a);
}
}",
MainDescription($"({FeaturesResources.constant}) int Program.a = true - false"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameterCrefDoesNotHaveQuickInfo()
{
await TestAsync(
@"class C<T>
{
/// <see cref=""C{X$$}""/>
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref1()
{
await TestAsync(
@"class Program
{
/// <see cref=""Mai$$n""/>
static void Main(string[] args)
{
}
}",
MainDescription(@"void Program.Main(string[] args)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref2()
{
await TestAsync(
@"class Program
{
/// <see cref=""$$Main""/>
static void Main(string[] args)
{
}
}",
MainDescription(@"void Program.Main(string[] args)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref3()
{
await TestAsync(
@"class Program
{
/// <see cref=""Main""$$/>
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref4()
{
await TestAsync(
@"class Program
{
/// <see cref=""Main$$""/>
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref5()
{
await TestAsync(
@"class Program
{
/// <see cref=""Main""$$/>
static void Main(string[] args)
{
}
}");
}
[WorkItem(546849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546849")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIndexedProperty()
{
var markup = @"class Program
{
void M()
{
CCC c = new CCC();
c.Index$$Prop[0] = ""s"";
}
}";
// Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types.
var referencedCode = @"Imports System.Runtime.InteropServices
<ComImport()>
<GuidAttribute(CCC.ClassId)>
Public Class CCC
#Region ""COM GUIDs""
Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0""
Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6""
Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb""
# End Region
''' <summary>
''' An index property from VB
''' </summary>
''' <param name=""p1"">p1 is an integer index</param>
''' <returns>A string</returns>
Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
await TestWithReferenceAsync(sourceCode: markup,
referencedCode: referencedCode,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic,
expectedResults: MainDescription("string CCC.IndexProp[int p1, [int p2 = 0]] { get; set; }"));
}
[WorkItem(546918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546918")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnconstructedGeneric()
{
await TestAsync(
@"class A<T>
{
enum SortOrder
{
Ascending,
Descending,
None
}
void Goo()
{
var b = $$SortOrder.Ascending;
}
}",
MainDescription(@"enum A<T>.SortOrder"));
}
[WorkItem(546970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546970")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnconstructedGenericInCRef()
{
await TestAsync(
@"/// <see cref=""$$C{T}"" />
class C<T>
{
}",
MainDescription(@"class C<T>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitableMethod()
{
var markup = @"using System.Threading.Tasks;
class C
{
async Task Goo()
{
Go$$o();
}
}";
var description = $"({CSharpFeaturesResources.awaitable}) Task C.Goo()";
await VerifyWithMscorlib45Async(markup, new[] { MainDescription(description) });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ObsoleteItem()
{
var markup = @"
using System;
class Program
{
[Obsolete]
public void goo()
{
go$$o();
}
}";
await TestAsync(markup, MainDescription($"[{CSharpFeaturesResources.deprecated}] void Program.goo()"));
}
[WorkItem(751070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751070")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DynamicOperator()
{
var markup = @"
public class Test
{
public delegate void NoParam();
static int Main()
{
dynamic x = new object();
if (((System.Func<dynamic>)(() => (x =$$= null)))())
return 0;
return 1;
}
}";
await TestAsync(markup, MainDescription("dynamic dynamic.operator ==(dynamic left, dynamic right)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TextOnlyDocComment()
{
await TestAsync(
@"/// <summary>
///goo
/// </summary>
class C$$
{
}", Documentation("goo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTrimConcatMultiLine()
{
await TestAsync(
@"/// <summary>
/// goo
/// bar
/// </summary>
class C$$
{
}", Documentation("goo bar"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref()
{
await TestAsync(
@"/// <summary>
/// <see cref=""C""/>
/// <seealso cref=""C""/>
/// </summary>
class C$$
{
}", Documentation("C C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExcludeTextOutsideSummaryBlock()
{
await TestAsync(
@"/// red
/// <summary>
/// green
/// </summary>
/// yellow
class C$$
{
}", Documentation("green"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NewlineAfterPara()
{
await TestAsync(
@"/// <summary>
/// <para>goo</para>
/// </summary>
class C$$
{
}", Documentation("goo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TextOnlyDocComment_Metadata()
{
var referenced = @"
/// <summary>
///goo
/// </summary>
public class C
{
}";
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTrimConcatMultiLine_Metadata()
{
var referenced = @"
/// <summary>
/// goo
/// bar
/// </summary>
public class C
{
}";
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo bar"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref_Metadata()
{
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
var referenced = @"/// <summary>
/// <see cref=""C""/>
/// <seealso cref=""C""/>
/// </summary>
public class C
{
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("C C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExcludeTextOutsideSummaryBlock_Metadata()
{
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
var referenced = @"
/// red
/// <summary>
/// green
/// </summary>
/// yellow
public class C
{
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("green"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] arg$$s, T otherParam)
{
}
}", Documentation("First parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param_Metadata()
{
var code = @"
class G
{
void goo()
{
C c;
c.Goo<int>(arg$$s: new string[] { }, 1);
}
}";
var referenced = @"
/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] args, T otherParam)
{
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("First parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param2()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] args, T oth$$erParam)
{
}
}", Documentation("Another parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param2_Metadata()
{
var code = @"
class G
{
void goo()
{
C c;
c.Goo<int>(args: new string[] { }, other$$Param: 1);
}
}";
var referenced = @"
/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] args, T otherParam)
{
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("Another parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TypeParam()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""Goo{T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T$$>(string[] args, T otherParam)
{
}
}", Documentation("A type parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnboundCref()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{T}(string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T$$>(string[] args, T otherParam)
{
}
}", Documentation("A type parameter of goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInConstructor()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute.
/// </summary>
public TestClass$$()
{
}
}", Documentation("This sample shows how to specify the TestClass constructor as a cref attribute."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInConstructorOverloaded()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute.
/// </summary>
public TestClass()
{
}
/// <summary>
/// This sample shows how to specify the <see cref=""TestClass(int)""/> constructor as a cref attribute.
/// </summary>
public TestC$$lass(int value)
{
}
}", Documentation("This sample shows how to specify the TestClass(int) constructor as a cref attribute."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInGenericMethod1()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// The GetGenericValue method.
/// <para>This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.</para>
/// </summary>
public static T GetGenericVa$$lue<T>(T para)
{
return para;
}
}", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInGenericMethod2()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// The GetGenericValue method.
/// <para>This sample shows how to specify the <see cref=""GetGenericValue{T}(T)""/> method as a cref attribute.</para>
/// </summary>
public static T GetGenericVa$$lue<T>(T para)
{
return para;
}
}", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute."));
}
[WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInMethodOverloading1()
{
await TestAsync(
@"public class TestClass
{
public static int GetZero()
{
GetGenericValu$$e();
GetGenericValue(5);
}
/// <summary>
/// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method
/// </summary>
public static T GetGenericValue<T>(T para)
{
return para;
}
/// <summary>
/// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.
/// </summary>
public static void GetGenericValue()
{
}
}", Documentation("This sample shows how to specify the TestClass.GetGenericValue() method as a cref attribute."));
}
[WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInMethodOverloading2()
{
await TestAsync(
@"public class TestClass
{
public static int GetZero()
{
GetGenericValue();
GetGenericVal$$ue(5);
}
/// <summary>
/// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method
/// </summary>
public static T GetGenericValue<T>(T para)
{
return para;
}
/// <summary>
/// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.
/// </summary>
public static void GetGenericValue()
{
}
}", Documentation("This sample shows how to call the TestClass.GetGenericValue<T>(T) method"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInGenericType()
{
await TestAsync(
@"/// <summary>
/// <remarks>This example shows how to specify the <see cref=""GenericClass{T}""/> cref.</remarks>
/// </summary>
class Generic$$Class<T>
{
}",
Documentation("This example shows how to specify the GenericClass<T> cref.",
ExpectedClassifications(
Text("This example shows how to specify the"),
WhiteSpace(" "),
Class("GenericClass"),
Punctuation.OpenAngle,
TypeParameter("T"),
Punctuation.CloseAngle,
WhiteSpace(" "),
Text("cref."))));
}
[WorkItem(812720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812720")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ClassificationOfCrefsFromMetadata()
{
var code = @"
class G
{
void goo()
{
C c;
c.Go$$o();
}
}";
var referenced = @"
/// <summary></summary>
public class C
{
/// <summary>
/// See <see cref=""Goo""/> method
/// </summary>
public void Goo()
{
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#",
Documentation("See C.Goo() method",
ExpectedClassifications(
Text("See"),
WhiteSpace(" "),
Class("C"),
Punctuation.Text("."),
Identifier("Goo"),
Punctuation.OpenParen,
Punctuation.CloseParen,
WhiteSpace(" "),
Text("method"))));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FieldAvailableInBothLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
int x;
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.field}) int C.x"), Usage("") });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(37097, "https://github.com/dotnet/roslyn/issues/37097")]
public async Task BindSymbolInOtherFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""GOO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FieldUnavailableInTwoLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage(
$"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}",
expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
#if BAR
void goo()
{
x$$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[WorkItem(962353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962353")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NoValidSymbolsInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void goo()
{
B$$ar();
}
#if B
void Bar() { }
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void M()
{
int x$$;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage("") });
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalWarningInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void M()
{
#if PROJ1
int x;
#endif
int y = x$$;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true) });
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LabelsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void M()
{
$$LABEL: goto LABEL;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.label}) LABEL"), Usage("") });
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task RangeVariablesValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
using System.Linq;
class C
{
void M()
{
var x = from y in new[] {1, 2, 3} select $$y;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.range_variable}) int y"), Usage("") });
}
[WorkItem(1019766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019766")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task PointerAccessibility()
{
var markup = @"class C
{
unsafe static void Main()
{
void* p = null;
void* q = null;
dynamic d = true;
var x = p =$$= q == d;
}
}";
await TestAsync(markup, MainDescription("bool void*.operator ==(void* left, void* right)"));
}
[WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AwaitingTaskOfArrayType()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async Task<int[]> M()
{
awa$$it M();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "int[]")));
}
[WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AwaitingTaskOfDynamic()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async Task<dynamic> M()
{
awa$$it M();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "dynamic")));
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
#if TWO
void Do(string x){}
#endif
void Shared()
{
this.Do$$
}
}]]></Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = $"void C.Do(int x)";
await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription));
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ContainingType()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void Shared()
{
var x = GetThing().Do$$();
}
#if ONE
private Methods1 GetThing()
{
return new Methods1();
}
#endif
#if TWO
private Methods2 GetThing()
{
return new Methods2();
}
#endif
}
#if ONE
public class Methods1
{
public void Do(string x) { }
}
#endif
#if TWO
public class Methods2
{
public void Do(string x) { }
}
#endif
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = $"void Methods1.Do(string x)";
await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(4868, "https://github.com/dotnet/roslyn/issues/4868")]
public async Task QuickInfoExceptions()
{
await TestAsync(
@"using System;
namespace MyNs
{
class MyException1 : Exception
{
}
class MyException2 : Exception
{
}
class TestClass
{
/// <exception cref=""MyException1""></exception>
/// <exception cref=""T:MyNs.MyException2""></exception>
/// <exception cref=""System.Int32""></exception>
/// <exception cref=""double""></exception>
/// <exception cref=""Not_A_Class_But_Still_Displayed""></exception>
void M()
{
M$$();
}
}
}",
Exceptions($"\r\n{WorkspacesResources.Exceptions_colon}\r\n MyException1\r\n MyException2\r\n int\r\n double\r\n Not_A_Class_But_Still_Displayed"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLocalFunction()
{
await TestAsync(@"
class C
{
void M()
{
int i;
local$$();
void local() { i++; this.M(); }
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLocalFunction2()
{
await TestAsync(@"
class C
{
void M()
{
int i;
local$$(i);
void local(int j) { j++; M(); }
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLocalFunction3()
{
await TestAsync(@"
class C
{
public void M(int @this)
{
int i = 0;
local$$();
void local()
{
M(1);
i++;
@this++;
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction4()
{
await TestAsync(@"
class C
{
int field;
void M()
{
void OuterLocalFunction$$()
{
int local = 0;
int InnerLocalFunction()
{
field++;
return local;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction5()
{
await TestAsync(@"
class C
{
int field;
void M()
{
void OuterLocalFunction()
{
int local = 0;
int InnerLocalFunction$$()
{
field++;
return local;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction6()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
void OuterLocalFunction$$()
{
_ = local1;
void InnerLocalFunction()
{
_ = local2;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction7()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
void OuterLocalFunction()
{
_ = local1;
void InnerLocalFunction$$()
{
_ = local2;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda()
{
await TestAsync(@"
class C
{
void M()
{
int i;
System.Action a = () =$$> { i++; M(); };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda2()
{
await TestAsync(@"
class C
{
void M()
{
int i;
System.Action<int> a = j =$$> { i++; j++; M(); };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda2_DifferentOrder()
{
await TestAsync(@"
class C
{
void M(int j)
{
int i;
System.Action a = () =$$> { M(); i++; j++; };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, j, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda3()
{
await TestAsync(@"
class C
{
void M()
{
int i;
int @this;
N(() =$$> { M(); @this++; }, () => { i++; });
}
void N(System.Action x, System.Action y) { }
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda4()
{
await TestAsync(@"
class C
{
void M()
{
int i;
N(() => { M(); }, () =$$> { i++; });
}
void N(System.Action x, System.Action y) { }
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda5()
{
await TestAsync(@"
class C
{
int field;
void M()
{
System.Action a = () =$$>
{
int local = 0;
System.Func<int> b = () =>
{
field++;
return local;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda6()
{
await TestAsync(@"
class C
{
int field;
void M()
{
System.Action a = () =>
{
int local = 0;
System.Func<int> b = () =$$>
{
field++;
return local;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda7()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
System.Action a = () =$$>
{
_ = local1;
System.Action b = () =>
{
_ = local2;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda8()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
System.Action a = () =>
{
_ = local1;
System.Action b = () =$$>
{
_ = local2;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnDelegate()
{
await TestAsync(@"
class C
{
void M()
{
int i;
System.Func<bool, int> f = dele$$gate(bool b) { i++; return 1; };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(1516, "https://github.com/dotnet/roslyn/issues/1516")]
public async Task QuickInfoWithNonStandardSeeAttributesAppear()
{
await TestAsync(
@"class C
{
/// <summary>
/// <see cref=""System.String"" />
/// <see href=""http://microsoft.com"" />
/// <see langword=""null"" />
/// <see unsupported-attribute=""cat"" />
/// </summary>
void M()
{
M$$();
}
}",
Documentation(@"string http://microsoft.com null cat"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(6657, "https://github.com/dotnet/roslyn/issues/6657")]
public async Task OptionalParameterFromPreviousSubmission()
{
const string workspaceDefinition = @"
<Workspace>
<Submission Language=""C#"" CommonReferences=""true"">
void M(int x = 1) { }
</Submission>
<Submission Language=""C#"" CommonReferences=""true"">
M(x$$: 2)
</Submission>
</Workspace>
";
using var workspace = TestWorkspace.Create(XElement.Parse(workspaceDefinition), workspaceKind: WorkspaceKind.Interactive);
await TestWithOptionsAsync(workspace, MainDescription($"({ FeaturesResources.parameter }) int x = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TupleProperty()
{
await TestInMethodAsync(
@"interface I
{
(int, int) Name { get; set; }
}
class C : I
{
(int, int) I.Name$$
{
get
{
throw new System.Exception();
}
set
{
}
}
}",
MainDescription("(int, int) C.Name { get; set; }"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity0VariableName()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var y$$ = ValueTuple.Create();
}
}
",
MainDescription($"({ FeaturesResources.local_variable }) ValueTuple y"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity0ImplicitVar()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var$$ y = ValueTuple.Create();
}
}
",
MainDescription("struct System.ValueTuple"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity1VariableName()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var y$$ = ValueTuple.Create(1);
}
}
",
MainDescription($"({ FeaturesResources.local_variable }) ValueTuple<int> y"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity1ImplicitVar()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var$$ y = ValueTuple.Create(1);
}
}
",
MainDescription("struct System.ValueTuple<System.Int32>"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity2VariableName()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var y$$ = ValueTuple.Create(1, 1);
}
}
",
MainDescription($"({ FeaturesResources.local_variable }) (int, int) y"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity2ImplicitVar()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var$$ y = ValueTuple.Create(1, 1);
}
}
",
MainDescription("(System.Int32, System.Int32)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefMethod()
{
await TestInMethodAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
ref int i = ref $$goo();
}
private static ref int goo()
{
throw new NotImplementedException();
}
}",
MainDescription("ref int Program.goo()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefLocal()
{
await TestInMethodAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
ref int $$i = ref goo();
}
private static ref int goo()
{
throw new NotImplementedException();
}
}",
MainDescription($"({FeaturesResources.local_variable}) ref int i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")]
public async Task TestGenericMethodInDocComment()
{
await TestAsync(
@"
class Test
{
T F<T>()
{
F<T>();
}
/// <summary>
/// <see cref=""F$${T}()""/>
/// </summary>
void S()
{ }
}
",
MainDescription("T Test.F<T>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(403665, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=403665&_a=edit")]
public async Task TestExceptionWithCrefToConstructorDoesNotCrash()
{
await TestAsync(
@"
class Test
{
/// <summary>
/// </summary>
/// <exception cref=""Test.Test""/>
public Test$$() {}
}
",
MainDescription("Test.Test()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefStruct()
{
var markup = "ref struct X$$ {}";
await TestAsync(markup, MainDescription("ref struct X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefStruct_Nested()
{
var markup = @"
namespace Nested
{
ref struct X$$ {}
}";
await TestAsync(markup, MainDescription("ref struct Nested.X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyStruct()
{
var markup = "readonly struct X$$ {}";
await TestAsync(markup, MainDescription("readonly struct X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyStruct_Nested()
{
var markup = @"
namespace Nested
{
readonly struct X$$ {}
}";
await TestAsync(markup, MainDescription("readonly struct Nested.X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyRefStruct()
{
var markup = "readonly ref struct X$$ {}";
await TestAsync(markup, MainDescription("readonly ref struct X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyRefStruct_Nested()
{
var markup = @"
namespace Nested
{
readonly ref struct X$$ {}
}";
await TestAsync(markup, MainDescription("readonly ref struct Nested.X"));
}
[WorkItem(22450, "https://github.com/dotnet/roslyn/issues/22450")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefLikeTypesNoDeprecated()
{
var xmlString = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true"">
<MetadataReferenceFromSource Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true"">
<Document FilePath=""ReferencedDocument"">
public ref struct TestRef
{
}
</Document>
</MetadataReferenceFromSource>
<Document FilePath=""SourceDocument"">
ref struct Test
{
private $$TestRef _field;
}
</Document>
</Project>
</Workspace>";
// There should be no [deprecated] attribute displayed.
await VerifyWithReferenceWorkerAsync(xmlString, MainDescription($"ref struct TestRef"));
}
[WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task PropertyWithSameNameAsOtherType()
{
await TestAsync(
@"namespace ConsoleApplication1
{
class Program
{
static A B { get; set; }
static B A { get; set; }
static void Main(string[] args)
{
B = ConsoleApplication1.B$$.F();
}
}
class A { }
class B
{
public static A F() => null;
}
}",
MainDescription($"ConsoleApplication1.A ConsoleApplication1.B.F()"));
}
[WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task PropertyWithSameNameAsOtherType2()
{
await TestAsync(
@"using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
public static List<Bar> Bar { get; set; }
static void Main(string[] args)
{
Tes$$t<Bar>();
}
static void Test<T>() { }
}
class Bar
{
}
}",
MainDescription($"void Program.Test<Bar>()"));
}
[WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task InMalformedEmbeddedStatement_01()
{
await TestAsync(
@"
class Program
{
void method1()
{
if (method2())
.Any(b => b.Content$$Type, out var chars)
{
}
}
}
");
}
[WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task InMalformedEmbeddedStatement_02()
{
await TestAsync(
@"
class Program
{
void method1()
{
if (method2())
.Any(b => b$$.ContentType, out var chars)
{
}
}
}
",
MainDescription($"({ FeaturesResources.parameter }) ? b"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumConstraint()
{
await TestInMethodAsync(
@"
class X<T> where T : System.Enum
{
private $$T x;
}",
MainDescription($"T {FeaturesResources.in_} X<T> where T : Enum"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DelegateConstraint()
{
await TestInMethodAsync(
@"
class X<T> where T : System.Delegate
{
private $$T x;
}",
MainDescription($"T {FeaturesResources.in_} X<T> where T : Delegate"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task MulticastDelegateConstraint()
{
await TestInMethodAsync(
@"
class X<T> where T : System.MulticastDelegate
{
private $$T x;
}",
MainDescription($"T {FeaturesResources.in_} X<T> where T : MulticastDelegate"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_Type()
{
await TestAsync(
@"
class $$X<T> where T : unmanaged
{
}",
MainDescription("class X<T> where T : unmanaged"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_Method()
{
await TestAsync(
@"
class X
{
void $$M<T>() where T : unmanaged { }
}",
MainDescription("void X.M<T>() where T : unmanaged"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_Delegate()
{
await TestAsync(
"delegate void $$D<T>() where T : unmanaged;",
MainDescription("delegate void D<T>() where T : unmanaged"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_LocalFunction()
{
await TestAsync(
@"
class X
{
void N()
{
void $$M<T>() where T : unmanaged { }
}
}",
MainDescription("void M<T>() where T : unmanaged"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGetAccessorDocumentation()
{
await TestAsync(
@"
class X
{
/// <summary>Summary for property Goo</summary>
int Goo { g$$et; set; }
}",
Documentation("Summary for property Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestSetAccessorDocumentation()
{
await TestAsync(
@"
class X
{
/// <summary>Summary for property Goo</summary>
int Goo { get; s$$et; }
}",
Documentation("Summary for property Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventAddDocumentation1()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo
{
a$$dd => throw null;
remove => throw null;
}
}",
Documentation("Summary for event Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventAddDocumentation2()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo;
void M() => Goo +$$= null;
}",
Documentation("Summary for event Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventRemoveDocumentation1()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo
{
add => throw null;
r$$emove => throw null;
}
}",
Documentation("Summary for event Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventRemoveDocumentation2()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo;
void M() => Goo -$$= null;
}",
Documentation("Summary for event Goo"));
}
[WorkItem(30642, "https://github.com/dotnet/roslyn/issues/30642")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task BuiltInOperatorWithUserDefinedEquivalent()
{
await TestAsync(
@"
class X
{
void N(string a, string b)
{
var v = a $$== b;
}
}",
MainDescription("bool string.operator ==(string a, string b)"),
SymbolGlyph(Glyph.Operator));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_Type()
{
await TestAsync(
@"
class $$X<T> where T : notnull
{
}",
MainDescription("class X<T> where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_Method()
{
await TestAsync(
@"
class X
{
void $$M<T>() where T : notnull { }
}",
MainDescription("void X.M<T>() where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_Delegate()
{
await TestAsync(
"delegate void $$D<T>() where T : notnull;",
MainDescription("delegate void D<T>() where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_LocalFunction()
{
await TestAsync(
@"
class X
{
void N()
{
void $$M<T>() where T : notnull { }
}
}",
MainDescription("void M<T>() where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableParameterThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
void N(string? s)
{
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.parameter}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableParameterThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
void N(string? s)
{
s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.parameter}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableFieldThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? s = null;
void N()
{
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.field}) string? X.s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableFieldThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? s = null;
void N()
{
s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.field}) string? X.s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullablePropertyThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? S { get; set; }
void N()
{
string s2 = $$S;
}
}",
MainDescription("string? X.S { get; set; }"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "S")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullablePropertyThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? S { get; set; }
void N()
{
S = """";
string s2 = $$S;
}
}",
MainDescription("string? X.S { get; set; }"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "S")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableRangeVariableThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
IEnumerable<string?> enumerable;
foreach (var s in enumerable)
{
string s2 = $$s;
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableRangeVariableThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
IEnumerable<string> enumerable;
foreach (var s in enumerable)
{
string s2 = $$s;
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableLocalThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
string? s = null;
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableLocalThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
string? s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownPriorToLanguageVersion8()
{
await TestWithOptionsAsync(TestOptions.Regular7_3,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
string s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string s"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownInNullableDisable()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable disable
using System.Collections.Generic;
class X
{
void N()
{
string s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string s"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableShownWhenEnabledGlobally()
{
await TestWithOptionsAsync(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable),
@"using System.Collections.Generic;
class X
{
void N()
{
string s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownForValueType()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
int a = 0;
int b = $$a;
}
}",
MainDescription($"({FeaturesResources.local_variable}) int a"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownForConst()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
const string? s = null;
string? s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_constant}) string? s = null"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocInlineSummary()
{
var markup =
@"
/// <summary>Summary documentation</summary>
/// <remarks>Remarks documentation</remarks>
void M(int x) { }
/// <summary><inheritdoc cref=""M(int)""/></summary>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation("Summary documentation"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocTwoLevels1()
{
var markup =
@"
/// <summary>Summary documentation</summary>
/// <remarks>Remarks documentation</remarks>
void M() { }
/// <inheritdoc cref=""M()""/>
void M(int x) { }
/// <inheritdoc cref=""M(int)""/>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation("Summary documentation"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocTwoLevels2()
{
var markup =
@"
/// <summary>Summary documentation</summary>
/// <remarks>Remarks documentation</remarks>
void M() { }
/// <summary><inheritdoc cref=""M()""/></summary>
void M(int x) { }
/// <summary><inheritdoc cref=""M(int)""/></summary>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation("Summary documentation"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocWithTypeParamRef()
{
var markup =
@"
public class Program
{
public static void Main() => _ = new Test<int>().$$Clone();
}
public class Test<T> : ICloneable<Test<T>>
{
/// <inheritdoc/>
public Test<T> Clone() => new();
}
/// <summary>A type that has clonable instances.</summary>
/// <typeparam name=""T"">The type of instances that can be cloned.</typeparam>
public interface ICloneable<T>
{
/// <summary>Clones a <typeparamref name=""T""/>.</summary>
/// <returns>A clone of the <typeparamref name=""T""/>.</returns>
public T Clone();
}";
await TestInClassAsync(markup,
MainDescription("Test<int> Test<int>.Clone()"),
Documentation("Clones a Test<T>."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocCycle1()
{
var markup =
@"
/// <inheritdoc cref=""M(int, int)""/>
void M(int x) { }
/// <inheritdoc cref=""M(int)""/>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocCycle2()
{
var markup =
@"
/// <inheritdoc cref=""M(int)""/>
void $$M(int x) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x)"),
Documentation(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocCycle3()
{
var markup =
@"
/// <inheritdoc cref=""M""/>
void $$M(int x) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x)"),
Documentation(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38794, "https://github.com/dotnet/roslyn/issues/38794")]
public async Task TestLinqGroupVariableDeclaration()
{
var code =
@"
void M(string[] a)
{
var v = from x in a
group x by x.Length into $$g
select g;
}";
await TestInClassAsync(code,
MainDescription($"({FeaturesResources.range_variable}) IGrouping<int, string> g"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")]
public async Task QuickInfoOnIndexerCloseBracket()
{
await TestAsync(@"
class C
{
public int this[int x] { get { return 1; } }
void M()
{
var x = new C()[5$$];
}
}",
MainDescription("int C.this[int x] { get; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")]
public async Task QuickInfoOnIndexerOpenBracket()
{
await TestAsync(@"
class C
{
public int this[int x] { get { return 1; } }
void M()
{
var x = new C()$$[5];
}
}",
MainDescription("int C.this[int x] { get; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")]
public async Task QuickInfoOnIndexer_NotOnArrayAccess()
{
await TestAsync(@"
class Program
{
void M()
{
int[] x = new int[4];
int y = x[3$$];
}
}",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithRemarksOnMethod()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <remarks>
/// Remarks text
/// </remarks>
int M()
{
return $$M();
}
}",
MainDescription("int Program.M()"),
Documentation("Summary text"),
Remarks("\r\nRemarks text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithRemarksOnPropertyAccessor()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <remarks>
/// Remarks text
/// </remarks>
int M { $$get; }
}",
MainDescription("int Program.M.get"),
Documentation("Summary text"),
Remarks("\r\nRemarks text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithReturnsOnMethod()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <returns>
/// Returns text
/// </returns>
int M()
{
return $$M();
}
}",
MainDescription("int Program.M()"),
Documentation("Summary text"),
Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithReturnsOnPropertyAccessor()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <returns>
/// Returns text
/// </returns>
int M { $$get; }
}",
MainDescription("int Program.M.get"),
Documentation("Summary text"),
Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithValueOnMethod()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <value>
/// Value text
/// </value>
int M()
{
return $$M();
}
}",
MainDescription("int Program.M()"),
Documentation("Summary text"),
Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithValueOnPropertyAccessor()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <value>
/// Value text
/// </value>
int M { $$get; }
}",
MainDescription("int Program.M.get"),
Documentation("Summary text"),
Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoNotPattern1()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is not $$Person p)
{
}
}
}",
MainDescription("class Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoNotPattern2()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is $$not Person p)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoOrPattern1()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is $$Person or int)
{
}
}
}", MainDescription("class Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoOrPattern2()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is Person or $$int)
{
}
}
}", MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoOrPattern3()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is Person $$or int)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoRecord()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("record Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoDerivedRecord()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record Person(string First, string Last)
{
}
record Student(string Id)
{
void M($$Student p)
{
}
}
", MainDescription("record Student"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(44904, "https://github.com/dotnet/roslyn/issues/44904")]
public async Task QuickInfoRecord_BaseTypeList()
{
await TestAsync(@"
record Person(string First, string Last);
record Student(int Id) : $$Person(null, null);
", MainDescription("Person.Person(string First, string Last)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfo_BaseConstructorInitializer()
{
await TestAsync(@"
public class Person { public Person(int id) { } }
public class Student : Person { public Student() : $$base(0) { } }
", MainDescription("Person.Person(int id)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoRecordClass()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record class Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("record Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoRecordStruct()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record struct Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("record struct Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoReadOnlyRecordStruct()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"readonly record struct Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("readonly record struct Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(51615, "https://github.com/dotnet/roslyn/issues/51615")]
public async Task TestVarPatternOnVarKeyword()
{
await TestAsync(
@"class C
{
string M() { }
void M2()
{
if (M() is va$$r x && x.Length > 0)
{
}
}
}",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVarPatternOnVariableItself()
{
await TestAsync(
@"class C
{
string M() { }
void M2()
{
if (M() is var x$$ && x.Length > 0)
{
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? x"));
}
[WorkItem(53135, "https://github.com/dotnet/roslyn/issues/53135")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationCData()
{
var markup =
@"using I$$ = IGoo;
/// <summary>
/// summary for interface IGoo
/// <code><![CDATA[
/// List<string> y = null;
/// ]]></code>
/// </summary>
interface IGoo { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation(@"summary for interface IGoo
List<string> y = null;"));
}
[WorkItem(37503, "https://github.com/dotnet/roslyn/issues/37503")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DoNotNormalizeWhitespaceForCode()
{
var markup =
@"using I$$ = IGoo;
/// <summary>
/// Normalize this, and <c>Also this</c>
/// <code>
/// line 1
/// line 2
/// </code>
/// </summary>
interface IGoo { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation(@"Normalize this, and Also this
line 1
line 2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ImplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
public static void $$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ImplicitImplementation_FromReference()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
public static void M1() { }
}
class R
{
public static void M() { C1_1.$$M1(); }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_FromTypeParameterReference()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class R
{
public static void M<T>() where T : I1 { T.$$M1(); }
}
";
await TestAsync(
code,
MainDescription("void I1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ExplicitInheritdoc_ImplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
/// <inheritdoc/>
public static void $$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ExplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
static void I1.$$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ExplicitInheritdoc_ExplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
/// <inheritdoc/>
static void I1.$$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoLambdaReturnType_01()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"class Program
{
System.Delegate D = bo$$ol () => true;
}",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoLambdaReturnType_02()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"class A
{
struct B { }
System.Delegate D = A.B$$ () => null;
}",
MainDescription("struct A.B"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoLambdaReturnType_03()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"class A<T>
{
}
struct B
{
System.Delegate D = A<B$$> () => null;
}",
MainDescription("struct B"));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo
{
public class SemanticQuickInfoSourceTests : AbstractSemanticQuickInfoSourceTests
{
private static async Task TestWithOptionsAsync(CSharpParseOptions options, string markup, params Action<QuickInfoItem>[] expectedResults)
{
using var workspace = TestWorkspace.CreateCSharp(markup, options);
await TestWithOptionsAsync(workspace, expectedResults);
}
private static async Task TestWithOptionsAsync(CSharpCompilationOptions options, string markup, params Action<QuickInfoItem>[] expectedResults)
{
using var workspace = TestWorkspace.CreateCSharp(markup, compilationOptions: options);
await TestWithOptionsAsync(workspace, expectedResults);
}
private static async Task TestWithOptionsAsync(TestWorkspace workspace, params Action<QuickInfoItem>[] expectedResults)
{
var testDocument = workspace.DocumentWithCursor;
var position = testDocument.CursorPosition.GetValueOrDefault();
var documentId = workspace.GetDocumentId(testDocument);
var document = workspace.CurrentSolution.GetDocument(documentId);
var service = QuickInfoService.GetService(document);
await TestWithOptionsAsync(document, service, position, expectedResults);
// speculative semantic model
if (await CanUseSpeculativeSemanticModelAsync(document, position))
{
var buffer = testDocument.GetTextBuffer();
using (var edit = buffer.CreateEdit())
{
var currentSnapshot = buffer.CurrentSnapshot;
edit.Replace(0, currentSnapshot.Length, currentSnapshot.GetText());
edit.Apply();
}
await TestWithOptionsAsync(document, service, position, expectedResults);
}
}
private static async Task TestWithOptionsAsync(Document document, QuickInfoService service, int position, Action<QuickInfoItem>[] expectedResults)
{
var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None);
if (expectedResults.Length == 0)
{
Assert.Null(info);
}
else
{
Assert.NotNull(info);
foreach (var expected in expectedResults)
{
expected(info);
}
}
}
private static async Task VerifyWithMscorlib45Async(string markup, Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""C#"" CommonReferencesNet45=""true"">
<Document FilePath=""SourceDocument"">
{0}
</Document>
</Project>
</Workspace>", SecurityElement.Escape(markup));
using var workspace = TestWorkspace.Create(xmlString);
var position = workspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = workspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id;
var document = workspace.CurrentSolution.GetDocument(documentId);
var service = QuickInfoService.GetService(document);
var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None);
if (expectedResults.Length == 0)
{
Assert.Null(info);
}
else
{
Assert.NotNull(info);
foreach (var expected in expectedResults)
{
expected(info);
}
}
}
protected override async Task TestAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
await TestWithOptionsAsync(Options.Regular, markup, expectedResults);
await TestWithOptionsAsync(Options.Script, markup, expectedResults);
}
private async Task TestWithUsingsAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
var markupWithUsings =
@"using System;
using System.Collections.Generic;
using System.Linq;
" + markup;
await TestAsync(markupWithUsings, expectedResults);
}
private Task TestInClassAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
var markupInClass = "class C { " + markup + " }";
return TestWithUsingsAsync(markupInClass, expectedResults);
}
private Task TestInMethodAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
var markupInMethod = "class C { void M() { " + markup + " } }";
return TestWithUsingsAsync(markupInMethod, expectedResults);
}
private static async Task TestWithReferenceAsync(string sourceCode,
string referencedCode,
string sourceLanguage,
string referencedLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
await TestWithMetadataReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults);
await TestWithProjectReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults);
// Multi-language projects are not supported.
if (sourceLanguage == referencedLanguage)
{
await TestInSameProjectHelperAsync(sourceCode, referencedCode, sourceLanguage, expectedResults);
}
}
private static async Task TestWithMetadataReferenceHelperAsync(
string sourceCode,
string referencedCode,
string sourceLanguage,
string referencedLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</MetadataReferenceFromSource>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyWithReferenceWorkerAsync(xmlString, expectedResults);
}
private static async Task TestWithProjectReferenceHelperAsync(
string sourceCode,
string referencedCode,
string sourceLanguage,
string referencedLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<ProjectReference>ReferencedProject</ProjectReference>
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
<Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyWithReferenceWorkerAsync(xmlString, expectedResults);
}
private static async Task TestInSameProjectHelperAsync(
string sourceCode,
string referencedCode,
string sourceLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<Document FilePath=""ReferencedDocument"">
{2}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode));
await VerifyWithReferenceWorkerAsync(xmlString, expectedResults);
}
private static async Task VerifyWithReferenceWorkerAsync(string xmlString, params Action<QuickInfoItem>[] expectedResults)
{
using var workspace = TestWorkspace.Create(xmlString);
var position = workspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = workspace.Documents.First(d => d.Name == "SourceDocument").Id;
var document = workspace.CurrentSolution.GetDocument(documentId);
var service = QuickInfoService.GetService(document);
var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None);
if (expectedResults.Length == 0)
{
Assert.Null(info);
}
else
{
Assert.NotNull(info);
foreach (var expected in expectedResults)
{
expected(info);
}
}
}
protected async Task TestInvalidTypeInClassAsync(string code)
{
var codeInClass = "class C { " + code + " }";
await TestAsync(codeInClass);
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirective()
{
await TestAsync(
@"using $$System;",
MainDescription("namespace System"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirective2()
{
await TestAsync(
@"using System.Coll$$ections.Generic;",
MainDescription("namespace System.Collections"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirective3()
{
await TestAsync(
@"using System.L$$inq;",
MainDescription("namespace System.Linq"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirectiveWithAlias()
{
await TestAsync(
@"using Goo = Sys$$tem.Console;",
MainDescription("namespace System"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeInUsingDirectiveWithAlias()
{
await TestAsync(
@"using Goo = System.Con$$sole;",
MainDescription("class System.Console"));
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationInUsingDirectiveWithAlias()
{
var markup =
@"using I$$ = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation("summary for interface IGoo"));
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationInUsingDirectiveWithAlias2()
{
var markup =
@"using I = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo { }
class C : I$$ { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation("summary for interface IGoo"));
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationInUsingDirectiveWithAlias3()
{
var markup =
@"using I = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo
{
void Goo();
}
class C : I$$ { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation("summary for interface IGoo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestThis()
{
var markup =
@"
///<summary>summary for Class C</summary>
class C { string M() { return thi$$s.ToString(); } }";
await TestWithUsingsAsync(markup,
MainDescription("class C"),
Documentation("summary for Class C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestClassWithDocComment()
{
var markup =
@"
///<summary>Hello!</summary>
class C { void M() { $$C obj; } }";
await TestAsync(markup,
MainDescription("class C"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestSingleLineDocComments()
{
// Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedSingleLineComment
// SingleLine doc comment with leading whitespace
await TestAsync(
@"///<summary>Hello!</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with space before opening tag
await TestAsync(
@"/// <summary>Hello!</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with space before opening tag and leading whitespace
await TestAsync(
@"/// <summary>Hello!</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with leading whitespace and blank line
await TestAsync(
@"///<summary>Hello!
///</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with '\r' line separators
await TestAsync("///<summary>Hello!\r///</summary>\rclass C { void M() { $$C obj; } }",
MainDescription("class C"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMultiLineDocComments()
{
// Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedMultiLineComment
// Multiline doc comment with leading whitespace
await TestAsync(
@"/**<summary>Hello!</summary>*/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with space before opening tag
await TestAsync(
@"/** <summary>Hello!</summary>
**/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with space before opening tag and leading whitespace
await TestAsync(
@"/**
** <summary>Hello!</summary>
**/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with no per-line prefix
await TestAsync(
@"/**
<summary>
Hello!
</summary>
*/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with inconsistent per-line prefix
await TestAsync(
@"/**
** <summary>
Hello!</summary>
**
**/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with closing comment on final line
await TestAsync(
@"/**
<summary>Hello!
</summary>*/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with '\r' line separators
await TestAsync("/**\r* <summary>\r* Hello!\r* </summary>\r*/\rclass C { void M() { $$C obj; } }",
MainDescription("class C"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMethodWithDocComment()
{
var markup =
@"
///<summary>Hello!</summary>
void M() { M$$() }";
await TestInClassAsync(markup,
MainDescription("void C.M()"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInt32()
{
await TestInClassAsync(
@"$$Int32 i;",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInInt()
{
await TestInClassAsync(
@"$$int i;",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestString()
{
await TestInClassAsync(
@"$$String s;",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInString()
{
await TestInClassAsync(
@"$$string s;",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInStringAtEndOfToken()
{
await TestInClassAsync(
@"string$$ s;",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBoolean()
{
await TestInClassAsync(
@"$$Boolean b;",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInBool()
{
await TestInClassAsync(
@"$$bool b;",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestSingle()
{
await TestInClassAsync(
@"$$Single s;",
MainDescription("struct System.Single"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInFloat()
{
await TestInClassAsync(
@"$$float f;",
MainDescription("struct System.Single"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVoidIsInvalid()
{
await TestInvalidTypeInClassAsync(
@"$$void M()
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidPointer1_931958()
{
await TestInvalidTypeInClassAsync(
@"$$T* i;");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidPointer2_931958()
{
await TestInvalidTypeInClassAsync(
@"T$$* i;");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidPointer3_931958()
{
await TestInvalidTypeInClassAsync(
@"T*$$ i;");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestListOfString()
{
await TestInClassAsync(
@"$$List<string> l;",
MainDescription("class System.Collections.Generic.List<T>"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} string"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestListOfSomethingFromSource()
{
var markup =
@"
///<summary>Generic List</summary>
public class GenericList<T> { Generic$$List<int> t; }";
await TestAsync(markup,
MainDescription("class GenericList<T>"),
Documentation("Generic List"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestListOfT()
{
await TestInMethodAsync(
@"class C<T>
{
$$List<T> l;
}",
MainDescription("class System.Collections.Generic.List<T>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDictionaryOfIntAndString()
{
await TestInClassAsync(
@"$$Dictionary<int, string> d;",
MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"),
TypeParameterMap(
Lines($"\r\nTKey {FeaturesResources.is_} int",
$"TValue {FeaturesResources.is_} string")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDictionaryOfTAndU()
{
await TestInMethodAsync(
@"class C<T, U>
{
$$Dictionary<T, U> d;
}",
MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"),
TypeParameterMap(
Lines($"\r\nTKey {FeaturesResources.is_} T",
$"TValue {FeaturesResources.is_} U")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIEnumerableOfInt()
{
await TestInClassAsync(
@"$$IEnumerable<int> M()
{
yield break;
}",
MainDescription("interface System.Collections.Generic.IEnumerable<out T>"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventHandler()
{
await TestInClassAsync(
@"event $$EventHandler e;",
MainDescription("delegate void System.EventHandler(object sender, System.EventArgs e)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter()
{
await TestAsync(
@"class C<T>
{
$$T t;
}",
MainDescription($"T {FeaturesResources.in_} C<T>"));
}
[WorkItem(538636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538636")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameterWithDocComment()
{
var markup =
@"
///<summary>Hello!</summary>
///<typeparam name=""T"">T is Type Parameter</typeparam>
class C<T> { $$T t; }";
await TestAsync(markup,
MainDescription($"T {FeaturesResources.in_} C<T>"),
Documentation("T is Type Parameter"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter1_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
$$T11 t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter2_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
T$$11 t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter3_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
T1$$1 t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter4_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
T11$$ t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullableOfInt()
{
await TestInClassAsync(@"$$Nullable<int> i; }",
MainDescription("struct System.Nullable<T> where T : struct"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeDeclaredOnMethod1_Bug1946()
{
await TestAsync(
@"class C
{
static void Meth1<T1>($$T1 i) where T1 : struct
{
T1 i;
}
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeDeclaredOnMethod2_Bug1946()
{
await TestAsync(
@"class C
{
static void Meth1<T1>(T1 i) where $$T1 : struct
{
T1 i;
}
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeDeclaredOnMethod3_Bug1946()
{
await TestAsync(
@"class C
{
static void Meth1<T1>(T1 i) where T1 : struct
{
$$T1 i;
}
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Class()
{
await TestAsync(
@"class C<T> where $$T : class
{
}",
MainDescription($"T {FeaturesResources.in_} C<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Struct()
{
await TestAsync(
@"struct S<T> where $$T : class
{
}",
MainDescription($"T {FeaturesResources.in_} S<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Interface()
{
await TestAsync(
@"interface I<T> where $$T : class
{
}",
MainDescription($"T {FeaturesResources.in_} I<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Delegate()
{
await TestAsync(
@"delegate void D<T>() where $$T : class;",
MainDescription($"T {FeaturesResources.in_} D<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMinimallyQualifiedConstraint()
{
await TestAsync(@"class C<T> where $$T : IEnumerable<int>",
MainDescription($"T {FeaturesResources.in_} C<T> where T : IEnumerable<int>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FullyQualifiedConstraint()
{
await TestAsync(@"class C<T> where $$T : System.Collections.Generic.IEnumerable<int>",
MainDescription($"T {FeaturesResources.in_} C<T> where T : System.Collections.Generic.IEnumerable<int>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMethodReferenceInSameMethod()
{
await TestAsync(
@"class C
{
void M()
{
M$$();
}
}",
MainDescription("void C.M()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMethodReferenceInSameMethodWithDocComment()
{
var markup =
@"
///<summary>Hello World</summary>
void M() { M$$(); }";
await TestInClassAsync(markup,
MainDescription("void C.M()"),
Documentation("Hello World"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodBuiltIn()
{
var markup =
@"int field;
void M()
{
field$$
}";
await TestInClassAsync(markup,
MainDescription($"({FeaturesResources.field}) int C.field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodBuiltIn2()
{
await TestInClassAsync(
@"int field;
void M()
{
int f = field$$;
}",
MainDescription($"({FeaturesResources.field}) int C.field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodBuiltInWithFieldInitializer()
{
await TestInClassAsync(
@"int field = 1;
void M()
{
int f = field $$;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn()
{
await TestInMethodAsync(
@"int x;
x = x$$+1;",
MainDescription("int int.operator +(int left, int right)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn1()
{
await TestInMethodAsync(
@"int x;
x = x$$ + 1;",
MainDescription($"({FeaturesResources.local_variable}) int x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn2()
{
await TestInMethodAsync(
@"int x;
x = x+$$x;",
MainDescription($"({FeaturesResources.local_variable}) int x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn3()
{
await TestInMethodAsync(
@"int x;
x = x +$$ x;",
MainDescription("int int.operator +(int left, int right)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn4()
{
await TestInMethodAsync(
@"int x;
x = x + $$x;",
MainDescription($"({FeaturesResources.local_variable}) int x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorCustomTypeBuiltIn()
{
var markup =
@"class C
{
static void M() { C c; c = c +$$ c; }
}";
await TestAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorCustomTypeOverload()
{
var markup =
@"class C
{
static void M() { C c; c = c +$$ c; }
static C operator+(C a, C b) { return a; }
}";
await TestAsync(markup,
MainDescription("C C.operator +(C a, C b)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodMinimal()
{
var markup =
@"DateTime field;
void M()
{
field$$
}";
await TestInClassAsync(markup,
MainDescription($"({FeaturesResources.field}) DateTime C.field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodQualified()
{
var markup =
@"System.IO.FileInfo file;
void M()
{
file$$
}";
await TestInClassAsync(markup,
MainDescription($"({FeaturesResources.field}) System.IO.FileInfo C.file"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructFromSource()
{
var markup =
@"struct MyStruct {
public static int SomeField; }
static class Test { int a = MyStruct.Some$$Field; }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"));
}
[WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructFromSourceWithDocComment()
{
var markup =
@"struct MyStruct {
///<summary>My Field</summary>
public static int SomeField; }
static class Test { int a = MyStruct.Some$$Field; }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"),
Documentation("My Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructInsideMethodFromSource()
{
var markup =
@"struct MyStruct {
public static int SomeField; }
static class Test { static void Method() { int a = MyStruct.Some$$Field; } }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"));
}
[WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructInsideMethodFromSourceWithDocComment()
{
var markup =
@"struct MyStruct {
///<summary>My Field</summary>
public static int SomeField; }
static class Test { static void Method() { int a = MyStruct.Some$$Field; } }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"),
Documentation("My Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldMinimal()
{
await TestInMethodAsync(@"DateTime dt = DateTime.MaxValue$$",
MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldQualified1()
{
// NOTE: we qualify the field type, but not the type that contains the field in Dev10
var markup =
@"class C {
void M()
{
DateTime dt = System.DateTime.MaxValue$$
}
}";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldQualified2()
{
await TestAsync(
@"class C
{
void M()
{
DateTime dt = System.DateTime.MaxValue$$
}
}",
MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldQualified3()
{
await TestAsync(
@"using System;
class C
{
void M()
{
DateTime dt = System.DateTime.MaxValue$$
}
}",
MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ConstructedGenericField()
{
await TestAsync(
@"class C<T>
{
public T Field;
}
class D
{
void M()
{
new C<int>().Fi$$eld.ToString();
}
}",
MainDescription($"({FeaturesResources.field}) int C<int>.Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnconstructedGenericField()
{
await TestAsync(
@"class C<T>
{
public T Field;
void M()
{
Fi$$eld.ToString();
}
}",
MainDescription($"({FeaturesResources.field}) T C<T>.Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIntegerLiteral()
{
await TestInMethodAsync(@"int f = 37$$",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTrueKeyword()
{
await TestInMethodAsync(@"bool f = true$$",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFalseKeyword()
{
await TestInMethodAsync(@"bool f = false$$",
MainDescription("struct System.Boolean"));
}
[WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullLiteral()
{
await TestInMethodAsync(@"string f = null$$",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullLiteralWithVar()
=> await TestInMethodAsync(@"var f = null$$");
[WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDefaultLiteral()
{
await TestInMethodAsync(@"string f = default$$",
MainDescription("class System.String"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitKeywordOnGenericTaskReturningAsync()
{
var markup = @"using System.Threading.Tasks;
class C
{
public async Task<int> Calc()
{
aw$$ait Calc();
return 5;
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32")));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitKeywordInDeclarationStatement()
{
var markup = @"using System.Threading.Tasks;
class C
{
public async Task<int> Calc()
{
var x = $$await Calc();
return 5;
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32")));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitKeywordOnTaskReturningAsync()
{
var markup = @"using System.Threading.Tasks;
class C
{
public async void Calc()
{
aw$$ait Task.Delay(100);
}
}";
await TestAsync(markup, MainDescription(FeaturesResources.Awaited_task_returns_no_value));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNestedAwaitKeywords1()
{
var markup = @"using System;
using System.Threading.Tasks;
class AsyncExample2
{
async Task<Task<int>> AsyncMethod()
{
return NewMethod();
}
private static Task<int> NewMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await await AsyncMethod();
};
int result = await await AsyncMethod();
Task<Task<int>> resultTask = AsyncMethod();
result = await awa$$it resultTask;
result = await lambda();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, $"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>")),
TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNestedAwaitKeywords2()
{
var markup = @"using System;
using System.Threading.Tasks;
class AsyncExample2
{
async Task<Task<int>> AsyncMethod()
{
return NewMethod();
}
private static Task<int> NewMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await await AsyncMethod();
};
int result = await await AsyncMethod();
Task<Task<int>> resultTask = AsyncMethod();
result = awa$$it await resultTask;
result = await lambda();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32")));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitablePrefixOnCustomAwaiter()
{
var markup = @"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Z = $$C;
class C
{
public MyAwaiter GetAwaiter() { throw new NotImplementedException(); }
}
class MyAwaiter : INotifyCompletion
{
public void OnCompleted(Action continuation)
{
throw new NotImplementedException();
}
public bool IsCompleted { get { throw new NotImplementedException(); } }
public void GetResult() { }
}";
await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class C"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTaskType()
{
var markup = @"using System.Threading.Tasks;
class C
{
public void Calc()
{
Task$$ v1;
}
}";
await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTaskOfTType()
{
var markup = @"using System;
using System.Threading.Tasks;
class C
{
public void Calc()
{
Task$$<int> v1;
}
}";
await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>"),
TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int"));
}
[WorkItem(7100, "https://github.com/dotnet/roslyn/issues/7100")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDynamicIsntAwaitable()
{
var markup = @"
class C
{
dynamic D() { return null; }
void M()
{
D$$();
}
}
";
await TestAsync(markup, MainDescription("dynamic C.D()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStringLiteral()
{
await TestInMethodAsync(@"string f = ""Goo""$$",
MainDescription("class System.String"));
}
[WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVerbatimStringLiteral()
{
await TestInMethodAsync(@"string f = @""cat""$$",
MainDescription("class System.String"));
}
[WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInterpolatedStringLiteral()
{
await TestInMethodAsync(@"string f = $""cat""$$", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $""c$$at""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $""$$cat""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $""cat {1$$ + 2} dog""", MainDescription("struct System.Int32"));
}
[WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVerbatimInterpolatedStringLiteral()
{
await TestInMethodAsync(@"string f = $@""cat""$$", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $@""c$$at""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $@""$$cat""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $@""cat {1$$ + 2} dog""", MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCharLiteral()
{
await TestInMethodAsync(@"string f = 'x'$$",
MainDescription("struct System.Char"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DynamicKeyword()
{
await TestInMethodAsync(
@"dyn$$amic dyn;",
MainDescription("dynamic"),
Documentation(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DynamicField()
{
await TestInClassAsync(
@"dynamic dyn;
void M()
{
d$$yn.Goo();
}",
MainDescription($"({FeaturesResources.field}) dynamic C.dyn"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Minimal()
{
await TestInClassAsync(
@"DateTime Prop { get; set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("DateTime C.Prop { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Minimal_PrivateSet()
{
await TestInClassAsync(
@"public DateTime Prop { get; private set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("DateTime C.Prop { get; private set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Minimal_PrivateSet1()
{
await TestInClassAsync(
@"protected internal int Prop { get; private set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("int C.Prop { get; private set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Qualified()
{
await TestInClassAsync(
@"System.IO.FileInfo Prop { get; set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("System.IO.FileInfo C.Prop { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NonLocalProperty_Minimal()
{
await TestInMethodAsync(@"DateTime.No$$w.ToString();",
MainDescription("DateTime DateTime.Now { get; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NonLocalProperty_Qualified()
{
await TestInMethodAsync(
@"System.IO.FileInfo f;
f.Att$$ributes.ToString();",
MainDescription("System.IO.FileAttributes System.IO.FileSystemInfo.Attributes { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ConstructedGenericProperty()
{
await TestAsync(
@"class C<T>
{
public T Property { get; set }
}
class D
{
void M()
{
new C<int>().Pro$$perty.ToString();
}
}",
MainDescription("int C<int>.Property { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnconstructedGenericProperty()
{
await TestAsync(
@"class C<T>
{
public T Property { get; set}
void M()
{
Pro$$perty.ToString();
}
}",
MainDescription("T C<T>.Property { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueInProperty()
{
await TestInClassAsync(
@"public DateTime Property
{
set
{
goo = val$$ue;
}
}",
MainDescription($"({FeaturesResources.parameter}) DateTime value"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumTypeName()
{
await TestInMethodAsync(@"Consol$$eColor c",
MainDescription("enum System.ConsoleColor"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_Definition()
{
await TestInClassAsync(@"enum E$$ : byte { A, B }",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsField()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private E$$ _E;
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsProperty()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private E$$ E{ get; set; };
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsParameter()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M(E$$ e) { }
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsReturnType()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private E$$ M() { }
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsLocal()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M()
{
E$$ e = default;
}
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_OnMemberAccessOnType()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M()
{
var ea = E$$.A;
}
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_NotOnMemberAccessOnMember()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M()
{
var ea = E.A$$;
}
",
MainDescription("E.A = 0"));
}
[Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
[InlineData("byte", "byte")]
[InlineData("byte", "System.Byte")]
[InlineData("sbyte", "sbyte")]
[InlineData("sbyte", "System.SByte")]
[InlineData("short", "short")]
[InlineData("short", "System.Int16")]
[InlineData("ushort", "ushort")]
[InlineData("ushort", "System.UInt16")]
// int is the default type and is not shown
[InlineData("uint", "uint")]
[InlineData("uint", "System.UInt32")]
[InlineData("long", "long")]
[InlineData("long", "System.Int64")]
[InlineData("ulong", "ulong")]
[InlineData("ulong", "System.UInt64")]
public async Task EnumNonDefaultUnderlyingType_ShowForNonDefaultTypes(string displayTypeName, string underlyingTypeName)
{
await TestInClassAsync(@$"
enum E$$ : {underlyingTypeName}
{{
A, B
}}",
MainDescription($"enum C.E : {displayTypeName}"));
}
[Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
[InlineData("")]
[InlineData(": int")]
[InlineData(": System.Int32")]
public async Task EnumNonDefaultUnderlyingType_DontShowForDefaultType(string defaultType)
{
await TestInClassAsync(@$"
enum E$$ {defaultType}
{{
A, B
}}",
MainDescription("enum C.E"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumMemberNameFromMetadata()
{
await TestInMethodAsync(@"ConsoleColor c = ConsoleColor.Bla$$ck",
MainDescription("ConsoleColor.Black = 0"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FlagsEnumMemberNameFromMetadata1()
{
await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.Cl$$ass",
MainDescription("AttributeTargets.Class = 4"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FlagsEnumMemberNameFromMetadata2()
{
await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.A$$ll",
MainDescription("AttributeTargets.All = AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumMemberNameFromSource1()
{
await TestAsync(
@"enum E
{
A = 1 << 0,
B = 1 << 1,
C = 1 << 2
}
class C
{
void M()
{
var e = E.B$$;
}
}",
MainDescription("E.B = 1 << 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumMemberNameFromSource2()
{
await TestAsync(
@"enum E
{
A,
B,
C
}
class C
{
void M()
{
var e = E.B$$;
}
}",
MainDescription("E.B = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_InMethod_Minimal()
{
await TestInClassAsync(
@"void M(DateTime dt)
{
d$$t.ToString();",
MainDescription($"({FeaturesResources.parameter}) DateTime dt"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_InMethod_Qualified()
{
await TestInClassAsync(
@"void M(System.IO.FileInfo fileInfo)
{
file$$Info.ToString();",
MainDescription($"({FeaturesResources.parameter}) System.IO.FileInfo fileInfo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_FromReferenceToNamedParameter()
{
await TestInMethodAsync(@"Console.WriteLine(va$$lue: ""Hi"");",
MainDescription($"({FeaturesResources.parameter}) string value"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_DefaultValue()
{
// NOTE: Dev10 doesn't show the default value, but it would be nice if we did.
// NOTE: The "DefaultValue" property isn't implemented yet.
await TestInClassAsync(
@"void M(int param = 42)
{
para$$m.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) int param = 42"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_Params()
{
await TestInClassAsync(
@"void M(params DateTime[] arg)
{
ar$$g.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) params DateTime[] arg"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_Ref()
{
await TestInClassAsync(
@"void M(ref DateTime arg)
{
ar$$g.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) ref DateTime arg"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_Out()
{
await TestInClassAsync(
@"void M(out DateTime arg)
{
ar$$g.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) out DateTime arg"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Local_Minimal()
{
await TestInMethodAsync(
@"DateTime dt;
d$$t.ToString();",
MainDescription($"({FeaturesResources.local_variable}) DateTime dt"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Local_Qualified()
{
await TestInMethodAsync(
@"System.IO.FileInfo fileInfo;
file$$Info.ToString();",
MainDescription($"({FeaturesResources.local_variable}) System.IO.FileInfo fileInfo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_MetadataOverload()
{
await TestInMethodAsync("Console.Write$$Line();",
MainDescription($"void Console.WriteLine() (+ 18 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_SimpleWithOverload()
{
await TestInClassAsync(
@"void Method()
{
Met$$hod();
}
void Method(int i)
{
}",
MainDescription($"void C.Method() (+ 1 {FeaturesResources.overload})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_MoreOverloads()
{
await TestInClassAsync(
@"void Method()
{
Met$$hod(null);
}
void Method(int i)
{
}
void Method(DateTime dt)
{
}
void Method(System.IO.FileInfo fileInfo)
{
}",
MainDescription($"void C.Method(System.IO.FileInfo fileInfo) (+ 3 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_SimpleInSameClass()
{
await TestInClassAsync(
@"DateTime GetDate(System.IO.FileInfo ft)
{
Get$$Date(null);
}",
MainDescription("DateTime C.GetDate(System.IO.FileInfo ft)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_OptionalParameter()
{
await TestInClassAsync(
@"void M()
{
Met$$hod();
}
void Method(int i = 0)
{
}",
MainDescription("void C.Method([int i = 0])"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_OptionalDecimalParameter()
{
await TestInClassAsync(
@"void Goo(decimal x$$yz = 10)
{
}",
MainDescription($"({FeaturesResources.parameter}) decimal xyz = 10"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_Generic()
{
// Generic method don't get the instantiation info yet. NOTE: We don't display
// constraint info in Dev10. Should we?
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>
{
Go$$o<int, DateTime>(37);
}",
MainDescription("DateTime C.Goo<int, DateTime>(int arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_UnconstructedGeneric()
{
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg)
{
Go$$o<TIn, TOut>(default(TIn);
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_Inferred()
{
await TestInClassAsync(
@"void Goo<TIn>(TIn arg)
{
Go$$o(42);
}",
MainDescription("void C.Goo<int>(int arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_MultipleParams()
{
await TestInClassAsync(
@"void Goo(DateTime dt, System.IO.FileInfo fi, int number)
{
Go$$o(DateTime.Now, null, 32);
}",
MainDescription("void C.Goo(DateTime dt, System.IO.FileInfo fi, int number)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_OptionalParam()
{
// NOTE - Default values aren't actually returned by symbols yet.
await TestInClassAsync(
@"void Goo(int num = 42)
{
Go$$o();
}",
MainDescription("void C.Goo([int num = 42])"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_ParameterModifiers()
{
// NOTE - Default values aren't actually returned by symbols yet.
await TestInClassAsync(
@"void Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)
{
Go$$o(DateTime.Now, null, 32);
}",
MainDescription("void C.Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor()
{
await TestInClassAsync(
@"public C()
{
}
void M()
{
new C$$().ToString();
}",
MainDescription("C.C()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_Overloads()
{
await TestInClassAsync(
@"public C()
{
}
public C(DateTime dt)
{
}
public C(int i)
{
}
void M()
{
new C$$(DateTime.MaxValue).ToString();
}",
MainDescription($"C.C(DateTime dt) (+ 2 {FeaturesResources.overloads_})"));
}
/// <summary>
/// Regression for 3923
/// </summary>
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_OverloadFromStringLiteral()
{
await TestInMethodAsync(
@"new InvalidOperatio$$nException("""");",
MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})"));
}
/// <summary>
/// Regression for 3923
/// </summary>
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_UnknownType()
{
await TestInvalidTypeInClassAsync(
@"void M()
{
new G$$oo();
}");
}
/// <summary>
/// Regression for 3923
/// </summary>
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_OverloadFromProperty()
{
await TestInMethodAsync(
@"new InvalidOperatio$$nException(this.GetType().Name);",
MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_Metadata()
{
await TestInMethodAsync(
@"new Argument$$NullException();",
MainDescription($"ArgumentNullException.ArgumentNullException() (+ 3 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_MetadataQualified()
{
await TestInMethodAsync(@"new System.IO.File$$Info(null);",
MainDescription("System.IO.FileInfo.FileInfo(string fileName)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task InterfaceProperty()
{
await TestInMethodAsync(
@"interface I
{
string Name$$ { get; set; }
}",
MainDescription("string I.Name { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExplicitInterfacePropertyImplementation()
{
await TestInMethodAsync(
@"interface I
{
string Name { get; set; }
}
class C : I
{
string IEmployee.Name$$
{
get
{
return """";
}
set
{
}
}
}",
MainDescription("string C.Name { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Operator()
{
await TestInClassAsync(
@"public static C operator +(C left, C right)
{
return null;
}
void M(C left, C right)
{
return left +$$ right;
}",
MainDescription("C C.operator +(C left, C right)"));
}
#pragma warning disable CA2243 // Attribute string literals should parse correctly
[WorkItem(792629, "generic type parameter constraints for methods in quick info")]
#pragma warning restore CA2243 // Attribute string literals should parse correctly
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericMethodWithConstraintsAtDeclaration()
{
await TestInClassAsync(
@"TOut G$$oo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>
{
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>"));
}
#pragma warning disable CA2243 // Attribute string literals should parse correctly
[WorkItem(792629, "generic type parameter constraints for methods in quick info")]
#pragma warning restore CA2243 // Attribute string literals should parse correctly
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericMethodWithMultipleConstraintsAtDeclaration()
{
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee, new()
{
Go$$o<TIn, TOut>(default(TIn);
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee, new()"));
}
#pragma warning disable CA2243 // Attribute string literals should parse correctly
[WorkItem(792629, "generic type parameter constraints for methods in quick info")]
#pragma warning restore CA2243 // Attribute string literals should parse correctly
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnConstructedGenericMethodWithConstraintsAtInvocation()
{
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee
{
Go$$o<TIn, TOut>(default(TIn);
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericTypeWithConstraintsAtDeclaration()
{
await TestAsync(
@"public class Employee : IComparable<Employee>
{
public int CompareTo(Employee other)
{
throw new NotImplementedException();
}
}
class Emplo$$yeeList<T> : IEnumerable<T> where T : Employee, System.IComparable<T>, new()
{
}",
MainDescription("class EmployeeList<T> where T : Employee, System.IComparable<T>, new()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericType()
{
await TestAsync(
@"class T1<T11>
{
$$T11 i;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericMethod()
{
await TestInClassAsync(
@"static void Meth1<T1>(T1 i) where T1 : struct
{
$$T1 i;
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Var()
{
await TestInMethodAsync(
@"var x = new Exception();
var y = $$x;",
MainDescription($"({FeaturesResources.local_variable}) Exception x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableReference()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8),
@"class A<T>
{
}
class B
{
static void M()
{
A<B?>? x = null!;
var y = x;
$$y.ToString();
}
}",
// https://github.com/dotnet/roslyn/issues/26198 public API should show inferred nullability
MainDescription($"({FeaturesResources.local_variable}) A<B?> y"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26648, "https://github.com/dotnet/roslyn/issues/26648")]
public async Task NullableReference_InMethod()
{
var code = @"
class G
{
void M()
{
C c;
c.Go$$o();
}
}
public class C
{
public string? Goo(IEnumerable<object?> arg)
{
}
}";
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8),
code, MainDescription("string? C.Goo(IEnumerable<object?> arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NestedInGeneric()
{
await TestInMethodAsync(
@"List<int>.Enu$$merator e;",
MainDescription("struct System.Collections.Generic.List<T>.Enumerator"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NestedGenericInGeneric()
{
await TestAsync(
@"class Outer<T>
{
class Inner<U>
{
}
static void M()
{
Outer<int>.I$$nner<string> e;
}
}",
MainDescription("class Outer<T>.Inner<U>"),
TypeParameterMap(
Lines($"\r\nT {FeaturesResources.is_} int",
$"U {FeaturesResources.is_} string")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ObjectInitializer1()
{
await TestInClassAsync(
@"void M()
{
var x = new test() { $$z = 5 };
}
class test
{
public int z;
}",
MainDescription($"({FeaturesResources.field}) int test.z"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ObjectInitializer2()
{
await TestInMethodAsync(
@"class C
{
void M()
{
var x = new test() { z = $$5 };
}
class test
{
public int z;
}
}",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(537880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537880")]
public async Task TypeArgument()
{
await TestAsync(
@"class C<T, Y>
{
void M()
{
C<int, DateTime> variable;
$$variable = new C<int, DateTime>();
}
}",
MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ForEachLoop_1()
{
await TestInMethodAsync(
@"int bb = 555;
bb = bb + 1;
foreach (int cc in new int[]{ 1,2,3}){
c$$c = 1;
bb = bb + 21;
}",
MainDescription($"({FeaturesResources.local_variable}) int cc"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_1()
{
await TestInMethodAsync(
@"try
{
int aa = 555;
a$$a = aa + 1;
}
catch (Exception ex)
{
}
finally
{
}",
MainDescription($"({FeaturesResources.local_variable}) int aa"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_2()
{
await TestInMethodAsync(
@"try
{
}
catch (Exception ex)
{
var y = e$$x;
var z = y;
}
finally
{
}",
MainDescription($"({FeaturesResources.local_variable}) Exception ex"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_3()
{
await TestInMethodAsync(
@"try
{
}
catch (Exception ex)
{
var aa = 555;
aa = a$$a + 1;
}
finally
{
}",
MainDescription($"({FeaturesResources.local_variable}) int aa"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_4()
{
await TestInMethodAsync(
@"try
{
}
catch (Exception ex)
{
}
finally
{
int aa = 555;
aa = a$$a + 1;
}",
MainDescription($"({FeaturesResources.local_variable}) int aa"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericVariable()
{
await TestAsync(
@"class C<T, Y>
{
void M()
{
C<int, DateTime> variable;
var$$iable = new C<int, DateTime>();
}
}",
MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInstantiation()
{
await TestAsync(
@"using System.Collections.Generic;
class Program<T>
{
static void Main(string[] args)
{
var p = new Dictio$$nary<int, string>();
}
}",
MainDescription($"Dictionary<int, string>.Dictionary() (+ 5 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUsingAlias_Bug4141()
{
await TestAsync(
@"using X = A.C;
class A
{
public class C
{
}
}
class D : X$$
{
}",
MainDescription(@"class A.C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldOnDeclaration()
{
await TestInClassAsync(
@"DateTime fie$$ld;",
MainDescription($"({FeaturesResources.field}) DateTime C.field"));
}
[WorkItem(538767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538767")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericErrorFieldOnDeclaration()
{
await TestInClassAsync(
@"NonExistentType<int> fi$$eld;",
MainDescription($"({FeaturesResources.field}) NonExistentType<int> C.field"));
}
[WorkItem(538822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538822")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDelegateType()
{
await TestInClassAsync(
@"Fun$$c<int, string> field;",
MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"),
TypeParameterMap(
Lines($"\r\nT {FeaturesResources.is_} int",
$"TResult {FeaturesResources.is_} string")));
}
[WorkItem(538824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538824")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOnDelegateInvocation()
{
await TestAsync(
@"class Program
{
delegate void D1();
static void Main()
{
D1 d = Main;
$$d();
}
}",
MainDescription($"({FeaturesResources.local_variable}) D1 d"));
}
[WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOnArrayCreation1()
{
await TestAsync(
@"class Program
{
static void Main()
{
int[] a = n$$ew int[0];
}
}", MainDescription("int[]"));
}
[WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOnArrayCreation2()
{
await TestAsync(
@"class Program
{
static void Main()
{
int[] a = new i$$nt[0];
}
}",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_ImplicitObjectCreation()
{
await TestAsync(
@"class C
{
static void Main()
{
C c = ne$$w();
}
}
",
MainDescription("C.C()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_ImplicitObjectCreation_WithParameters()
{
await TestAsync(
@"class C
{
C(int i) { }
C(string s) { }
static void Main()
{
C c = ne$$w(1);
}
}
",
MainDescription($"C.C(int i) (+ 1 {FeaturesResources.overload})"));
}
[WorkItem(539841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539841")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIsNamedTypeAccessibleForErrorTypes()
{
await TestAsync(
@"sealed class B<T1, T2> : A<B<T1, T2>>
{
protected sealed override B<A<T>, A$$<T>> N()
{
}
}
internal class A<T>
{
}",
MainDescription("class A<T>"));
}
[WorkItem(540075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540075")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType()
{
await TestAsync(
@"using Goo = Goo;
class C
{
void Main()
{
$$Goo
}
}",
MainDescription("Goo"));
}
[WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestShortDiscardInAssignment()
{
await TestAsync(
@"class C
{
int M()
{
$$_ = M();
}
}",
MainDescription($"({FeaturesResources.discard}) int _"));
}
[WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnderscoreLocalInAssignment()
{
await TestAsync(
@"class C
{
int M()
{
var $$_ = M();
}
}",
MainDescription($"({FeaturesResources.local_variable}) int _"));
}
[WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestShortDiscardInOutVar()
{
await TestAsync(
@"class C
{
void M(out int i)
{
M(out $$_);
i = 0;
}
}",
MainDescription($"({FeaturesResources.discard}) int _"));
}
[WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDiscardInOutVar()
{
await TestAsync(
@"class C
{
void M(out int i)
{
M(out var $$_);
i = 0;
}
}"); // No quick info (see issue #16667)
}
[WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDiscardInIsPattern()
{
await TestAsync(
@"class C
{
void M()
{
if (3 is int $$_) { }
}
}"); // No quick info (see issue #16667)
}
[WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDiscardInSwitchPattern()
{
await TestAsync(
@"class C
{
void M()
{
switch (3)
{
case int $$_:
return;
}
}
}"); // No quick info (see issue #16667)
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLambdaDiscardParameter_FirstDiscard()
{
await TestAsync(
@"class C
{
void M()
{
System.Func<string, int, int> f = ($$_, _) => 1;
}
}",
MainDescription($"({FeaturesResources.discard}) string _"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLambdaDiscardParameter_SecondDiscard()
{
await TestAsync(
@"class C
{
void M()
{
System.Func<string, int, int> f = (_, $$_) => 1;
}
}",
MainDescription($"({FeaturesResources.discard}) int _"));
}
[WorkItem(540871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540871")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLiterals()
{
await TestAsync(
@"class MyClass
{
MyClass() : this($$10)
{
intI = 2;
}
public MyClass(int i)
{
}
static int intI = 1;
public static int Main()
{
return 1;
}
}",
MainDescription("struct System.Int32"));
}
[WorkItem(541444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541444")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorInForeach()
{
await TestAsync(
@"class C
{
void Main()
{
foreach (int cc in null)
{
$$cc = 1;
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) int cc"));
}
[WorkItem(541678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541678")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnEvent()
{
await TestAsync(
@"using System;
public class SampleEventArgs
{
public SampleEventArgs(string s)
{
Text = s;
}
public String Text { get; private set; }
}
public class Publisher
{
public delegate void SampleEventHandler(object sender, SampleEventArgs e);
public event SampleEventHandler SampleEvent;
protected virtual void RaiseSampleEvent()
{
if (Sam$$pleEvent != null)
SampleEvent(this, new SampleEventArgs(""Hello""));
}
}",
MainDescription("SampleEventHandler Publisher.SampleEvent"));
}
[WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEvent()
{
await TestInMethodAsync(@"System.Console.CancelKeyPres$$s += null;",
MainDescription("ConsoleCancelEventHandler Console.CancelKeyPress"));
}
[WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventPlusEqualsOperator()
{
await TestInMethodAsync(@"System.Console.CancelKeyPress +$$= null;",
MainDescription("void Console.CancelKeyPress.add"));
}
[WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventMinusEqualsOperator()
{
await TestInMethodAsync(@"System.Console.CancelKeyPress -$$= null;",
MainDescription("void Console.CancelKeyPress.remove"));
}
[WorkItem(541885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541885")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnExtensionMethod()
{
await TestWithOptionsAsync(Options.Regular,
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] values = {
1
};
bool isArray = 7.I$$n(values);
}
}
public static class MyExtensions
{
public static bool In<T>(this T o, IEnumerable<T> items)
{
return true;
}
}",
MainDescription($"({CSharpFeaturesResources.extension}) bool int.In<int>(IEnumerable<int> items)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnExtensionMethodOverloads()
{
await TestWithOptionsAsync(Options.Regular,
@"using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
""1"".Test$$Ext();
}
}
public static class Ex
{
public static void TestExt<T>(this T ex)
{
}
public static void TestExt<T>(this T ex, T arg)
{
}
public static void TestExt(this string ex, int arg)
{
}
}",
MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 2 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnExtensionMethodOverloads2()
{
await TestWithOptionsAsync(Options.Regular,
@"using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
""1"".Test$$Ext();
}
}
public static class Ex
{
public static void TestExt<T>(this T ex)
{
}
public static void TestExt<T>(this T ex, T arg)
{
}
public static void TestExt(this int ex, int arg)
{
}
}",
MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 1 {FeaturesResources.overload})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query1()
{
await TestAsync(
@"using System.Linq;
class C
{
void M()
{
var q = from n in new int[] { 1, 2, 3, 4, 5 }
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query2()
{
await TestAsync(
@"using System.Linq;
class C
{
void M()
{
var q = from n$$ in new int[] { 1, 2, 3, 4, 5 }
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query3()
{
await TestAsync(
@"class C
{
void M()
{
var q = from n in new int[] { 1, 2, 3, 4, 5 }
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) ? n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query4()
{
await TestAsync(
@"class C
{
void M()
{
var q = from n$$ in new int[] { 1, 2, 3, 4, 5 }
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) ? n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query5()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from n in new List<object>()
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) object n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query6()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from n$$ in new List<object>()
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) object n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query7()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from int n in new List<object>()
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query8()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from int n$$ in new List<object>()
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query9()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x$$ in new List<List<int>>()
from y in x
select y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) List<int> x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query10()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x in new List<List<int>>()
from y in $$x
select y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) List<int> x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query11()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x in new List<List<int>>()
from y$$ in x
select y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int y"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query12()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x in new List<List<int>>()
from y in x
select $$y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int y"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMappedEnumerable()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Select<int, int>(Func<int, int> selector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMappedQueryable()
{
await TestInMethodAsync(
@"
var q = from i in new int[0].AsQueryable()
$$select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IQueryable<int> IQueryable<int>.Select<int, int>(System.Linq.Expressions.Expression<Func<int, int>> selector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMappedCustom()
{
await TestAsync(
@"
using System;
using System.Linq;
namespace N {
public static class LazyExt
{
public static Lazy<U> Select<T, U>(this Lazy<T> source, Func<T, U> selector) => new Lazy<U>(() => selector(source.Value));
}
public class C
{
public void M()
{
var lazy = new Lazy<object>();
var q = from i in lazy
$$select i;
}
}
}
",
MainDescription($"({CSharpFeaturesResources.extension}) Lazy<object> Lazy<object>.Select<object, object>(Func<object, object> selector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectNotMapped()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
where true
$$select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoLet()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$let j = true
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<'a> IEnumerable<int>.Select<int, 'a>(Func<int, 'a> selector)"),
AnonymousTypes($@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ int i, bool j }}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoWhere()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$where true
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Where<int>(Func<int, bool> predicate)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByOneProperty()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByOnePropertyWithOrdering1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i $$ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByOnePropertyWithOrdering2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithComma1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i$$, i
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithComma2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i, i
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i, i ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i,$$ i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering3()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i, i $$ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i ascending, i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i $$ascending, i ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach3()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i ascending ,$$ i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach4()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i ascending, i $$ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByIncomplete()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
where i > 0
orderby$$
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, ?>(Func<int, ?> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMany1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$from i2 in new int[0]
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMany2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
from i2 $$in new int[0]
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoGroupBy1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$group i by i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoGroupBy2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
group i $$by i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoGroupByInto()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$group i by i into g
select g;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$join i2 in new int[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 $$in new int[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin3()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 in new int[0] $$on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin4()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 in new int[0] on i1 $$equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoinInto1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$join i2 in new int[0] on i1 equals i2 into g
select g;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IEnumerable<int>> IEnumerable<int>.GroupJoin<int, int, int, IEnumerable<int>>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, IEnumerable<int>, IEnumerable<int>> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoinInto2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 in new int[0] on i1 equals i2 $$into g
select g;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoFromMissing()
{
await TestInMethodAsync(
@"
var q = $$from i in new int[0]
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSimple1()
{
await TestInMethodAsync(
@"
var q = $$from double i in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSimple2()
{
await TestInMethodAsync(
@"
var q = from double i $$in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSelectMany1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$from double d in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, double, int>(Func<int, IEnumerable<double>> collectionSelector, Func<int, double, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSelectMany2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
from double d $$in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$join int i2 in new double[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join int i2 $$in new double[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> System.Collections.IEnumerable.Cast<int>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin3()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join int i2 in new double[0] $$on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin4()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join int i2 in new double[0] on i1 $$equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[WorkItem(543205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543205")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorGlobal()
{
await TestAsync(
@"extern alias global;
class myClass
{
static int Main()
{
$$global::otherClass oc = new global::otherClass();
return 0;
}
}",
MainDescription("<global namespace>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DontRemoveAttributeSuffixAndProduceInvalidIdentifier1()
{
await TestAsync(
@"using System;
class classAttribute : Attribute
{
private classAttribute x$$;
}",
MainDescription($"({FeaturesResources.field}) classAttribute classAttribute.x"));
}
[WorkItem(544026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544026")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DontRemoveAttributeSuffix2()
{
await TestAsync(
@"using System;
class class1Attribute : Attribute
{
private class1Attribute x$$;
}",
MainDescription($"({FeaturesResources.field}) class1Attribute class1Attribute.x"));
}
[WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AttributeQuickInfoBindsToClassTest()
{
await TestAsync(
@"using System;
/// <summary>
/// class comment
/// </summary>
[Some$$]
class SomeAttribute : Attribute
{
/// <summary>
/// ctor comment
/// </summary>
public SomeAttribute()
{
}
}",
Documentation("class comment"));
}
[WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AttributeConstructorQuickInfo()
{
await TestAsync(
@"using System;
/// <summary>
/// class comment
/// </summary>
class SomeAttribute : Attribute
{
/// <summary>
/// ctor comment
/// </summary>
public SomeAttribute()
{
var s = new Some$$Attribute();
}
}",
Documentation("ctor comment"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLabel()
{
await TestInClassAsync(
@"void M()
{
Goo:
int Goo;
goto Goo$$;
}",
MainDescription($"({FeaturesResources.label}) Goo"));
}
[WorkItem(542613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542613")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnboundGeneric()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class C
{
void M()
{
Type t = typeof(L$$ist<>);
}
}",
MainDescription("class System.Collections.Generic.List<T>"),
NoTypeParameterMap);
}
[WorkItem(543113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543113")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAnonymousTypeNew1()
{
await TestAsync(
@"class C
{
void M()
{
var v = $$new { };
}
}",
MainDescription(@"AnonymousType 'a"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ }}"));
}
[WorkItem(543873, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543873")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNestedAnonymousType()
{
// verify nested anonymous types are listed in the same order for different properties
// verify first property
await TestInMethodAsync(
@"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } };
x[0].$$Address",
MainDescription(@"'b 'a.Address { get; }"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ string Name, 'b Address }}
'b {FeaturesResources.is_} new {{ string Street, string Zip }}"));
// verify second property
await TestInMethodAsync(
@"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } };
x[0].$$Name",
MainDescription(@"string 'a.Name { get; }"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ string Name, 'b Address }}
'b {FeaturesResources.is_} new {{ string Street, string Zip }}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(543183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543183")]
public async Task TestAssignmentOperatorInAnonymousType()
{
await TestAsync(
@"class C
{
void M()
{
var a = new { A $$= 0 };
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(10731, "DevDiv_Projects/Roslyn")]
public async Task TestErrorAnonymousTypeDoesntShow()
{
await TestInMethodAsync(
@"var a = new { new { N = 0 }.N, new { } }.$$N;",
MainDescription(@"int 'a.N { get; }"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ int N }}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(543553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543553")]
public async Task TestArrayAssignedToVar()
{
await TestAsync(
@"class C
{
static void M(string[] args)
{
v$$ar a = args;
}
}",
MainDescription("string[]"));
}
[WorkItem(529139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529139")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ColorColorRangeVariable()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
namespace N1
{
class yield
{
public static IEnumerable<yield> Bar()
{
foreach (yield yield in from yield in new yield[0]
select y$$ield)
{
yield return yield;
}
}
}
}",
MainDescription($"({FeaturesResources.range_variable}) N1.yield yield"));
}
[WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoOnOperator()
{
await TestAsync(
@"using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var v = new Program() $$+ string.Empty;
}
public static implicit operator Program(string s)
{
return null;
}
public static IEnumerable<Program> operator +(Program p1, Program p2)
{
yield return p1;
yield return p2;
}
}",
MainDescription("IEnumerable<Program> Program.operator +(Program p1, Program p2)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantField()
{
await TestAsync(
@"class C
{
const int $$F = 1;",
MainDescription($"({FeaturesResources.constant}) int C.F = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMultipleConstantFields()
{
await TestAsync(
@"class C
{
public const double X = 1.0, Y = 2.0, $$Z = 3.5;",
MainDescription($"({FeaturesResources.constant}) double C.Z = 3.5"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantDependencies()
{
await TestAsync(
@"class A
{
public const int $$X = B.Z + 1;
public const int Y = 10;
}
class B
{
public const int Z = A.Y + 1;
}",
MainDescription($"({FeaturesResources.constant}) int A.X = B.Z + 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantCircularDependencies()
{
await TestAsync(
@"class A
{
public const int X = B.Z + 1;
}
class B
{
public const int Z$$ = A.X + 1;
}",
MainDescription($"({FeaturesResources.constant}) int B.Z = A.X + 1"));
}
[WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantOverflow()
{
await TestAsync(
@"class B
{
public const int Z$$ = int.MaxValue + 1;
}",
MainDescription($"({FeaturesResources.constant}) int B.Z = int.MaxValue + 1"));
}
[WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantOverflowInUncheckedContext()
{
await TestAsync(
@"class B
{
public const int Z$$ = unchecked(int.MaxValue + 1);
}",
MainDescription($"({FeaturesResources.constant}) int B.Z = unchecked(int.MaxValue + 1)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEnumInConstantField()
{
await TestAsync(
@"public class EnumTest
{
enum Days
{
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
};
static void Main()
{
const int $$x = (int)Days.Sun;
}
}",
MainDescription($"({FeaturesResources.local_constant}) int x = (int)Days.Sun"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantInDefaultExpression()
{
await TestAsync(
@"public class EnumTest
{
enum Days
{
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
};
static void Main()
{
const Days $$x = default(Days);
}
}",
MainDescription($"({FeaturesResources.local_constant}) Days x = default(Days)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantParameter()
{
await TestAsync(
@"class C
{
void Bar(int $$b = 1);
}",
MainDescription($"({FeaturesResources.parameter}) int b = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantLocal()
{
await TestAsync(
@"class C
{
void Bar()
{
const int $$loc = 1;
}",
MainDescription($"({FeaturesResources.local_constant}) int loc = 1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType1()
{
await TestInMethodAsync(
@"var $$v1 = new Goo();",
MainDescription($"({FeaturesResources.local_variable}) Goo v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType2()
{
await TestInMethodAsync(
@"var $$v1 = v1;",
MainDescription($"({FeaturesResources.local_variable}) var v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType3()
{
await TestInMethodAsync(
@"var $$v1 = new Goo<Bar>();",
MainDescription($"({FeaturesResources.local_variable}) Goo<Bar> v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType4()
{
await TestInMethodAsync(
@"var $$v1 = &(x => x);",
MainDescription($"({FeaturesResources.local_variable}) ?* v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType5()
{
await TestInMethodAsync("var $$v1 = &v1",
MainDescription($"({FeaturesResources.local_variable}) var* v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType6()
{
await TestInMethodAsync("var $$v1 = new Goo[1]",
MainDescription($"({FeaturesResources.local_variable}) Goo[] v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType7()
{
await TestInClassAsync(
@"class C
{
void Method()
{
}
void Goo()
{
var $$v1 = MethodGroup;
}
}",
MainDescription($"({FeaturesResources.local_variable}) ? v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType8()
{
await TestInMethodAsync("var $$v1 = Unknown",
MainDescription($"({FeaturesResources.local_variable}) ? v1"));
}
[WorkItem(545072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545072")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDelegateSpecialTypes()
{
await TestAsync(
@"delegate void $$F(int x);",
MainDescription("delegate void F(int x)"));
}
[WorkItem(545108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545108")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullPointerParameter()
{
await TestAsync(
@"class C
{
unsafe void $$Goo(int* x = null)
{
}
}",
MainDescription("void C.Goo([int* x = null])"));
}
[WorkItem(545098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545098")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLetIdentifier1()
{
await TestInMethodAsync("var q = from e in \"\" let $$y = 1 let a = new { y } select a;",
MainDescription($"({FeaturesResources.range_variable}) int y"));
}
[WorkItem(545295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545295")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullableDefaultValue()
{
await TestAsync(
@"class Test
{
void $$Method(int? t1 = null)
{
}
}",
MainDescription("void Test.Method([int? t1 = null])"));
}
[WorkItem(529586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529586")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidParameterInitializer()
{
await TestAsync(
@"class Program
{
void M1(float $$j1 = ""Hello""
+
""World"")
{
}
}",
MainDescription($@"({FeaturesResources.parameter}) float j1 = ""Hello"" + ""World"""));
}
[WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestComplexConstLocal()
{
await TestAsync(
@"class Program
{
void Main()
{
const int MEGABYTE = 1024 *
1024 + true;
Blah($$MEGABYTE);
}
}",
MainDescription($@"({FeaturesResources.local_constant}) int MEGABYTE = 1024 * 1024 + true"));
}
[WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestComplexConstField()
{
await TestAsync(
@"class Program
{
const int a = true
-
false;
void Main()
{
Goo($$a);
}
}",
MainDescription($"({FeaturesResources.constant}) int Program.a = true - false"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameterCrefDoesNotHaveQuickInfo()
{
await TestAsync(
@"class C<T>
{
/// <see cref=""C{X$$}""/>
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref1()
{
await TestAsync(
@"class Program
{
/// <see cref=""Mai$$n""/>
static void Main(string[] args)
{
}
}",
MainDescription(@"void Program.Main(string[] args)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref2()
{
await TestAsync(
@"class Program
{
/// <see cref=""$$Main""/>
static void Main(string[] args)
{
}
}",
MainDescription(@"void Program.Main(string[] args)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref3()
{
await TestAsync(
@"class Program
{
/// <see cref=""Main""$$/>
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref4()
{
await TestAsync(
@"class Program
{
/// <see cref=""Main$$""/>
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref5()
{
await TestAsync(
@"class Program
{
/// <see cref=""Main""$$/>
static void Main(string[] args)
{
}
}");
}
[WorkItem(546849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546849")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIndexedProperty()
{
var markup = @"class Program
{
void M()
{
CCC c = new CCC();
c.Index$$Prop[0] = ""s"";
}
}";
// Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types.
var referencedCode = @"Imports System.Runtime.InteropServices
<ComImport()>
<GuidAttribute(CCC.ClassId)>
Public Class CCC
#Region ""COM GUIDs""
Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0""
Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6""
Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb""
# End Region
''' <summary>
''' An index property from VB
''' </summary>
''' <param name=""p1"">p1 is an integer index</param>
''' <returns>A string</returns>
Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
await TestWithReferenceAsync(sourceCode: markup,
referencedCode: referencedCode,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic,
expectedResults: MainDescription("string CCC.IndexProp[int p1, [int p2 = 0]] { get; set; }"));
}
[WorkItem(546918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546918")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnconstructedGeneric()
{
await TestAsync(
@"class A<T>
{
enum SortOrder
{
Ascending,
Descending,
None
}
void Goo()
{
var b = $$SortOrder.Ascending;
}
}",
MainDescription(@"enum A<T>.SortOrder"));
}
[WorkItem(546970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546970")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnconstructedGenericInCRef()
{
await TestAsync(
@"/// <see cref=""$$C{T}"" />
class C<T>
{
}",
MainDescription(@"class C<T>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitableMethod()
{
var markup = @"using System.Threading.Tasks;
class C
{
async Task Goo()
{
Go$$o();
}
}";
var description = $"({CSharpFeaturesResources.awaitable}) Task C.Goo()";
await VerifyWithMscorlib45Async(markup, new[] { MainDescription(description) });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ObsoleteItem()
{
var markup = @"
using System;
class Program
{
[Obsolete]
public void goo()
{
go$$o();
}
}";
await TestAsync(markup, MainDescription($"[{CSharpFeaturesResources.deprecated}] void Program.goo()"));
}
[WorkItem(751070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751070")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DynamicOperator()
{
var markup = @"
public class Test
{
public delegate void NoParam();
static int Main()
{
dynamic x = new object();
if (((System.Func<dynamic>)(() => (x =$$= null)))())
return 0;
return 1;
}
}";
await TestAsync(markup, MainDescription("dynamic dynamic.operator ==(dynamic left, dynamic right)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TextOnlyDocComment()
{
await TestAsync(
@"/// <summary>
///goo
/// </summary>
class C$$
{
}", Documentation("goo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTrimConcatMultiLine()
{
await TestAsync(
@"/// <summary>
/// goo
/// bar
/// </summary>
class C$$
{
}", Documentation("goo bar"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref()
{
await TestAsync(
@"/// <summary>
/// <see cref=""C""/>
/// <seealso cref=""C""/>
/// </summary>
class C$$
{
}", Documentation("C C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExcludeTextOutsideSummaryBlock()
{
await TestAsync(
@"/// red
/// <summary>
/// green
/// </summary>
/// yellow
class C$$
{
}", Documentation("green"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NewlineAfterPara()
{
await TestAsync(
@"/// <summary>
/// <para>goo</para>
/// </summary>
class C$$
{
}", Documentation("goo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TextOnlyDocComment_Metadata()
{
var referenced = @"
/// <summary>
///goo
/// </summary>
public class C
{
}";
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTrimConcatMultiLine_Metadata()
{
var referenced = @"
/// <summary>
/// goo
/// bar
/// </summary>
public class C
{
}";
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo bar"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref_Metadata()
{
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
var referenced = @"/// <summary>
/// <see cref=""C""/>
/// <seealso cref=""C""/>
/// </summary>
public class C
{
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("C C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExcludeTextOutsideSummaryBlock_Metadata()
{
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
var referenced = @"
/// red
/// <summary>
/// green
/// </summary>
/// yellow
public class C
{
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("green"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] arg$$s, T otherParam)
{
}
}", Documentation("First parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param_Metadata()
{
var code = @"
class G
{
void goo()
{
C c;
c.Goo<int>(arg$$s: new string[] { }, 1);
}
}";
var referenced = @"
/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] args, T otherParam)
{
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("First parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param2()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] args, T oth$$erParam)
{
}
}", Documentation("Another parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param2_Metadata()
{
var code = @"
class G
{
void goo()
{
C c;
c.Goo<int>(args: new string[] { }, other$$Param: 1);
}
}";
var referenced = @"
/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] args, T otherParam)
{
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("Another parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TypeParam()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""Goo{T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T$$>(string[] args, T otherParam)
{
}
}", Documentation("A type parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnboundCref()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{T}(string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T$$>(string[] args, T otherParam)
{
}
}", Documentation("A type parameter of goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInConstructor()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute.
/// </summary>
public TestClass$$()
{
}
}", Documentation("This sample shows how to specify the TestClass constructor as a cref attribute."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInConstructorOverloaded()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute.
/// </summary>
public TestClass()
{
}
/// <summary>
/// This sample shows how to specify the <see cref=""TestClass(int)""/> constructor as a cref attribute.
/// </summary>
public TestC$$lass(int value)
{
}
}", Documentation("This sample shows how to specify the TestClass(int) constructor as a cref attribute."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInGenericMethod1()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// The GetGenericValue method.
/// <para>This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.</para>
/// </summary>
public static T GetGenericVa$$lue<T>(T para)
{
return para;
}
}", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInGenericMethod2()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// The GetGenericValue method.
/// <para>This sample shows how to specify the <see cref=""GetGenericValue{T}(T)""/> method as a cref attribute.</para>
/// </summary>
public static T GetGenericVa$$lue<T>(T para)
{
return para;
}
}", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute."));
}
[WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInMethodOverloading1()
{
await TestAsync(
@"public class TestClass
{
public static int GetZero()
{
GetGenericValu$$e();
GetGenericValue(5);
}
/// <summary>
/// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method
/// </summary>
public static T GetGenericValue<T>(T para)
{
return para;
}
/// <summary>
/// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.
/// </summary>
public static void GetGenericValue()
{
}
}", Documentation("This sample shows how to specify the TestClass.GetGenericValue() method as a cref attribute."));
}
[WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInMethodOverloading2()
{
await TestAsync(
@"public class TestClass
{
public static int GetZero()
{
GetGenericValue();
GetGenericVal$$ue(5);
}
/// <summary>
/// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method
/// </summary>
public static T GetGenericValue<T>(T para)
{
return para;
}
/// <summary>
/// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.
/// </summary>
public static void GetGenericValue()
{
}
}", Documentation("This sample shows how to call the TestClass.GetGenericValue<T>(T) method"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInGenericType()
{
await TestAsync(
@"/// <summary>
/// <remarks>This example shows how to specify the <see cref=""GenericClass{T}""/> cref.</remarks>
/// </summary>
class Generic$$Class<T>
{
}",
Documentation("This example shows how to specify the GenericClass<T> cref.",
ExpectedClassifications(
Text("This example shows how to specify the"),
WhiteSpace(" "),
Class("GenericClass"),
Punctuation.OpenAngle,
TypeParameter("T"),
Punctuation.CloseAngle,
WhiteSpace(" "),
Text("cref."))));
}
[WorkItem(812720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812720")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ClassificationOfCrefsFromMetadata()
{
var code = @"
class G
{
void goo()
{
C c;
c.Go$$o();
}
}";
var referenced = @"
/// <summary></summary>
public class C
{
/// <summary>
/// See <see cref=""Goo""/> method
/// </summary>
public void Goo()
{
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#",
Documentation("See C.Goo() method",
ExpectedClassifications(
Text("See"),
WhiteSpace(" "),
Class("C"),
Punctuation.Text("."),
Identifier("Goo"),
Punctuation.OpenParen,
Punctuation.CloseParen,
WhiteSpace(" "),
Text("method"))));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FieldAvailableInBothLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
int x;
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.field}) int C.x"), Usage("") });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(37097, "https://github.com/dotnet/roslyn/issues/37097")]
public async Task BindSymbolInOtherFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""GOO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FieldUnavailableInTwoLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage(
$"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}",
expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
#if BAR
void goo()
{
x$$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[WorkItem(962353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962353")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NoValidSymbolsInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void goo()
{
B$$ar();
}
#if B
void Bar() { }
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void M()
{
int x$$;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage("") });
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalWarningInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void M()
{
#if PROJ1
int x;
#endif
int y = x$$;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true) });
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LabelsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void M()
{
$$LABEL: goto LABEL;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.label}) LABEL"), Usage("") });
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task RangeVariablesValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
using System.Linq;
class C
{
void M()
{
var x = from y in new[] {1, 2, 3} select $$y;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.range_variable}) int y"), Usage("") });
}
[WorkItem(1019766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019766")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task PointerAccessibility()
{
var markup = @"class C
{
unsafe static void Main()
{
void* p = null;
void* q = null;
dynamic d = true;
var x = p =$$= q == d;
}
}";
await TestAsync(markup, MainDescription("bool void*.operator ==(void* left, void* right)"));
}
[WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AwaitingTaskOfArrayType()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async Task<int[]> M()
{
awa$$it M();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "int[]")));
}
[WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AwaitingTaskOfDynamic()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async Task<dynamic> M()
{
awa$$it M();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "dynamic")));
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
#if TWO
void Do(string x){}
#endif
void Shared()
{
this.Do$$
}
}]]></Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = $"void C.Do(int x)";
await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription));
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ContainingType()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void Shared()
{
var x = GetThing().Do$$();
}
#if ONE
private Methods1 GetThing()
{
return new Methods1();
}
#endif
#if TWO
private Methods2 GetThing()
{
return new Methods2();
}
#endif
}
#if ONE
public class Methods1
{
public void Do(string x) { }
}
#endif
#if TWO
public class Methods2
{
public void Do(string x) { }
}
#endif
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = $"void Methods1.Do(string x)";
await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(4868, "https://github.com/dotnet/roslyn/issues/4868")]
public async Task QuickInfoExceptions()
{
await TestAsync(
@"using System;
namespace MyNs
{
class MyException1 : Exception
{
}
class MyException2 : Exception
{
}
class TestClass
{
/// <exception cref=""MyException1""></exception>
/// <exception cref=""T:MyNs.MyException2""></exception>
/// <exception cref=""System.Int32""></exception>
/// <exception cref=""double""></exception>
/// <exception cref=""Not_A_Class_But_Still_Displayed""></exception>
void M()
{
M$$();
}
}
}",
Exceptions($"\r\n{WorkspacesResources.Exceptions_colon}\r\n MyException1\r\n MyException2\r\n int\r\n double\r\n Not_A_Class_But_Still_Displayed"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLocalFunction()
{
await TestAsync(@"
class C
{
void M()
{
int i;
local$$();
void local() { i++; this.M(); }
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLocalFunction2()
{
await TestAsync(@"
class C
{
void M()
{
int i;
local$$(i);
void local(int j) { j++; M(); }
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLocalFunction3()
{
await TestAsync(@"
class C
{
public void M(int @this)
{
int i = 0;
local$$();
void local()
{
M(1);
i++;
@this++;
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction4()
{
await TestAsync(@"
class C
{
int field;
void M()
{
void OuterLocalFunction$$()
{
int local = 0;
int InnerLocalFunction()
{
field++;
return local;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction5()
{
await TestAsync(@"
class C
{
int field;
void M()
{
void OuterLocalFunction()
{
int local = 0;
int InnerLocalFunction$$()
{
field++;
return local;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction6()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
void OuterLocalFunction$$()
{
_ = local1;
void InnerLocalFunction()
{
_ = local2;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction7()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
void OuterLocalFunction()
{
_ = local1;
void InnerLocalFunction$$()
{
_ = local2;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda()
{
await TestAsync(@"
class C
{
void M()
{
int i;
System.Action a = () =$$> { i++; M(); };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda2()
{
await TestAsync(@"
class C
{
void M()
{
int i;
System.Action<int> a = j =$$> { i++; j++; M(); };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda2_DifferentOrder()
{
await TestAsync(@"
class C
{
void M(int j)
{
int i;
System.Action a = () =$$> { M(); i++; j++; };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, j, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda3()
{
await TestAsync(@"
class C
{
void M()
{
int i;
int @this;
N(() =$$> { M(); @this++; }, () => { i++; });
}
void N(System.Action x, System.Action y) { }
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda4()
{
await TestAsync(@"
class C
{
void M()
{
int i;
N(() => { M(); }, () =$$> { i++; });
}
void N(System.Action x, System.Action y) { }
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda5()
{
await TestAsync(@"
class C
{
int field;
void M()
{
System.Action a = () =$$>
{
int local = 0;
System.Func<int> b = () =>
{
field++;
return local;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda6()
{
await TestAsync(@"
class C
{
int field;
void M()
{
System.Action a = () =>
{
int local = 0;
System.Func<int> b = () =$$>
{
field++;
return local;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda7()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
System.Action a = () =$$>
{
_ = local1;
System.Action b = () =>
{
_ = local2;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda8()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
System.Action a = () =>
{
_ = local1;
System.Action b = () =$$>
{
_ = local2;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnDelegate()
{
await TestAsync(@"
class C
{
void M()
{
int i;
System.Func<bool, int> f = dele$$gate(bool b) { i++; return 1; };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(1516, "https://github.com/dotnet/roslyn/issues/1516")]
public async Task QuickInfoWithNonStandardSeeAttributesAppear()
{
await TestAsync(
@"class C
{
/// <summary>
/// <see cref=""System.String"" />
/// <see href=""http://microsoft.com"" />
/// <see langword=""null"" />
/// <see unsupported-attribute=""cat"" />
/// </summary>
void M()
{
M$$();
}
}",
Documentation(@"string http://microsoft.com null cat"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(6657, "https://github.com/dotnet/roslyn/issues/6657")]
public async Task OptionalParameterFromPreviousSubmission()
{
const string workspaceDefinition = @"
<Workspace>
<Submission Language=""C#"" CommonReferences=""true"">
void M(int x = 1) { }
</Submission>
<Submission Language=""C#"" CommonReferences=""true"">
M(x$$: 2)
</Submission>
</Workspace>
";
using var workspace = TestWorkspace.Create(XElement.Parse(workspaceDefinition), workspaceKind: WorkspaceKind.Interactive);
await TestWithOptionsAsync(workspace, MainDescription($"({ FeaturesResources.parameter }) int x = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TupleProperty()
{
await TestInMethodAsync(
@"interface I
{
(int, int) Name { get; set; }
}
class C : I
{
(int, int) I.Name$$
{
get
{
throw new System.Exception();
}
set
{
}
}
}",
MainDescription("(int, int) C.Name { get; set; }"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity0VariableName()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var y$$ = ValueTuple.Create();
}
}
",
MainDescription($"({ FeaturesResources.local_variable }) ValueTuple y"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity0ImplicitVar()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var$$ y = ValueTuple.Create();
}
}
",
MainDescription("struct System.ValueTuple"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity1VariableName()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var y$$ = ValueTuple.Create(1);
}
}
",
MainDescription($"({ FeaturesResources.local_variable }) ValueTuple<int> y"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity1ImplicitVar()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var$$ y = ValueTuple.Create(1);
}
}
",
MainDescription("struct System.ValueTuple<System.Int32>"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity2VariableName()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var y$$ = ValueTuple.Create(1, 1);
}
}
",
MainDescription($"({ FeaturesResources.local_variable }) (int, int) y"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity2ImplicitVar()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var$$ y = ValueTuple.Create(1, 1);
}
}
",
MainDescription("(System.Int32, System.Int32)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefMethod()
{
await TestInMethodAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
ref int i = ref $$goo();
}
private static ref int goo()
{
throw new NotImplementedException();
}
}",
MainDescription("ref int Program.goo()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefLocal()
{
await TestInMethodAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
ref int $$i = ref goo();
}
private static ref int goo()
{
throw new NotImplementedException();
}
}",
MainDescription($"({FeaturesResources.local_variable}) ref int i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")]
public async Task TestGenericMethodInDocComment()
{
await TestAsync(
@"
class Test
{
T F<T>()
{
F<T>();
}
/// <summary>
/// <see cref=""F$${T}()""/>
/// </summary>
void S()
{ }
}
",
MainDescription("T Test.F<T>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(403665, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=403665&_a=edit")]
public async Task TestExceptionWithCrefToConstructorDoesNotCrash()
{
await TestAsync(
@"
class Test
{
/// <summary>
/// </summary>
/// <exception cref=""Test.Test""/>
public Test$$() {}
}
",
MainDescription("Test.Test()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefStruct()
{
var markup = "ref struct X$$ {}";
await TestAsync(markup, MainDescription("ref struct X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefStruct_Nested()
{
var markup = @"
namespace Nested
{
ref struct X$$ {}
}";
await TestAsync(markup, MainDescription("ref struct Nested.X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyStruct()
{
var markup = "readonly struct X$$ {}";
await TestAsync(markup, MainDescription("readonly struct X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyStruct_Nested()
{
var markup = @"
namespace Nested
{
readonly struct X$$ {}
}";
await TestAsync(markup, MainDescription("readonly struct Nested.X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyRefStruct()
{
var markup = "readonly ref struct X$$ {}";
await TestAsync(markup, MainDescription("readonly ref struct X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyRefStruct_Nested()
{
var markup = @"
namespace Nested
{
readonly ref struct X$$ {}
}";
await TestAsync(markup, MainDescription("readonly ref struct Nested.X"));
}
[WorkItem(22450, "https://github.com/dotnet/roslyn/issues/22450")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefLikeTypesNoDeprecated()
{
var xmlString = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true"">
<MetadataReferenceFromSource Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true"">
<Document FilePath=""ReferencedDocument"">
public ref struct TestRef
{
}
</Document>
</MetadataReferenceFromSource>
<Document FilePath=""SourceDocument"">
ref struct Test
{
private $$TestRef _field;
}
</Document>
</Project>
</Workspace>";
// There should be no [deprecated] attribute displayed.
await VerifyWithReferenceWorkerAsync(xmlString, MainDescription($"ref struct TestRef"));
}
[WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task PropertyWithSameNameAsOtherType()
{
await TestAsync(
@"namespace ConsoleApplication1
{
class Program
{
static A B { get; set; }
static B A { get; set; }
static void Main(string[] args)
{
B = ConsoleApplication1.B$$.F();
}
}
class A { }
class B
{
public static A F() => null;
}
}",
MainDescription($"ConsoleApplication1.A ConsoleApplication1.B.F()"));
}
[WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task PropertyWithSameNameAsOtherType2()
{
await TestAsync(
@"using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
public static List<Bar> Bar { get; set; }
static void Main(string[] args)
{
Tes$$t<Bar>();
}
static void Test<T>() { }
}
class Bar
{
}
}",
MainDescription($"void Program.Test<Bar>()"));
}
[WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task InMalformedEmbeddedStatement_01()
{
await TestAsync(
@"
class Program
{
void method1()
{
if (method2())
.Any(b => b.Content$$Type, out var chars)
{
}
}
}
");
}
[WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task InMalformedEmbeddedStatement_02()
{
await TestAsync(
@"
class Program
{
void method1()
{
if (method2())
.Any(b => b$$.ContentType, out var chars)
{
}
}
}
",
MainDescription($"({ FeaturesResources.parameter }) ? b"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumConstraint()
{
await TestInMethodAsync(
@"
class X<T> where T : System.Enum
{
private $$T x;
}",
MainDescription($"T {FeaturesResources.in_} X<T> where T : Enum"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DelegateConstraint()
{
await TestInMethodAsync(
@"
class X<T> where T : System.Delegate
{
private $$T x;
}",
MainDescription($"T {FeaturesResources.in_} X<T> where T : Delegate"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task MulticastDelegateConstraint()
{
await TestInMethodAsync(
@"
class X<T> where T : System.MulticastDelegate
{
private $$T x;
}",
MainDescription($"T {FeaturesResources.in_} X<T> where T : MulticastDelegate"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_Type()
{
await TestAsync(
@"
class $$X<T> where T : unmanaged
{
}",
MainDescription("class X<T> where T : unmanaged"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_Method()
{
await TestAsync(
@"
class X
{
void $$M<T>() where T : unmanaged { }
}",
MainDescription("void X.M<T>() where T : unmanaged"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_Delegate()
{
await TestAsync(
"delegate void $$D<T>() where T : unmanaged;",
MainDescription("delegate void D<T>() where T : unmanaged"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_LocalFunction()
{
await TestAsync(
@"
class X
{
void N()
{
void $$M<T>() where T : unmanaged { }
}
}",
MainDescription("void M<T>() where T : unmanaged"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGetAccessorDocumentation()
{
await TestAsync(
@"
class X
{
/// <summary>Summary for property Goo</summary>
int Goo { g$$et; set; }
}",
Documentation("Summary for property Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestSetAccessorDocumentation()
{
await TestAsync(
@"
class X
{
/// <summary>Summary for property Goo</summary>
int Goo { get; s$$et; }
}",
Documentation("Summary for property Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventAddDocumentation1()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo
{
a$$dd => throw null;
remove => throw null;
}
}",
Documentation("Summary for event Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventAddDocumentation2()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo;
void M() => Goo +$$= null;
}",
Documentation("Summary for event Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventRemoveDocumentation1()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo
{
add => throw null;
r$$emove => throw null;
}
}",
Documentation("Summary for event Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventRemoveDocumentation2()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo;
void M() => Goo -$$= null;
}",
Documentation("Summary for event Goo"));
}
[WorkItem(30642, "https://github.com/dotnet/roslyn/issues/30642")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task BuiltInOperatorWithUserDefinedEquivalent()
{
await TestAsync(
@"
class X
{
void N(string a, string b)
{
var v = a $$== b;
}
}",
MainDescription("bool string.operator ==(string a, string b)"),
SymbolGlyph(Glyph.Operator));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_Type()
{
await TestAsync(
@"
class $$X<T> where T : notnull
{
}",
MainDescription("class X<T> where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_Method()
{
await TestAsync(
@"
class X
{
void $$M<T>() where T : notnull { }
}",
MainDescription("void X.M<T>() where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_Delegate()
{
await TestAsync(
"delegate void $$D<T>() where T : notnull;",
MainDescription("delegate void D<T>() where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_LocalFunction()
{
await TestAsync(
@"
class X
{
void N()
{
void $$M<T>() where T : notnull { }
}
}",
MainDescription("void M<T>() where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableParameterThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
void N(string? s)
{
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.parameter}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableParameterThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
void N(string? s)
{
s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.parameter}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableFieldThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? s = null;
void N()
{
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.field}) string? X.s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableFieldThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? s = null;
void N()
{
s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.field}) string? X.s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullablePropertyThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? S { get; set; }
void N()
{
string s2 = $$S;
}
}",
MainDescription("string? X.S { get; set; }"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "S")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullablePropertyThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? S { get; set; }
void N()
{
S = """";
string s2 = $$S;
}
}",
MainDescription("string? X.S { get; set; }"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "S")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableRangeVariableThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
IEnumerable<string?> enumerable;
foreach (var s in enumerable)
{
string s2 = $$s;
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableRangeVariableThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
IEnumerable<string> enumerable;
foreach (var s in enumerable)
{
string s2 = $$s;
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableLocalThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
string? s = null;
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableLocalThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
string? s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownPriorToLanguageVersion8()
{
await TestWithOptionsAsync(TestOptions.Regular7_3,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
string s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string s"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownInNullableDisable()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable disable
using System.Collections.Generic;
class X
{
void N()
{
string s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string s"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableShownWhenEnabledGlobally()
{
await TestWithOptionsAsync(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable),
@"using System.Collections.Generic;
class X
{
void N()
{
string s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownForValueType()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
int a = 0;
int b = $$a;
}
}",
MainDescription($"({FeaturesResources.local_variable}) int a"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownForConst()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
const string? s = null;
string? s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_constant}) string? s = null"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocInlineSummary()
{
var markup =
@"
/// <summary>Summary documentation</summary>
/// <remarks>Remarks documentation</remarks>
void M(int x) { }
/// <summary><inheritdoc cref=""M(int)""/></summary>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation("Summary documentation"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocTwoLevels1()
{
var markup =
@"
/// <summary>Summary documentation</summary>
/// <remarks>Remarks documentation</remarks>
void M() { }
/// <inheritdoc cref=""M()""/>
void M(int x) { }
/// <inheritdoc cref=""M(int)""/>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation("Summary documentation"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocTwoLevels2()
{
var markup =
@"
/// <summary>Summary documentation</summary>
/// <remarks>Remarks documentation</remarks>
void M() { }
/// <summary><inheritdoc cref=""M()""/></summary>
void M(int x) { }
/// <summary><inheritdoc cref=""M(int)""/></summary>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation("Summary documentation"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocWithTypeParamRef()
{
var markup =
@"
public class Program
{
public static void Main() => _ = new Test<int>().$$Clone();
}
public class Test<T> : ICloneable<Test<T>>
{
/// <inheritdoc/>
public Test<T> Clone() => new();
}
/// <summary>A type that has clonable instances.</summary>
/// <typeparam name=""T"">The type of instances that can be cloned.</typeparam>
public interface ICloneable<T>
{
/// <summary>Clones a <typeparamref name=""T""/>.</summary>
/// <returns>A clone of the <typeparamref name=""T""/>.</returns>
public T Clone();
}";
await TestInClassAsync(markup,
MainDescription("Test<int> Test<int>.Clone()"),
Documentation("Clones a Test<T>."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocCycle1()
{
var markup =
@"
/// <inheritdoc cref=""M(int, int)""/>
void M(int x) { }
/// <inheritdoc cref=""M(int)""/>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocCycle2()
{
var markup =
@"
/// <inheritdoc cref=""M(int)""/>
void $$M(int x) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x)"),
Documentation(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocCycle3()
{
var markup =
@"
/// <inheritdoc cref=""M""/>
void $$M(int x) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x)"),
Documentation(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38794, "https://github.com/dotnet/roslyn/issues/38794")]
public async Task TestLinqGroupVariableDeclaration()
{
var code =
@"
void M(string[] a)
{
var v = from x in a
group x by x.Length into $$g
select g;
}";
await TestInClassAsync(code,
MainDescription($"({FeaturesResources.range_variable}) IGrouping<int, string> g"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")]
public async Task QuickInfoOnIndexerCloseBracket()
{
await TestAsync(@"
class C
{
public int this[int x] { get { return 1; } }
void M()
{
var x = new C()[5$$];
}
}",
MainDescription("int C.this[int x] { get; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")]
public async Task QuickInfoOnIndexerOpenBracket()
{
await TestAsync(@"
class C
{
public int this[int x] { get { return 1; } }
void M()
{
var x = new C()$$[5];
}
}",
MainDescription("int C.this[int x] { get; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")]
public async Task QuickInfoOnIndexer_NotOnArrayAccess()
{
await TestAsync(@"
class Program
{
void M()
{
int[] x = new int[4];
int y = x[3$$];
}
}",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithRemarksOnMethod()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <remarks>
/// Remarks text
/// </remarks>
int M()
{
return $$M();
}
}",
MainDescription("int Program.M()"),
Documentation("Summary text"),
Remarks("\r\nRemarks text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithRemarksOnPropertyAccessor()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <remarks>
/// Remarks text
/// </remarks>
int M { $$get; }
}",
MainDescription("int Program.M.get"),
Documentation("Summary text"),
Remarks("\r\nRemarks text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithReturnsOnMethod()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <returns>
/// Returns text
/// </returns>
int M()
{
return $$M();
}
}",
MainDescription("int Program.M()"),
Documentation("Summary text"),
Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithReturnsOnPropertyAccessor()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <returns>
/// Returns text
/// </returns>
int M { $$get; }
}",
MainDescription("int Program.M.get"),
Documentation("Summary text"),
Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithValueOnMethod()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <value>
/// Value text
/// </value>
int M()
{
return $$M();
}
}",
MainDescription("int Program.M()"),
Documentation("Summary text"),
Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithValueOnPropertyAccessor()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <value>
/// Value text
/// </value>
int M { $$get; }
}",
MainDescription("int Program.M.get"),
Documentation("Summary text"),
Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoNotPattern1()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is not $$Person p)
{
}
}
}",
MainDescription("class Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoNotPattern2()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is $$not Person p)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoOrPattern1()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is $$Person or int)
{
}
}
}", MainDescription("class Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoOrPattern2()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is Person or $$int)
{
}
}
}", MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoOrPattern3()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is Person $$or int)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoRecord()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("record Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoDerivedRecord()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record Person(string First, string Last)
{
}
record Student(string Id)
{
void M($$Student p)
{
}
}
", MainDescription("record Student"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(44904, "https://github.com/dotnet/roslyn/issues/44904")]
public async Task QuickInfoRecord_BaseTypeList()
{
await TestAsync(@"
record Person(string First, string Last);
record Student(int Id) : $$Person(null, null);
", MainDescription("Person.Person(string First, string Last)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfo_BaseConstructorInitializer()
{
await TestAsync(@"
public class Person { public Person(int id) { } }
public class Student : Person { public Student() : $$base(0) { } }
", MainDescription("Person.Person(int id)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoRecordClass()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record class Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("record Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoRecordStruct()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record struct Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("record struct Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoReadOnlyRecordStruct()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"readonly record struct Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("readonly record struct Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(51615, "https://github.com/dotnet/roslyn/issues/51615")]
public async Task TestVarPatternOnVarKeyword()
{
await TestAsync(
@"class C
{
string M() { }
void M2()
{
if (M() is va$$r x && x.Length > 0)
{
}
}
}",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVarPatternOnVariableItself()
{
await TestAsync(
@"class C
{
string M() { }
void M2()
{
if (M() is var x$$ && x.Length > 0)
{
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? x"));
}
[WorkItem(53135, "https://github.com/dotnet/roslyn/issues/53135")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationCData()
{
var markup =
@"using I$$ = IGoo;
/// <summary>
/// summary for interface IGoo
/// <code><![CDATA[
/// List<string> y = null;
/// ]]></code>
/// </summary>
interface IGoo { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation(@"summary for interface IGoo
List<string> y = null;"));
}
[WorkItem(37503, "https://github.com/dotnet/roslyn/issues/37503")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DoNotNormalizeWhitespaceForCode()
{
var markup =
@"using I$$ = IGoo;
/// <summary>
/// Normalize this, and <c>Also this</c>
/// <code>
/// line 1
/// line 2
/// </code>
/// </summary>
interface IGoo { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation(@"Normalize this, and Also this
line 1
line 2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ImplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
public static void $$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ImplicitImplementation_FromReference()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
public static void M1() { }
}
class R
{
public static void M() { C1_1.$$M1(); }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_FromTypeParameterReference()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class R
{
public static void M<T>() where T : I1 { T.$$M1(); }
}
";
await TestAsync(
code,
MainDescription("void I1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ExplicitInheritdoc_ImplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
/// <inheritdoc/>
public static void $$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ExplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
static void I1.$$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ExplicitInheritdoc_ExplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
/// <inheritdoc/>
static void I1.$$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoLambdaReturnType_01()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"class Program
{
System.Delegate D = bo$$ol () => true;
}",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoLambdaReturnType_02()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"class A
{
struct B { }
System.Delegate D = A.B$$ () => null;
}",
MainDescription("struct A.B"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoLambdaReturnType_03()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"class A<T>
{
}
struct B
{
System.Delegate D = A<B$$> () => null;
}",
MainDescription("struct B"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNormalFuncSynthesizedLambdaType()
{
await TestAsync(
@"class C
{
void M()
{
$$var v = (int i) => i.ToString();
}
}",
MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"),
TypeParameterMap($@"
T {FeaturesResources.is_} int
TResult {FeaturesResources.is_} string"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAnonymousSynthesizedLambdaType()
{
await TestAsync(
@"class C
{
void M()
{
$$var v = (ref int i) => i.ToString();
}
}",
MainDescription("delegate string <anonymous delegate>(ref int)"));
}
}
}
| 1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.AbstractSymbolDescriptionBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal partial class AbstractSymbolDisplayService
{
protected abstract partial class AbstractSymbolDescriptionBuilder
{
private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat =
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance |
SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions: SymbolDisplayParameterOptions.None,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat =
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions:
SymbolDisplayMemberOptions.IncludeRef |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
propertyStyle:
SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeOptionalBrackets,
localOptions:
SymbolDisplayLocalOptions.IncludeRef |
SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName |
SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier |
SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral);
private static readonly SymbolDisplayFormat s_descriptionStyle =
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword);
private static readonly SymbolDisplayFormat s_globalNamespaceStyle =
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included);
private readonly SemanticModel _semanticModel;
private readonly int _position;
private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService;
private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap = new();
private readonly Dictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>> _documentationMap = new();
private readonly Func<ISymbol, string> _getNavigationHint;
protected readonly Workspace Workspace;
protected readonly CancellationToken CancellationToken;
protected AbstractSymbolDescriptionBuilder(
SemanticModel semanticModel,
int position,
Workspace workspace,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
CancellationToken cancellationToken)
{
_anonymousTypeDisplayService = anonymousTypeDisplayService;
Workspace = workspace;
CancellationToken = cancellationToken;
_semanticModel = semanticModel;
_position = position;
_getNavigationHint = GetNavigationHint;
}
protected abstract void AddExtensionPrefix();
protected abstract void AddAwaitablePrefix();
protected abstract void AddAwaitableExtensionPrefix();
protected abstract void AddDeprecatedPrefix();
protected abstract void AddEnumUnderlyingTypeSeparator();
protected abstract Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol);
protected abstract ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format);
protected abstract string GetNavigationHint(ISymbol symbol);
protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; }
protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; }
protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstantsAndModifiers { get; }
protected SemanticModel GetSemanticModel(SyntaxTree tree)
{
if (_semanticModel.SyntaxTree == tree)
{
return _semanticModel;
}
var model = _semanticModel.GetOriginalSemanticModel();
if (model.Compilation.ContainsSyntaxTree(tree))
{
return model.Compilation.GetSemanticModel(tree);
}
// it is from one of its p2p references
foreach (var referencedCompilation in model.Compilation.GetReferencedCompilations())
{
// find the reference that contains the given tree
if (referencedCompilation.ContainsSyntaxTree(tree))
{
return referencedCompilation.GetSemanticModel(tree);
}
}
// the tree, a source symbol is defined in, doesn't exist in universe
// how this can happen?
Debug.Assert(false, "How?");
return null;
}
protected Compilation GetCompilation()
=> _semanticModel.Compilation;
private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols)
{
var firstSymbol = symbols[0];
await AddDescriptionPartAsync(firstSymbol).ConfigureAwait(false);
AddOverloadCountPart(symbols);
FixAllAnonymousTypes(firstSymbol);
AddExceptions(firstSymbol);
AddCaptures(firstSymbol);
AddDocumentationContent(firstSymbol);
}
private void AddDocumentationContent(ISymbol symbol)
{
var formatter = Workspace.Services.GetLanguageServices(_semanticModel.Language).GetRequiredService<IDocumentationCommentFormattingService>();
if (symbol is IParameterSymbol or ITypeParameterSymbol)
{
// Can just defer to the standard helper here. We only want to get the summary portion for just the
// param/type-param and we have no need for remarks/returns/value.
_documentationMap.Add(
SymbolDescriptionGroups.Documentation,
symbol.GetDocumentationParts(_semanticModel, _position, formatter, CancellationToken));
return;
}
if (symbol is IAliasSymbol alias)
symbol = alias.Target;
var original = symbol.OriginalDefinition;
var format = ISymbolExtensions2.CrefFormat;
var compilation = _semanticModel.Compilation;
// Grab the doc comment once as computing it for each portion we're concatenating can be expensive for
// lsif (which does this for every symbol in an entire solution).
var documentationComment = original is IMethodSymbol method
? ISymbolExtensions2.GetMethodDocumentation(method, compilation, CancellationToken)
: original.GetDocumentationComment(compilation, expandIncludes: true, expandInheritdoc: true, cancellationToken: CancellationToken);
_documentationMap.Add(
SymbolDescriptionGroups.Documentation,
formatter.Format(documentationComment.SummaryText, symbol, _semanticModel, _position, format, CancellationToken));
_documentationMap.Add(
SymbolDescriptionGroups.RemarksDocumentation,
formatter.Format(documentationComment.RemarksText, symbol, _semanticModel, _position, format, CancellationToken));
AddReturnsDocumentationParts(symbol, formatter);
AddValueDocumentationParts(symbol, formatter);
return;
void AddReturnsDocumentationParts(ISymbol symbol, IDocumentationCommentFormattingService formatter)
{
var parts = formatter.Format(documentationComment.ReturnsText, symbol, _semanticModel, _position, format, CancellationToken);
if (!parts.IsDefaultOrEmpty)
{
using var _ = ArrayBuilder<TaggedText>.GetInstance(out var builder);
builder.Add(new TaggedText(TextTags.Text, FeaturesResources.Returns_colon));
builder.AddRange(LineBreak().ToTaggedText());
builder.Add(new TaggedText(TextTags.ContainerStart, " "));
builder.AddRange(parts);
builder.Add(new TaggedText(TextTags.ContainerEnd, string.Empty));
_documentationMap.Add(SymbolDescriptionGroups.ReturnsDocumentation, builder.ToImmutable());
}
}
void AddValueDocumentationParts(ISymbol symbol, IDocumentationCommentFormattingService formatter)
{
var parts = formatter.Format(documentationComment.ValueText, symbol, _semanticModel, _position, format, CancellationToken);
if (!parts.IsDefaultOrEmpty)
{
using var _ = ArrayBuilder<TaggedText>.GetInstance(out var builder);
builder.Add(new TaggedText(TextTags.Text, FeaturesResources.Value_colon));
builder.AddRange(LineBreak().ToTaggedText());
builder.Add(new TaggedText(TextTags.ContainerStart, " "));
builder.AddRange(parts);
builder.Add(new TaggedText(TextTags.ContainerEnd, string.Empty));
_documentationMap.Add(SymbolDescriptionGroups.ValueDocumentation, builder.ToImmutable());
}
}
}
private void AddExceptions(ISymbol symbol)
{
var exceptionTypes = symbol.GetDocumentationComment(GetCompilation(), expandIncludes: true, expandInheritdoc: true).ExceptionTypes;
if (exceptionTypes.Any())
{
var parts = new List<SymbolDisplayPart>();
parts.AddLineBreak();
parts.AddText(WorkspacesResources.Exceptions_colon);
foreach (var exceptionString in exceptionTypes)
{
parts.AddRange(LineBreak());
parts.AddRange(Space(count: 2));
parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel));
}
AddToGroup(SymbolDescriptionGroups.Exceptions, parts);
}
}
/// <summary>
/// If the symbol is a local or anonymous function (lambda or delegate), adds the variables captured
/// by that local or anonymous function to the "Captures" group.
/// </summary>
/// <param name="symbol"></param>
protected abstract void AddCaptures(ISymbol symbol);
/// <summary>
/// Given the body of a local or an anonymous function (lambda or delegate), add the variables captured
/// by that local or anonymous function to the "Captures" group.
/// </summary>
protected void AddCaptures(SyntaxNode syntax)
{
var semanticModel = GetSemanticModel(syntax.SyntaxTree);
if (semanticModel.IsSpeculativeSemanticModel)
{
// The region analysis APIs used below are not meaningful/applicable in the context of speculation (because they are designed
// to ask questions about an expression if it were in a certain *scope* of code, not if it were inserted at a certain *position*).
//
// But in the context of symbol completion, we do prepare a description for the symbol while speculating. Only the "main description"
// section of that description will be displayed. We still add a "captures" section, just in case.
AddToGroup(SymbolDescriptionGroups.Captures, LineBreak());
AddToGroup(SymbolDescriptionGroups.Captures, PlainText($"{WorkspacesResources.Variables_captured_colon} ?"));
return;
}
var analysis = semanticModel.AnalyzeDataFlow(syntax);
var captures = analysis.CapturedInside.Except(analysis.VariablesDeclared).ToImmutableArray();
if (!captures.IsEmpty)
{
var parts = new List<SymbolDisplayPart>();
parts.AddLineBreak();
parts.AddText(WorkspacesResources.Variables_captured_colon);
var first = true;
foreach (var captured in captures)
{
if (!first)
{
parts.AddRange(Punctuation(","));
}
parts.AddRange(Space(count: 1));
parts.AddRange(ToMinimalDisplayParts(captured, s_formatForCaptures));
first = false;
}
AddToGroup(SymbolDescriptionGroups.Captures, parts);
}
}
private static readonly SymbolDisplayFormat s_formatForCaptures = SymbolDisplayFormat.MinimallyQualifiedFormat
.RemoveLocalOptions(SymbolDisplayLocalOptions.IncludeType)
.RemoveParameterOptions(SymbolDisplayParameterOptions.IncludeType);
public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync(
ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return BuildDescription(groups);
}
public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return BuildDescriptionSections();
}
private async Task AddDescriptionPartAsync(ISymbol symbol)
{
if (symbol.IsObsolete())
{
AddDeprecatedPrefix();
}
if (symbol is IDiscardSymbol discard)
{
AddDescriptionForDiscard(discard);
}
else if (symbol is IDynamicTypeSymbol)
{
AddDescriptionForDynamicType();
}
else if (symbol is IFieldSymbol field)
{
await AddDescriptionForFieldAsync(field).ConfigureAwait(false);
}
else if (symbol is ILocalSymbol local)
{
await AddDescriptionForLocalAsync(local).ConfigureAwait(false);
}
else if (symbol is IMethodSymbol method)
{
AddDescriptionForMethod(method);
}
else if (symbol is ILabelSymbol label)
{
AddDescriptionForLabel(label);
}
else if (symbol is INamedTypeSymbol namedType)
{
if (namedType.IsTupleType)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.ToDisplayParts(s_descriptionStyle));
}
else
{
AddDescriptionForNamedType(namedType);
}
}
else if (symbol is INamespaceSymbol namespaceSymbol)
{
AddDescriptionForNamespace(namespaceSymbol);
}
else if (symbol is IParameterSymbol parameter)
{
await AddDescriptionForParameterAsync(parameter).ConfigureAwait(false);
}
else if (symbol is IPropertySymbol property)
{
AddDescriptionForProperty(property);
}
else if (symbol is IRangeVariableSymbol rangeVariable)
{
AddDescriptionForRangeVariable(rangeVariable);
}
else if (symbol is ITypeParameterSymbol typeParameter)
{
AddDescriptionForTypeParameter(typeParameter);
}
else if (symbol is IAliasSymbol alias)
{
await AddDescriptionPartAsync(alias.Target).ConfigureAwait(false);
}
else
{
AddDescriptionForArbitrarySymbol(symbol);
}
}
private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups)
{
var finalParts = new List<SymbolDisplayPart>();
var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2);
foreach (var group in orderedGroups)
{
if ((groups & group) == 0)
{
continue;
}
if (!finalParts.IsEmpty())
{
var newLines = GetPrecedingNewLineCount(group);
finalParts.AddRange(LineBreak(newLines));
}
var parts = _groupMap[group];
finalParts.AddRange(parts);
}
return finalParts.AsImmutable();
}
private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group)
{
switch (group)
{
case SymbolDescriptionGroups.MainDescription:
// these parts are continuations of whatever text came before them
return 0;
case SymbolDescriptionGroups.Documentation:
case SymbolDescriptionGroups.RemarksDocumentation:
case SymbolDescriptionGroups.ReturnsDocumentation:
case SymbolDescriptionGroups.ValueDocumentation:
return 1;
case SymbolDescriptionGroups.AnonymousTypes:
return 0;
case SymbolDescriptionGroups.Exceptions:
case SymbolDescriptionGroups.TypeParameterMap:
case SymbolDescriptionGroups.Captures:
// Everything else is in a group on its own
return 2;
default:
throw ExceptionUtilities.UnexpectedValue(group);
}
}
private IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>> BuildDescriptionSections()
{
var includeNavigationHints = this.Workspace.Options.GetOption(QuickInfoOptions.IncludeNavigationHintsInQuickInfo);
// Merge the two maps into one final result.
var result = new Dictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>(_documentationMap);
foreach (var (group, parts) in _groupMap)
{
var taggedText = parts.ToTaggedText(_getNavigationHint, includeNavigationHints);
if (group == SymbolDescriptionGroups.MainDescription)
{
// Mark the main description as a code block.
taggedText = taggedText
.Insert(0, new TaggedText(TextTags.CodeBlockStart, string.Empty))
.Add(new TaggedText(TextTags.CodeBlockEnd, string.Empty));
}
result[group] = taggedText;
}
return result;
}
private void AddDescriptionForDynamicType()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Keyword("dynamic"));
AddToGroup(SymbolDescriptionGroups.Documentation,
PlainText(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime));
}
private void AddDescriptionForNamedType(INamedTypeSymbol symbol)
{
if (symbol.IsAwaitableNonDynamic(_semanticModel, _position))
{
AddAwaitablePrefix();
}
AddSymbolDescription(symbol);
if (!symbol.IsUnboundGenericType && !TypeArgumentsAndParametersAreSame(symbol))
{
var allTypeParameters = symbol.GetAllTypeParameters().ToList();
var allTypeArguments = symbol.GetAllTypeArguments().ToList();
AddTypeParameterMapPart(allTypeParameters, allTypeArguments);
}
if (symbol.IsEnumType() && symbol.EnumUnderlyingType.SpecialType != SpecialType.System_Int32)
{
AddEnumUnderlyingTypeSeparator();
var underlyingTypeDisplayParts = symbol.EnumUnderlyingType.ToDisplayParts(s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes));
AddToGroup(SymbolDescriptionGroups.MainDescription, underlyingTypeDisplayParts);
}
}
private void AddSymbolDescription(INamedTypeSymbol symbol)
{
if (symbol.TypeKind == TypeKind.Delegate)
{
var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.OriginalDefinition.ToDisplayParts(style));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.OriginalDefinition.ToDisplayParts(s_descriptionStyle));
}
}
private static bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol)
{
var typeArguments = symbol.GetAllTypeArguments().ToList();
var typeParameters = symbol.GetAllTypeParameters().ToList();
for (var i = 0; i < typeArguments.Count; i++)
{
var typeArgument = typeArguments[i];
var typeParameter = typeParameters[i];
if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name)
{
continue;
}
return false;
}
return true;
}
private void AddDescriptionForNamespace(INamespaceSymbol symbol)
{
if (symbol.IsGlobalNamespace)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.ToDisplayParts(s_globalNamespaceStyle));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.ToDisplayParts(s_descriptionStyle));
}
}
private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol)
{
var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false);
// Don't bother showing disambiguating text for enum members. The icon displayed
// on Quick Info should be enough.
if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum)
{
AddToGroup(SymbolDescriptionGroups.MainDescription, parts);
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.constant)
: Description(FeaturesResources.field),
parts);
}
}
private async Task<ImmutableArray<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (!initializerParts.IsDefaultOrEmpty)
{
using var _ = ArrayBuilder<SymbolDisplayPart>.GetInstance(out var parts);
parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat));
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts.ToImmutable();
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstantsAndModifiers);
}
private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol)
{
var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false);
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.local_constant)
: Description(FeaturesResources.local_variable),
parts);
}
private async Task<ImmutableArray<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
using var _ = ArrayBuilder<SymbolDisplayPart>.GetInstance(out var parts);
parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat));
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts.ToImmutable();
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private void AddDescriptionForLabel(ILabelSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.label),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.range_variable),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForMethod(IMethodSymbol method)
{
// TODO : show duplicated member case
var awaitable = method.IsAwaitableNonDynamic(_semanticModel, _position);
var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension;
if (awaitable && extension)
{
AddAwaitableExtensionPrefix();
}
else if (awaitable)
{
AddAwaitablePrefix();
}
else if (extension)
{
AddExtensionPrefix();
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat));
}
private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol)
{
if (symbol.IsOptional)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (!initializerParts.IsDefaultOrEmpty)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.parameter), parts);
return;
}
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(symbol.IsDiscard ? FeaturesResources.discard : FeaturesResources.parameter),
ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants));
}
private void AddDescriptionForDiscard(IDiscardSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.discard),
ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants));
}
protected void AddDescriptionForProperty(IPropertySymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat));
}
private void AddDescriptionForArbitrarySymbol(ISymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol)
{
Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol),
Space(),
PlainText(FeaturesResources.in_),
Space(),
ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat));
}
private void AddOverloadCountPart(
ImmutableArray<ISymbol> symbolGroup)
{
var count = GetOverloadCount(symbolGroup);
if (count >= 1)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Space(),
Punctuation("("),
Punctuation("+"),
Space(),
PlainText(count.ToString()),
Space(),
count == 1 ? PlainText(FeaturesResources.overload) : PlainText(FeaturesResources.overloads_),
Punctuation(")"));
}
}
private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup)
{
return symbolGroup.Select(s => s.OriginalDefinition)
.Where(s => !s.Equals(symbolGroup.First().OriginalDefinition))
.Where(s => s is IMethodSymbol || s.IsIndexer())
.Count();
}
protected void AddTypeParameterMapPart(
List<ITypeParameterSymbol> typeParameters,
List<ITypeSymbol> typeArguments)
{
var parts = new List<SymbolDisplayPart>();
var count = typeParameters.Count;
for (var i = 0; i < count; i++)
{
parts.AddRange(TypeParameterName(typeParameters[i].Name));
parts.AddRange(Space());
parts.AddRange(PlainText(FeaturesResources.is_));
parts.AddRange(Space());
parts.AddRange(ToMinimalDisplayParts(typeArguments[i]));
if (i < count - 1)
{
parts.AddRange(LineBreak());
}
}
AddToGroup(SymbolDescriptionGroups.TypeParameterMap,
parts);
}
protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray)
=> AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray);
protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray)
{
var partsList = partsArray.Flatten().ToList();
if (partsList.Count > 0)
{
if (!_groupMap.TryGetValue(group, out var existingParts))
{
existingParts = new List<SymbolDisplayPart>();
_groupMap.Add(group, existingParts);
}
existingParts.AddRange(partsList);
}
}
private static IEnumerable<SymbolDisplayPart> Description(string description)
{
return Punctuation("(")
.Concat(PlainText(description))
.Concat(Punctuation(")"))
.Concat(Space());
}
protected static IEnumerable<SymbolDisplayPart> Keyword(string text)
=> Part(SymbolDisplayPartKind.Keyword, text);
protected static IEnumerable<SymbolDisplayPart> LineBreak(int count = 1)
{
for (var i = 0; i < count; i++)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n");
}
}
protected static IEnumerable<SymbolDisplayPart> PlainText(string text)
=> Part(SymbolDisplayPartKind.Text, text);
protected static IEnumerable<SymbolDisplayPart> Punctuation(string text)
=> Part(SymbolDisplayPartKind.Punctuation, text);
protected static IEnumerable<SymbolDisplayPart> Space(int count = 1)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count));
}
protected ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
format ??= MinimallyQualifiedFormat;
return ToMinimalDisplayParts(symbol, _semanticModel, _position, format);
}
private static IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text)
{
yield return new SymbolDisplayPart(kind, symbol, text);
}
private static IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text)
=> Part(kind, null, text);
private static IEnumerable<SymbolDisplayPart> TypeParameterName(string text)
=> Part(SymbolDisplayPartKind.TypeParameterName, text);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal partial class AbstractSymbolDisplayService
{
protected abstract partial class AbstractSymbolDescriptionBuilder
{
private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat =
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance |
SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions: SymbolDisplayParameterOptions.None,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat =
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions:
SymbolDisplayMemberOptions.IncludeRef |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
propertyStyle:
SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeOptionalBrackets,
localOptions:
SymbolDisplayLocalOptions.IncludeRef |
SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName |
SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier |
SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral);
private static readonly SymbolDisplayFormat s_descriptionStyle =
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword);
private static readonly SymbolDisplayFormat s_globalNamespaceStyle =
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included);
private readonly SemanticModel _semanticModel;
private readonly int _position;
private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService;
private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap = new();
private readonly Dictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>> _documentationMap = new();
private readonly Func<ISymbol, string> _getNavigationHint;
protected readonly Workspace Workspace;
protected readonly CancellationToken CancellationToken;
protected AbstractSymbolDescriptionBuilder(
SemanticModel semanticModel,
int position,
Workspace workspace,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
CancellationToken cancellationToken)
{
_anonymousTypeDisplayService = anonymousTypeDisplayService;
Workspace = workspace;
CancellationToken = cancellationToken;
_semanticModel = semanticModel;
_position = position;
_getNavigationHint = GetNavigationHint;
}
protected abstract void AddExtensionPrefix();
protected abstract void AddAwaitablePrefix();
protected abstract void AddAwaitableExtensionPrefix();
protected abstract void AddDeprecatedPrefix();
protected abstract void AddEnumUnderlyingTypeSeparator();
protected abstract Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol);
protected abstract ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format);
protected abstract string GetNavigationHint(ISymbol symbol);
protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; }
protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; }
protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstantsAndModifiers { get; }
protected SemanticModel GetSemanticModel(SyntaxTree tree)
{
if (_semanticModel.SyntaxTree == tree)
{
return _semanticModel;
}
var model = _semanticModel.GetOriginalSemanticModel();
if (model.Compilation.ContainsSyntaxTree(tree))
{
return model.Compilation.GetSemanticModel(tree);
}
// it is from one of its p2p references
foreach (var referencedCompilation in model.Compilation.GetReferencedCompilations())
{
// find the reference that contains the given tree
if (referencedCompilation.ContainsSyntaxTree(tree))
{
return referencedCompilation.GetSemanticModel(tree);
}
}
// the tree, a source symbol is defined in, doesn't exist in universe
// how this can happen?
Debug.Assert(false, "How?");
return null;
}
protected Compilation GetCompilation()
=> _semanticModel.Compilation;
private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols)
{
var firstSymbol = symbols[0];
await AddDescriptionPartAsync(firstSymbol).ConfigureAwait(false);
AddOverloadCountPart(symbols);
FixAllAnonymousTypes(firstSymbol);
AddExceptions(firstSymbol);
AddCaptures(firstSymbol);
AddDocumentationContent(firstSymbol);
}
private void AddDocumentationContent(ISymbol symbol)
{
var formatter = Workspace.Services.GetLanguageServices(_semanticModel.Language).GetRequiredService<IDocumentationCommentFormattingService>();
if (symbol is IParameterSymbol or ITypeParameterSymbol)
{
// Can just defer to the standard helper here. We only want to get the summary portion for just the
// param/type-param and we have no need for remarks/returns/value.
_documentationMap.Add(
SymbolDescriptionGroups.Documentation,
symbol.GetDocumentationParts(_semanticModel, _position, formatter, CancellationToken));
return;
}
if (symbol is IAliasSymbol alias)
symbol = alias.Target;
var original = symbol.OriginalDefinition;
var format = ISymbolExtensions2.CrefFormat;
var compilation = _semanticModel.Compilation;
// Grab the doc comment once as computing it for each portion we're concatenating can be expensive for
// lsif (which does this for every symbol in an entire solution).
var documentationComment = original is IMethodSymbol method
? ISymbolExtensions2.GetMethodDocumentation(method, compilation, CancellationToken)
: original.GetDocumentationComment(compilation, expandIncludes: true, expandInheritdoc: true, cancellationToken: CancellationToken);
_documentationMap.Add(
SymbolDescriptionGroups.Documentation,
formatter.Format(documentationComment.SummaryText, symbol, _semanticModel, _position, format, CancellationToken));
_documentationMap.Add(
SymbolDescriptionGroups.RemarksDocumentation,
formatter.Format(documentationComment.RemarksText, symbol, _semanticModel, _position, format, CancellationToken));
AddReturnsDocumentationParts(symbol, formatter);
AddValueDocumentationParts(symbol, formatter);
return;
void AddReturnsDocumentationParts(ISymbol symbol, IDocumentationCommentFormattingService formatter)
{
var parts = formatter.Format(documentationComment.ReturnsText, symbol, _semanticModel, _position, format, CancellationToken);
if (!parts.IsDefaultOrEmpty)
{
using var _ = ArrayBuilder<TaggedText>.GetInstance(out var builder);
builder.Add(new TaggedText(TextTags.Text, FeaturesResources.Returns_colon));
builder.AddRange(LineBreak().ToTaggedText());
builder.Add(new TaggedText(TextTags.ContainerStart, " "));
builder.AddRange(parts);
builder.Add(new TaggedText(TextTags.ContainerEnd, string.Empty));
_documentationMap.Add(SymbolDescriptionGroups.ReturnsDocumentation, builder.ToImmutable());
}
}
void AddValueDocumentationParts(ISymbol symbol, IDocumentationCommentFormattingService formatter)
{
var parts = formatter.Format(documentationComment.ValueText, symbol, _semanticModel, _position, format, CancellationToken);
if (!parts.IsDefaultOrEmpty)
{
using var _ = ArrayBuilder<TaggedText>.GetInstance(out var builder);
builder.Add(new TaggedText(TextTags.Text, FeaturesResources.Value_colon));
builder.AddRange(LineBreak().ToTaggedText());
builder.Add(new TaggedText(TextTags.ContainerStart, " "));
builder.AddRange(parts);
builder.Add(new TaggedText(TextTags.ContainerEnd, string.Empty));
_documentationMap.Add(SymbolDescriptionGroups.ValueDocumentation, builder.ToImmutable());
}
}
}
private void AddExceptions(ISymbol symbol)
{
var exceptionTypes = symbol.GetDocumentationComment(GetCompilation(), expandIncludes: true, expandInheritdoc: true).ExceptionTypes;
if (exceptionTypes.Any())
{
var parts = new List<SymbolDisplayPart>();
parts.AddLineBreak();
parts.AddText(WorkspacesResources.Exceptions_colon);
foreach (var exceptionString in exceptionTypes)
{
parts.AddRange(LineBreak());
parts.AddRange(Space(count: 2));
parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel));
}
AddToGroup(SymbolDescriptionGroups.Exceptions, parts);
}
}
/// <summary>
/// If the symbol is a local or anonymous function (lambda or delegate), adds the variables captured
/// by that local or anonymous function to the "Captures" group.
/// </summary>
/// <param name="symbol"></param>
protected abstract void AddCaptures(ISymbol symbol);
/// <summary>
/// Given the body of a local or an anonymous function (lambda or delegate), add the variables captured
/// by that local or anonymous function to the "Captures" group.
/// </summary>
protected void AddCaptures(SyntaxNode syntax)
{
var semanticModel = GetSemanticModel(syntax.SyntaxTree);
if (semanticModel.IsSpeculativeSemanticModel)
{
// The region analysis APIs used below are not meaningful/applicable in the context of speculation (because they are designed
// to ask questions about an expression if it were in a certain *scope* of code, not if it were inserted at a certain *position*).
//
// But in the context of symbol completion, we do prepare a description for the symbol while speculating. Only the "main description"
// section of that description will be displayed. We still add a "captures" section, just in case.
AddToGroup(SymbolDescriptionGroups.Captures, LineBreak());
AddToGroup(SymbolDescriptionGroups.Captures, PlainText($"{WorkspacesResources.Variables_captured_colon} ?"));
return;
}
var analysis = semanticModel.AnalyzeDataFlow(syntax);
var captures = analysis.CapturedInside.Except(analysis.VariablesDeclared).ToImmutableArray();
if (!captures.IsEmpty)
{
var parts = new List<SymbolDisplayPart>();
parts.AddLineBreak();
parts.AddText(WorkspacesResources.Variables_captured_colon);
var first = true;
foreach (var captured in captures)
{
if (!first)
{
parts.AddRange(Punctuation(","));
}
parts.AddRange(Space(count: 1));
parts.AddRange(ToMinimalDisplayParts(captured, s_formatForCaptures));
first = false;
}
AddToGroup(SymbolDescriptionGroups.Captures, parts);
}
}
private static readonly SymbolDisplayFormat s_formatForCaptures = SymbolDisplayFormat.MinimallyQualifiedFormat
.RemoveLocalOptions(SymbolDisplayLocalOptions.IncludeType)
.RemoveParameterOptions(SymbolDisplayParameterOptions.IncludeType);
public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync(
ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return BuildDescription(groups);
}
public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return BuildDescriptionSections();
}
private async Task AddDescriptionPartAsync(ISymbol symbol)
{
if (symbol.IsObsolete())
{
AddDeprecatedPrefix();
}
if (symbol is IDiscardSymbol discard)
{
AddDescriptionForDiscard(discard);
}
else if (symbol is IDynamicTypeSymbol)
{
AddDescriptionForDynamicType();
}
else if (symbol is IFieldSymbol field)
{
await AddDescriptionForFieldAsync(field).ConfigureAwait(false);
}
else if (symbol is ILocalSymbol local)
{
await AddDescriptionForLocalAsync(local).ConfigureAwait(false);
}
else if (symbol is IMethodSymbol method)
{
AddDescriptionForMethod(method);
}
else if (symbol is ILabelSymbol label)
{
AddDescriptionForLabel(label);
}
else if (symbol is INamedTypeSymbol namedType)
{
if (namedType.IsTupleType)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.ToDisplayParts(s_descriptionStyle));
}
else
{
AddDescriptionForNamedType(namedType);
}
}
else if (symbol is INamespaceSymbol namespaceSymbol)
{
AddDescriptionForNamespace(namespaceSymbol);
}
else if (symbol is IParameterSymbol parameter)
{
await AddDescriptionForParameterAsync(parameter).ConfigureAwait(false);
}
else if (symbol is IPropertySymbol property)
{
AddDescriptionForProperty(property);
}
else if (symbol is IRangeVariableSymbol rangeVariable)
{
AddDescriptionForRangeVariable(rangeVariable);
}
else if (symbol is ITypeParameterSymbol typeParameter)
{
AddDescriptionForTypeParameter(typeParameter);
}
else if (symbol is IAliasSymbol alias)
{
await AddDescriptionPartAsync(alias.Target).ConfigureAwait(false);
}
else
{
AddDescriptionForArbitrarySymbol(symbol);
}
}
private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups)
{
var finalParts = new List<SymbolDisplayPart>();
var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2);
foreach (var group in orderedGroups)
{
if ((groups & group) == 0)
{
continue;
}
if (!finalParts.IsEmpty())
{
var newLines = GetPrecedingNewLineCount(group);
finalParts.AddRange(LineBreak(newLines));
}
var parts = _groupMap[group];
finalParts.AddRange(parts);
}
return finalParts.AsImmutable();
}
private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group)
{
switch (group)
{
case SymbolDescriptionGroups.MainDescription:
// these parts are continuations of whatever text came before them
return 0;
case SymbolDescriptionGroups.Documentation:
case SymbolDescriptionGroups.RemarksDocumentation:
case SymbolDescriptionGroups.ReturnsDocumentation:
case SymbolDescriptionGroups.ValueDocumentation:
return 1;
case SymbolDescriptionGroups.AnonymousTypes:
return 0;
case SymbolDescriptionGroups.Exceptions:
case SymbolDescriptionGroups.TypeParameterMap:
case SymbolDescriptionGroups.Captures:
// Everything else is in a group on its own
return 2;
default:
throw ExceptionUtilities.UnexpectedValue(group);
}
}
private IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>> BuildDescriptionSections()
{
var includeNavigationHints = this.Workspace.Options.GetOption(QuickInfoOptions.IncludeNavigationHintsInQuickInfo);
// Merge the two maps into one final result.
var result = new Dictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>(_documentationMap);
foreach (var (group, parts) in _groupMap)
{
var taggedText = parts.ToTaggedText(_getNavigationHint, includeNavigationHints);
if (group == SymbolDescriptionGroups.MainDescription)
{
// Mark the main description as a code block.
taggedText = taggedText
.Insert(0, new TaggedText(TextTags.CodeBlockStart, string.Empty))
.Add(new TaggedText(TextTags.CodeBlockEnd, string.Empty));
}
result[group] = taggedText;
}
return result;
}
private void AddDescriptionForDynamicType()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Keyword("dynamic"));
AddToGroup(SymbolDescriptionGroups.Documentation,
PlainText(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime));
}
private void AddDescriptionForNamedType(INamedTypeSymbol symbol)
{
if (symbol.IsAwaitableNonDynamic(_semanticModel, _position))
{
AddAwaitablePrefix();
}
AddSymbolDescription(symbol);
if (!symbol.IsUnboundGenericType &&
!TypeArgumentsAndParametersAreSame(symbol) &&
!symbol.IsAnonymousDelegateType())
{
var allTypeParameters = symbol.GetAllTypeParameters().ToList();
var allTypeArguments = symbol.GetAllTypeArguments().ToList();
AddTypeParameterMapPart(allTypeParameters, allTypeArguments);
}
if (symbol.IsEnumType() && symbol.EnumUnderlyingType.SpecialType != SpecialType.System_Int32)
{
AddEnumUnderlyingTypeSeparator();
var underlyingTypeDisplayParts = symbol.EnumUnderlyingType.ToDisplayParts(s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes));
AddToGroup(SymbolDescriptionGroups.MainDescription, underlyingTypeDisplayParts);
}
}
private void AddSymbolDescription(INamedTypeSymbol symbol)
{
if (symbol.TypeKind == TypeKind.Delegate)
{
var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
// Under the covers anonymous delegates are represented with generic types. However, we don't want
// to see the unbound form of that generic. We want to see the fully instantiated signature.
AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.IsAnonymousDelegateType()
? symbol.ToDisplayParts(style)
: symbol.OriginalDefinition.ToDisplayParts(style));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.OriginalDefinition.ToDisplayParts(s_descriptionStyle));
}
}
private static bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol)
{
var typeArguments = symbol.GetAllTypeArguments().ToList();
var typeParameters = symbol.GetAllTypeParameters().ToList();
for (var i = 0; i < typeArguments.Count; i++)
{
var typeArgument = typeArguments[i];
var typeParameter = typeParameters[i];
if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name)
{
continue;
}
return false;
}
return true;
}
private void AddDescriptionForNamespace(INamespaceSymbol symbol)
{
if (symbol.IsGlobalNamespace)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.ToDisplayParts(s_globalNamespaceStyle));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.ToDisplayParts(s_descriptionStyle));
}
}
private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol)
{
var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false);
// Don't bother showing disambiguating text for enum members. The icon displayed
// on Quick Info should be enough.
if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum)
{
AddToGroup(SymbolDescriptionGroups.MainDescription, parts);
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.constant)
: Description(FeaturesResources.field),
parts);
}
}
private async Task<ImmutableArray<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (!initializerParts.IsDefaultOrEmpty)
{
using var _ = ArrayBuilder<SymbolDisplayPart>.GetInstance(out var parts);
parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat));
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts.ToImmutable();
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstantsAndModifiers);
}
private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol)
{
var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false);
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.local_constant)
: Description(FeaturesResources.local_variable),
parts);
}
private async Task<ImmutableArray<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
using var _ = ArrayBuilder<SymbolDisplayPart>.GetInstance(out var parts);
parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat));
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts.ToImmutable();
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private void AddDescriptionForLabel(ILabelSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.label),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.range_variable),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForMethod(IMethodSymbol method)
{
// TODO : show duplicated member case
var awaitable = method.IsAwaitableNonDynamic(_semanticModel, _position);
var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension;
if (awaitable && extension)
{
AddAwaitableExtensionPrefix();
}
else if (awaitable)
{
AddAwaitablePrefix();
}
else if (extension)
{
AddExtensionPrefix();
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat));
}
private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol)
{
if (symbol.IsOptional)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (!initializerParts.IsDefaultOrEmpty)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.parameter), parts);
return;
}
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(symbol.IsDiscard ? FeaturesResources.discard : FeaturesResources.parameter),
ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants));
}
private void AddDescriptionForDiscard(IDiscardSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.discard),
ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants));
}
protected void AddDescriptionForProperty(IPropertySymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat));
}
private void AddDescriptionForArbitrarySymbol(ISymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol)
{
Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol),
Space(),
PlainText(FeaturesResources.in_),
Space(),
ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat));
}
private void AddOverloadCountPart(
ImmutableArray<ISymbol> symbolGroup)
{
var count = GetOverloadCount(symbolGroup);
if (count >= 1)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Space(),
Punctuation("("),
Punctuation("+"),
Space(),
PlainText(count.ToString()),
Space(),
count == 1 ? PlainText(FeaturesResources.overload) : PlainText(FeaturesResources.overloads_),
Punctuation(")"));
}
}
private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup)
{
return symbolGroup.Select(s => s.OriginalDefinition)
.Where(s => !s.Equals(symbolGroup.First().OriginalDefinition))
.Where(s => s is IMethodSymbol || s.IsIndexer())
.Count();
}
protected void AddTypeParameterMapPart(
List<ITypeParameterSymbol> typeParameters,
List<ITypeSymbol> typeArguments)
{
var parts = new List<SymbolDisplayPart>();
var count = typeParameters.Count;
for (var i = 0; i < count; i++)
{
parts.AddRange(TypeParameterName(typeParameters[i].Name));
parts.AddRange(Space());
parts.AddRange(PlainText(FeaturesResources.is_));
parts.AddRange(Space());
parts.AddRange(ToMinimalDisplayParts(typeArguments[i]));
if (i < count - 1)
{
parts.AddRange(LineBreak());
}
}
AddToGroup(SymbolDescriptionGroups.TypeParameterMap,
parts);
}
protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray)
=> AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray);
protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray)
{
var partsList = partsArray.Flatten().ToList();
if (partsList.Count > 0)
{
if (!_groupMap.TryGetValue(group, out var existingParts))
{
existingParts = new List<SymbolDisplayPart>();
_groupMap.Add(group, existingParts);
}
existingParts.AddRange(partsList);
}
}
private static IEnumerable<SymbolDisplayPart> Description(string description)
{
return Punctuation("(")
.Concat(PlainText(description))
.Concat(Punctuation(")"))
.Concat(Space());
}
protected static IEnumerable<SymbolDisplayPart> Keyword(string text)
=> Part(SymbolDisplayPartKind.Keyword, text);
protected static IEnumerable<SymbolDisplayPart> LineBreak(int count = 1)
{
for (var i = 0; i < count; i++)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n");
}
}
protected static IEnumerable<SymbolDisplayPart> PlainText(string text)
=> Part(SymbolDisplayPartKind.Text, text);
protected static IEnumerable<SymbolDisplayPart> Punctuation(string text)
=> Part(SymbolDisplayPartKind.Punctuation, text);
protected static IEnumerable<SymbolDisplayPart> Space(int count = 1)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count));
}
protected ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
format ??= MinimallyQualifiedFormat;
return ToMinimalDisplayParts(symbol, _semanticModel, _position, format);
}
private static IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text)
{
yield return new SymbolDisplayPart(kind, symbol, text);
}
private static IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text)
=> Part(kind, null, text);
private static IEnumerable<SymbolDisplayPart> TypeParameterName(string text)
=> Part(SymbolDisplayPartKind.TypeParameterName, text);
}
}
}
| 1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ISymbolExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class ISymbolExtensions
{
public static string ToNameDisplayString(this ISymbol symbol)
=> symbol.ToDisplayString(SymbolDisplayFormats.NameFormat);
public static string ToSignatureDisplayString(this ISymbol symbol)
=> symbol.ToDisplayString(SymbolDisplayFormats.SignatureFormat);
public static bool HasPublicResultantVisibility(this ISymbol symbol)
=> symbol.GetResultantVisibility() == SymbolVisibility.Public;
public static SymbolVisibility GetResultantVisibility(this ISymbol symbol)
{
// Start by assuming it's visible.
var visibility = SymbolVisibility.Public;
switch (symbol.Kind)
{
case SymbolKind.Alias:
// Aliases are uber private. They're only visible in the same file that they
// were declared in.
return SymbolVisibility.Private;
case SymbolKind.Parameter:
// Parameters are only as visible as their containing symbol
return GetResultantVisibility(symbol.ContainingSymbol);
case SymbolKind.TypeParameter:
// Type Parameters are private.
return SymbolVisibility.Private;
}
while (symbol != null && symbol.Kind != SymbolKind.Namespace)
{
switch (symbol.DeclaredAccessibility)
{
// If we see anything private, then the symbol is private.
case Accessibility.NotApplicable:
case Accessibility.Private:
return SymbolVisibility.Private;
// If we see anything internal, then knock it down from public to
// internal.
case Accessibility.Internal:
case Accessibility.ProtectedAndInternal:
visibility = SymbolVisibility.Internal;
break;
// For anything else (Public, Protected, ProtectedOrInternal), the
// symbol stays at the level we've gotten so far.
}
symbol = symbol.ContainingSymbol;
}
return visibility;
}
public static ISymbol? GetOverriddenMember(this ISymbol? symbol)
=> symbol switch
{
IMethodSymbol method => method.OverriddenMethod,
IPropertySymbol property => property.OverriddenProperty,
IEventSymbol @event => @event.OverriddenEvent,
_ => null,
};
public static ImmutableArray<ISymbol> ExplicitInterfaceImplementations(this ISymbol symbol)
=> symbol switch
{
IEventSymbol @event => ImmutableArray<ISymbol>.CastUp(@event.ExplicitInterfaceImplementations),
IMethodSymbol method => ImmutableArray<ISymbol>.CastUp(method.ExplicitInterfaceImplementations),
IPropertySymbol property => ImmutableArray<ISymbol>.CastUp(property.ExplicitInterfaceImplementations),
_ => ImmutableArray.Create<ISymbol>(),
};
public static ImmutableArray<ISymbol> ExplicitOrImplicitInterfaceImplementations(this ISymbol symbol)
{
if (symbol.Kind != SymbolKind.Method && symbol.Kind != SymbolKind.Property && symbol.Kind != SymbolKind.Event)
return ImmutableArray<ISymbol>.Empty;
var containingType = symbol.ContainingType;
var query = from iface in containingType.AllInterfaces
from interfaceMember in iface.GetMembers()
let impl = containingType.FindImplementationForInterfaceMember(interfaceMember)
where symbol.Equals(impl)
select interfaceMember;
return query.ToImmutableArray();
}
public static ImmutableArray<ISymbol> ImplicitInterfaceImplementations(this ISymbol symbol)
=> symbol.ExplicitOrImplicitInterfaceImplementations().Except(symbol.ExplicitInterfaceImplementations()).ToImmutableArray();
public static bool IsOverridable([NotNullWhen(returnValue: true)] this ISymbol? symbol)
{
// Members can only have overrides if they are virtual, abstract or override and is not
// sealed.
return symbol?.ContainingType?.TypeKind == TypeKind.Class &&
(symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride) &&
!symbol.IsSealed;
}
public static bool IsImplementableMember([NotNullWhen(returnValue: true)] this ISymbol? symbol)
{
if (symbol != null &&
symbol.ContainingType != null &&
symbol.ContainingType.TypeKind == TypeKind.Interface)
{
if (symbol.Kind == SymbolKind.Event)
{
return true;
}
if (symbol.Kind == SymbolKind.Property)
{
return true;
}
if (symbol.Kind == SymbolKind.Method)
{
var methodSymbol = (IMethodSymbol)symbol;
if (methodSymbol.MethodKind == MethodKind.Ordinary ||
methodSymbol.MethodKind == MethodKind.PropertyGet ||
methodSymbol.MethodKind == MethodKind.PropertySet ||
methodSymbol.MethodKind == MethodKind.UserDefinedOperator ||
methodSymbol.MethodKind == MethodKind.Conversion)
{
return true;
}
}
}
return false;
}
public static INamedTypeSymbol? GetContainingTypeOrThis(this ISymbol symbol)
{
if (symbol is INamedTypeSymbol namedType)
{
return namedType;
}
return symbol.ContainingType;
}
public static bool IsPointerType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is IPointerTypeSymbol;
public static bool IsErrorType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as ITypeSymbol)?.TypeKind == TypeKind.Error;
public static bool IsModuleType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as ITypeSymbol)?.IsModuleType() == true;
public static bool IsInterfaceType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as ITypeSymbol)?.IsInterfaceType() == true;
public static bool IsArrayType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol?.Kind == SymbolKind.ArrayType;
public static bool IsTupleType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as ITypeSymbol)?.IsTupleType ?? false;
public static bool IsAnonymousFunction([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction;
public static bool IsKind([NotNullWhen(returnValue: true)] this ISymbol? symbol, SymbolKind kind)
=> symbol.MatchesKind(kind);
public static bool MatchesKind([NotNullWhen(returnValue: true)] this ISymbol? symbol, SymbolKind kind)
=> symbol?.Kind == kind;
public static bool MatchesKind([NotNullWhen(returnValue: true)] this ISymbol? symbol, SymbolKind kind1, SymbolKind kind2)
{
return symbol != null
&& (symbol.Kind == kind1 || symbol.Kind == kind2);
}
public static bool MatchesKind([NotNullWhen(returnValue: true)] this ISymbol? symbol, SymbolKind kind1, SymbolKind kind2, SymbolKind kind3)
{
return symbol != null
&& (symbol.Kind == kind1 || symbol.Kind == kind2 || symbol.Kind == kind3);
}
public static bool MatchesKind([NotNullWhen(returnValue: true)] this ISymbol? symbol, params SymbolKind[] kinds)
{
return symbol != null
&& kinds.Contains(symbol.Kind);
}
public static bool IsReducedExtension([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is IMethodSymbol method && method.MethodKind == MethodKind.ReducedExtension;
public static bool IsEnumMember([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol?.Kind == SymbolKind.Field && symbol.ContainingType.IsEnumType();
public static bool IsExtensionMethod(this ISymbol symbol)
=> symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsExtensionMethod;
public static bool IsLocalFunction([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol != null && symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.LocalFunction;
public static bool IsAnonymousOrLocalFunction([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol.IsAnonymousFunction() || symbol.IsLocalFunction();
public static bool IsModuleMember([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol != null && symbol.ContainingSymbol is INamedTypeSymbol && symbol.ContainingType.TypeKind == TypeKind.Module;
public static bool IsConstructor([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.Constructor;
public static bool IsStaticConstructor([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.StaticConstructor;
public static bool IsDestructor([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.Destructor;
public static bool IsUserDefinedOperator([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.UserDefinedOperator;
public static bool IsConversion([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.Conversion;
public static bool IsOrdinaryMethod([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.Ordinary;
public static bool IsOrdinaryMethodOrLocalFunction([NotNullWhen(returnValue: true)] this ISymbol? symbol)
{
if (symbol is not IMethodSymbol method)
{
return false;
}
return method.MethodKind == MethodKind.Ordinary
|| method.MethodKind == MethodKind.LocalFunction;
}
public static bool IsDelegateType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is ITypeSymbol && ((ITypeSymbol)symbol).TypeKind == TypeKind.Delegate;
public static bool IsAnonymousType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is INamedTypeSymbol && ((INamedTypeSymbol)symbol).IsAnonymousType;
public static bool IsNormalAnonymousType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol.IsAnonymousType() && !symbol.IsDelegateType();
public static bool IsAnonymousDelegateType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol.IsAnonymousType() && symbol.IsDelegateType();
public static bool IsAnonymousTypeProperty([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is IPropertySymbol && symbol.ContainingType.IsNormalAnonymousType();
public static bool IsTupleField([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is IFieldSymbol && symbol.ContainingType.IsTupleType;
public static bool IsIndexer([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IPropertySymbol)?.IsIndexer == true;
public static bool IsWriteableFieldOrProperty([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol switch
{
IFieldSymbol fieldSymbol => !fieldSymbol.IsReadOnly && !fieldSymbol.IsConst,
IPropertySymbol propertySymbol => !propertySymbol.IsReadOnly,
_ => false,
};
public static ITypeSymbol? GetMemberType(this ISymbol symbol)
=> symbol switch
{
IFieldSymbol fieldSymbol => fieldSymbol.Type,
IPropertySymbol propertySymbol => propertySymbol.Type,
IMethodSymbol methodSymbol => methodSymbol.ReturnType,
IEventSymbol eventSymbol => eventSymbol.Type,
_ => null,
};
public static int GetArity(this ISymbol symbol)
=> symbol.Kind switch
{
SymbolKind.NamedType => ((INamedTypeSymbol)symbol).Arity,
SymbolKind.Method => ((IMethodSymbol)symbol).Arity,
_ => 0,
};
[return: NotNullIfNotNull(parameterName: "symbol")]
public static ISymbol? GetOriginalUnreducedDefinition(this ISymbol? symbol)
{
if (symbol.IsTupleField())
{
return symbol;
}
if (symbol.IsReducedExtension())
{
// note: ReducedFrom is only a method definition and includes no type arguments.
symbol = ((IMethodSymbol)symbol).GetConstructedReducedFrom();
}
if (symbol.IsFunctionValue())
{
if (symbol.ContainingSymbol is IMethodSymbol method)
{
symbol = method;
if (method.AssociatedSymbol != null)
{
symbol = method.AssociatedSymbol;
}
}
}
if (symbol.IsNormalAnonymousType() || symbol.IsAnonymousTypeProperty())
{
return symbol;
}
if (symbol is IParameterSymbol parameter)
{
var method = parameter.ContainingSymbol as IMethodSymbol;
if (method?.IsReducedExtension() == true)
{
symbol = method.GetConstructedReducedFrom()!.Parameters[parameter.Ordinal + 1];
}
}
return symbol?.OriginalDefinition;
}
public static bool IsFunctionValue([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is ILocalSymbol && ((ILocalSymbol)symbol).IsFunctionValue;
public static bool IsThisParameter([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol?.Kind == SymbolKind.Parameter && ((IParameterSymbol)symbol).IsThis;
[return: NotNullIfNotNull(parameterName: "symbol")]
public static ISymbol? ConvertThisParameterToType(this ISymbol? symbol)
{
if (symbol.IsThisParameter())
{
return ((IParameterSymbol)symbol).Type;
}
return symbol;
}
public static bool IsParams([NotNullWhen(returnValue: true)] this ISymbol? symbol)
{
var parameters = symbol.GetParameters();
return parameters.Length > 0 && parameters[^1].IsParams;
}
public static ImmutableArray<IParameterSymbol> GetParameters(this ISymbol? symbol)
=> symbol switch
{
IMethodSymbol m => m.Parameters,
IPropertySymbol nt => nt.Parameters,
_ => ImmutableArray<IParameterSymbol>.Empty,
};
public static ImmutableArray<ITypeParameterSymbol> GetTypeParameters(this ISymbol? symbol)
=> symbol switch
{
IMethodSymbol m => m.TypeParameters,
INamedTypeSymbol nt => nt.TypeParameters,
_ => ImmutableArray<ITypeParameterSymbol>.Empty,
};
public static ImmutableArray<ITypeParameterSymbol> GetAllTypeParameters(this ISymbol? symbol)
{
var results = ArrayBuilder<ITypeParameterSymbol>.GetInstance();
while (symbol != null)
{
results.AddRange(symbol.GetTypeParameters());
symbol = symbol.ContainingType;
}
return results.ToImmutableAndFree();
}
public static ImmutableArray<ITypeSymbol> GetTypeArguments(this ISymbol? symbol)
=> symbol switch
{
IMethodSymbol m => m.TypeArguments,
INamedTypeSymbol nt => nt.TypeArguments,
_ => ImmutableArray.Create<ITypeSymbol>(),
};
public static ImmutableArray<ITypeSymbol> GetAllTypeArguments(this ISymbol symbol)
{
var results = ArrayBuilder<ITypeSymbol>.GetInstance();
results.AddRange(symbol.GetTypeArguments());
var containingType = symbol.ContainingType;
while (containingType != null)
{
results.AddRange(containingType.GetTypeArguments());
containingType = containingType.ContainingType;
}
return results.ToImmutableAndFree();
}
public static bool IsAttribute([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as ITypeSymbol)?.IsAttribute() == true;
/// <summary>
/// Returns <see langword="true"/> if the signature of this symbol requires the <see
/// langword="unsafe"/> modifier. For example a method that takes <c>List<int*[]></c>
/// is unsafe, as is <c>int* Goo { get; }</c>. This will return <see langword="false"/> for
/// symbols that cannot have the <see langword="unsafe"/> modifier on them.
/// </summary>
public static bool RequiresUnsafeModifier([NotNullWhen(returnValue: true)] this ISymbol? member)
{
// TODO(cyrusn): Defer to compiler code to handle this once it can.
return member?.Accept(new RequiresUnsafeModifierVisitor()) == true;
}
public static ITypeSymbol ConvertToType(
this ISymbol? symbol,
Compilation compilation,
bool extensionUsedAsInstance = false)
{
if (symbol is ITypeSymbol type)
{
return type;
}
if (symbol is IMethodSymbol method && method.Parameters.All(p => p.RefKind == RefKind.None))
{
var count = extensionUsedAsInstance ? Math.Max(0, method.Parameters.Length - 1) : method.Parameters.Length;
var skip = extensionUsedAsInstance ? 1 : 0;
// Convert the symbol to Func<...> or Action<...>
var delegateType = compilation.GetTypeByMetadataName(method.ReturnsVoid
? WithArity("System.Action", count)
: WithArity("System.Func", count + 1));
if (delegateType != null)
{
var types = method.Parameters
.Skip(skip)
.Select(p => (p.Type ?? compilation.GetSpecialType(SpecialType.System_Object)).WithNullableAnnotation(p.NullableAnnotation));
if (!method.ReturnsVoid)
{
// +1 for the return type.
types = types.Concat((method.ReturnType ?? compilation.GetSpecialType(SpecialType.System_Object)).WithNullableAnnotation(method.ReturnNullableAnnotation));
}
return delegateType.TryConstruct(types.ToArray());
}
}
// Otherwise, just default to object.
return compilation.ObjectType;
// local functions
static string WithArity(string typeName, int arity)
=> arity > 0 ? typeName + '`' + arity : typeName;
}
public static bool IsStaticType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol != null && symbol.Kind == SymbolKind.NamedType && symbol.IsStatic;
public static bool IsNamespace([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol?.Kind == SymbolKind.Namespace;
public static bool IsOrContainsAccessibleAttribute(
[NotNullWhen(returnValue: true)] this ISymbol? symbol, ISymbol withinType, IAssemblySymbol withinAssembly, CancellationToken cancellationToken)
{
var namespaceOrType = symbol is IAliasSymbol alias ? alias.Target : symbol as INamespaceOrTypeSymbol;
if (namespaceOrType == null)
{
return false;
}
// PERF: Avoid allocating a lambda capture
foreach (var type in namespaceOrType.GetAllTypes(cancellationToken))
{
if (type.IsAttribute() && type.IsAccessibleWithin(withinType ?? withinAssembly))
{
return true;
}
}
return false;
}
public static IEnumerable<IPropertySymbol> GetValidAnonymousTypeProperties(this ISymbol symbol)
{
Contract.ThrowIfFalse(symbol.IsNormalAnonymousType());
return ((INamedTypeSymbol)symbol).GetMembers().OfType<IPropertySymbol>().Where(p => p.CanBeReferencedByName);
}
public static Accessibility ComputeResultantAccessibility(this ISymbol? symbol, ITypeSymbol finalDestination)
{
if (symbol == null)
{
return Accessibility.Private;
}
switch (symbol.DeclaredAccessibility)
{
default:
return symbol.DeclaredAccessibility;
case Accessibility.ProtectedAndInternal:
return symbol.ContainingAssembly.GivesAccessTo(finalDestination.ContainingAssembly)
? Accessibility.ProtectedAndInternal
: Accessibility.Internal;
case Accessibility.ProtectedOrInternal:
return symbol.ContainingAssembly.GivesAccessTo(finalDestination.ContainingAssembly)
? Accessibility.ProtectedOrInternal
: Accessibility.Protected;
}
}
/// <returns>
/// Returns true if symbol is a local variable and its declaring syntax node is
/// after the current position, false otherwise (including for non-local symbols)
/// </returns>
public static bool IsInaccessibleLocal(this ISymbol symbol, int position)
{
if (symbol.Kind != SymbolKind.Local)
{
return false;
}
// Implicitly declared locals (with Option Explicit Off in VB) are scoped to the entire
// method and should always be considered accessible from within the same method.
if (symbol.IsImplicitlyDeclared)
{
return false;
}
var declarationSyntax = symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).FirstOrDefault();
return declarationSyntax != null && position < declarationSyntax.SpanStart;
}
public static bool IsAccessor([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol.IsPropertyAccessor() || symbol.IsEventAccessor();
public static bool IsPropertyAccessor([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind.IsPropertyAccessor() == true;
public static bool IsEventAccessor([NotNullWhen(returnValue: true)] this ISymbol? symbol)
{
var method = symbol as IMethodSymbol;
return method != null &&
(method.MethodKind == MethodKind.EventAdd ||
method.MethodKind == MethodKind.EventRaise ||
method.MethodKind == MethodKind.EventRemove);
}
public static bool IsFromSource(this ISymbol symbol)
=> symbol.Locations.Any() && symbol.Locations.All(location => location.IsInSource);
public static bool IsNonImplicitAndFromSource(this ISymbol symbol)
=> !symbol.IsImplicitlyDeclared && symbol.IsFromSource();
public static ITypeSymbol? GetSymbolType(this ISymbol? symbol)
=> symbol switch
{
ILocalSymbol localSymbol => localSymbol.Type,
IFieldSymbol fieldSymbol => fieldSymbol.Type,
IPropertySymbol propertySymbol => propertySymbol.Type,
IParameterSymbol parameterSymbol => parameterSymbol.Type,
IAliasSymbol aliasSymbol => aliasSymbol.Target as ITypeSymbol,
_ => symbol as ITypeSymbol,
};
/// <summary>
/// If the <paramref name="symbol"/> is a method symbol, returns <see langword="true"/> if the method's return type is "awaitable", but not if it's <see langword="dynamic"/>.
/// If the <paramref name="symbol"/> is a type symbol, returns <see langword="true"/> if that type is "awaitable".
/// An "awaitable" is any type that exposes a GetAwaiter method which returns a valid "awaiter". This GetAwaiter method may be an instance method or an extension method.
/// </summary>
public static bool IsAwaitableNonDynamic([NotNullWhen(returnValue: true)] this ISymbol? symbol, SemanticModel semanticModel, int position)
{
var methodSymbol = symbol as IMethodSymbol;
ITypeSymbol? typeSymbol = null;
if (methodSymbol == null)
{
typeSymbol = symbol as ITypeSymbol;
if (typeSymbol == null)
{
return false;
}
}
else
{
if (methodSymbol.ReturnType == null)
{
return false;
}
}
// otherwise: needs valid GetAwaiter
var potentialGetAwaiters = semanticModel.LookupSymbols(position,
container: typeSymbol ?? methodSymbol!.ReturnType.OriginalDefinition,
name: WellKnownMemberNames.GetAwaiter,
includeReducedExtensionMethods: true);
var getAwaiters = potentialGetAwaiters.OfType<IMethodSymbol>().Where(x => !x.Parameters.Any());
return getAwaiters.Any(VerifyGetAwaiter);
}
public static bool IsValidGetAwaiter(this IMethodSymbol symbol)
=> symbol.Name == WellKnownMemberNames.GetAwaiter &&
VerifyGetAwaiter(symbol);
private static bool VerifyGetAwaiter(IMethodSymbol getAwaiter)
{
var returnType = getAwaiter.ReturnType;
if (returnType == null)
{
return false;
}
// bool IsCompleted { get }
if (!returnType.GetMembers().OfType<IPropertySymbol>().Any(p => p.Name == WellKnownMemberNames.IsCompleted && p.Type.SpecialType == SpecialType.System_Boolean && p.GetMethod != null))
{
return false;
}
var methods = returnType.GetMembers().OfType<IMethodSymbol>();
// NOTE: (vladres) The current version of C# Spec, §7.7.7.3 'Runtime evaluation of await expressions', requires that
// NOTE: the interface method INotifyCompletion.OnCompleted or ICriticalNotifyCompletion.UnsafeOnCompleted is invoked
// NOTE: (rather than any OnCompleted method conforming to a certain pattern).
// NOTE: Should this code be updated to match the spec?
// void OnCompleted(Action)
// Actions are delegates, so we'll just check for delegates.
if (!methods.Any(x => x.Name == WellKnownMemberNames.OnCompleted && x.ReturnsVoid && x.Parameters.Length == 1 && x.Parameters.First().Type.TypeKind == TypeKind.Delegate))
{
return false;
}
// void GetResult() || T GetResult()
return methods.Any(m => m.Name == WellKnownMemberNames.GetResult && !m.Parameters.Any());
}
public static bool IsValidGetEnumerator(this IMethodSymbol symbol)
=> symbol.Name == WellKnownMemberNames.GetEnumeratorMethodName &&
VerifyGetEnumerator(symbol);
private static bool VerifyGetEnumerator(IMethodSymbol getEnumerator)
{
var returnType = getEnumerator.ReturnType;
if (returnType == null)
{
return false;
}
var members = returnType.AllInterfaces.Concat(returnType.GetBaseTypesAndThis())
.SelectMany(x => x.GetMembers())
.Where(x => x.DeclaredAccessibility == Accessibility.Public)
.ToList();
// T Current { get }
if (!members.OfType<IPropertySymbol>().Any(p => p.Name == WellKnownMemberNames.CurrentPropertyName && p.GetMethod != null))
{
return false;
}
// bool MoveNext()
if (!members.OfType<IMethodSymbol>().Any(x =>
{
return x is
{
Name: WellKnownMemberNames.MoveNextMethodName,
ReturnType: { SpecialType: SpecialType.System_Boolean },
Parameters: { Length: 0 },
};
}))
{
return false;
}
return true;
}
public static bool IsValidGetAsyncEnumerator(this IMethodSymbol symbol)
=> symbol.Name == WellKnownMemberNames.GetAsyncEnumeratorMethodName &&
VerifyGetAsyncEnumerator(symbol);
private static bool VerifyGetAsyncEnumerator(IMethodSymbol getAsyncEnumerator)
{
var returnType = getAsyncEnumerator.ReturnType;
if (returnType == null)
{
return false;
}
var members = returnType.AllInterfaces.Concat(returnType.GetBaseTypesAndThis())
.SelectMany(x => x.GetMembers())
.Where(x => x.DeclaredAccessibility == Accessibility.Public)
.ToList();
// T Current { get }
if (!members.OfType<IPropertySymbol>().Any(p => p.Name == WellKnownMemberNames.CurrentPropertyName && p.GetMethod != null))
{
return false;
}
// Task<bool> MoveNext()
// We don't check for the return type, since it can be any awaitable wrapping a boolean,
// which is too complex to be worth checking here.
// We don't check number of parameters since MoveNextAsync allows optional parameters/params
if (!members.OfType<IMethodSymbol>().Any(x => x.Name == WellKnownMemberNames.MoveNextAsyncMethodName))
{
return false;
}
return true;
}
public static bool IsKind<TSymbol>(this ISymbol symbol, SymbolKind kind, [NotNullWhen(true)] out TSymbol? result) where TSymbol : class, ISymbol
{
if (!symbol.IsKind(kind))
{
result = null;
return false;
}
result = (TSymbol)symbol;
return true;
}
/// <summary>
/// Returns true for symbols whose name starts with an underscore and
/// are optionally followed by an integer, such as '_', '_1', '_2', etc.
/// These are treated as special discard symbol names.
/// </summary>
public static bool IsSymbolWithSpecialDiscardName(this ISymbol symbol)
=> symbol.Name.StartsWith("_") &&
(symbol.Name.Length == 1 || uint.TryParse(symbol.Name.Substring(1), out _));
/// <summary>
/// Returns <see langword="true"/>, if the symbol is marked with the <see cref="System.ObsoleteAttribute"/>.
/// </summary>
/// <param name="symbol"></param>
/// <returns><see langword="true"/> if the symbol is marked with the <see cref="System.ObsoleteAttribute"/>.</returns>
public static bool IsObsolete(this ISymbol symbol)
=> symbol.GetAttributes().Any(x => x.AttributeClass is
{
MetadataName: nameof(ObsoleteAttribute),
ContainingNamespace: { Name: nameof(System) },
});
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class ISymbolExtensions
{
public static string ToNameDisplayString(this ISymbol symbol)
=> symbol.ToDisplayString(SymbolDisplayFormats.NameFormat);
public static string ToSignatureDisplayString(this ISymbol symbol)
=> symbol.ToDisplayString(SymbolDisplayFormats.SignatureFormat);
public static bool HasPublicResultantVisibility(this ISymbol symbol)
=> symbol.GetResultantVisibility() == SymbolVisibility.Public;
public static SymbolVisibility GetResultantVisibility(this ISymbol symbol)
{
// Start by assuming it's visible.
var visibility = SymbolVisibility.Public;
switch (symbol.Kind)
{
case SymbolKind.Alias:
// Aliases are uber private. They're only visible in the same file that they
// were declared in.
return SymbolVisibility.Private;
case SymbolKind.Parameter:
// Parameters are only as visible as their containing symbol
return GetResultantVisibility(symbol.ContainingSymbol);
case SymbolKind.TypeParameter:
// Type Parameters are private.
return SymbolVisibility.Private;
}
while (symbol != null && symbol.Kind != SymbolKind.Namespace)
{
switch (symbol.DeclaredAccessibility)
{
// If we see anything private, then the symbol is private.
case Accessibility.NotApplicable:
case Accessibility.Private:
return SymbolVisibility.Private;
// If we see anything internal, then knock it down from public to
// internal.
case Accessibility.Internal:
case Accessibility.ProtectedAndInternal:
visibility = SymbolVisibility.Internal;
break;
// For anything else (Public, Protected, ProtectedOrInternal), the
// symbol stays at the level we've gotten so far.
}
symbol = symbol.ContainingSymbol;
}
return visibility;
}
public static ISymbol? GetOverriddenMember(this ISymbol? symbol)
=> symbol switch
{
IMethodSymbol method => method.OverriddenMethod,
IPropertySymbol property => property.OverriddenProperty,
IEventSymbol @event => @event.OverriddenEvent,
_ => null,
};
public static ImmutableArray<ISymbol> ExplicitInterfaceImplementations(this ISymbol symbol)
=> symbol switch
{
IEventSymbol @event => ImmutableArray<ISymbol>.CastUp(@event.ExplicitInterfaceImplementations),
IMethodSymbol method => ImmutableArray<ISymbol>.CastUp(method.ExplicitInterfaceImplementations),
IPropertySymbol property => ImmutableArray<ISymbol>.CastUp(property.ExplicitInterfaceImplementations),
_ => ImmutableArray.Create<ISymbol>(),
};
public static ImmutableArray<ISymbol> ExplicitOrImplicitInterfaceImplementations(this ISymbol symbol)
{
if (symbol.Kind != SymbolKind.Method && symbol.Kind != SymbolKind.Property && symbol.Kind != SymbolKind.Event)
return ImmutableArray<ISymbol>.Empty;
var containingType = symbol.ContainingType;
var query = from iface in containingType.AllInterfaces
from interfaceMember in iface.GetMembers()
let impl = containingType.FindImplementationForInterfaceMember(interfaceMember)
where symbol.Equals(impl)
select interfaceMember;
return query.ToImmutableArray();
}
public static ImmutableArray<ISymbol> ImplicitInterfaceImplementations(this ISymbol symbol)
=> symbol.ExplicitOrImplicitInterfaceImplementations().Except(symbol.ExplicitInterfaceImplementations()).ToImmutableArray();
public static bool IsOverridable([NotNullWhen(returnValue: true)] this ISymbol? symbol)
{
// Members can only have overrides if they are virtual, abstract or override and is not
// sealed.
return symbol?.ContainingType?.TypeKind == TypeKind.Class &&
(symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride) &&
!symbol.IsSealed;
}
public static bool IsImplementableMember([NotNullWhen(returnValue: true)] this ISymbol? symbol)
{
if (symbol != null &&
symbol.ContainingType != null &&
symbol.ContainingType.TypeKind == TypeKind.Interface)
{
if (symbol.Kind == SymbolKind.Event)
{
return true;
}
if (symbol.Kind == SymbolKind.Property)
{
return true;
}
if (symbol.Kind == SymbolKind.Method)
{
var methodSymbol = (IMethodSymbol)symbol;
if (methodSymbol.MethodKind == MethodKind.Ordinary ||
methodSymbol.MethodKind == MethodKind.PropertyGet ||
methodSymbol.MethodKind == MethodKind.PropertySet ||
methodSymbol.MethodKind == MethodKind.UserDefinedOperator ||
methodSymbol.MethodKind == MethodKind.Conversion)
{
return true;
}
}
}
return false;
}
public static INamedTypeSymbol? GetContainingTypeOrThis(this ISymbol symbol)
{
if (symbol is INamedTypeSymbol namedType)
{
return namedType;
}
return symbol.ContainingType;
}
public static bool IsPointerType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is IPointerTypeSymbol;
public static bool IsErrorType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as ITypeSymbol)?.TypeKind == TypeKind.Error;
public static bool IsModuleType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as ITypeSymbol)?.IsModuleType() == true;
public static bool IsInterfaceType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as ITypeSymbol)?.IsInterfaceType() == true;
public static bool IsArrayType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol?.Kind == SymbolKind.ArrayType;
public static bool IsTupleType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as ITypeSymbol)?.IsTupleType ?? false;
public static bool IsAnonymousFunction([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction;
public static bool IsKind([NotNullWhen(returnValue: true)] this ISymbol? symbol, SymbolKind kind)
=> symbol.MatchesKind(kind);
public static bool MatchesKind([NotNullWhen(returnValue: true)] this ISymbol? symbol, SymbolKind kind)
=> symbol?.Kind == kind;
public static bool MatchesKind([NotNullWhen(returnValue: true)] this ISymbol? symbol, SymbolKind kind1, SymbolKind kind2)
{
return symbol != null
&& (symbol.Kind == kind1 || symbol.Kind == kind2);
}
public static bool MatchesKind([NotNullWhen(returnValue: true)] this ISymbol? symbol, SymbolKind kind1, SymbolKind kind2, SymbolKind kind3)
{
return symbol != null
&& (symbol.Kind == kind1 || symbol.Kind == kind2 || symbol.Kind == kind3);
}
public static bool MatchesKind([NotNullWhen(returnValue: true)] this ISymbol? symbol, params SymbolKind[] kinds)
{
return symbol != null
&& kinds.Contains(symbol.Kind);
}
public static bool IsReducedExtension([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is IMethodSymbol method && method.MethodKind == MethodKind.ReducedExtension;
public static bool IsEnumMember([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol?.Kind == SymbolKind.Field && symbol.ContainingType.IsEnumType();
public static bool IsExtensionMethod(this ISymbol symbol)
=> symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsExtensionMethod;
public static bool IsLocalFunction([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol != null && symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.LocalFunction;
public static bool IsAnonymousOrLocalFunction([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol.IsAnonymousFunction() || symbol.IsLocalFunction();
public static bool IsModuleMember([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol != null && symbol.ContainingSymbol is INamedTypeSymbol && symbol.ContainingType.TypeKind == TypeKind.Module;
public static bool IsConstructor([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.Constructor;
public static bool IsStaticConstructor([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.StaticConstructor;
public static bool IsDestructor([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.Destructor;
public static bool IsUserDefinedOperator([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.UserDefinedOperator;
public static bool IsConversion([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.Conversion;
public static bool IsOrdinaryMethod([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.Ordinary;
public static bool IsOrdinaryMethodOrLocalFunction([NotNullWhen(returnValue: true)] this ISymbol? symbol)
{
if (symbol is not IMethodSymbol method)
{
return false;
}
return method.MethodKind == MethodKind.Ordinary
|| method.MethodKind == MethodKind.LocalFunction;
}
public static bool IsDelegateType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is ITypeSymbol && ((ITypeSymbol)symbol).TypeKind == TypeKind.Delegate;
public static bool IsAnonymousType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is INamedTypeSymbol && ((INamedTypeSymbol)symbol).IsAnonymousType;
public static bool IsNormalAnonymousType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol.IsAnonymousType() && !symbol.IsDelegateType();
public static bool IsAnonymousDelegateType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol.IsDelegateType() && (symbol.IsAnonymousType() || !symbol.CanBeReferencedByName);
public static bool IsAnonymousTypeProperty([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is IPropertySymbol && symbol.ContainingType.IsNormalAnonymousType();
public static bool IsTupleField([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is IFieldSymbol && symbol.ContainingType.IsTupleType;
public static bool IsIndexer([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IPropertySymbol)?.IsIndexer == true;
public static bool IsWriteableFieldOrProperty([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol switch
{
IFieldSymbol fieldSymbol => !fieldSymbol.IsReadOnly && !fieldSymbol.IsConst,
IPropertySymbol propertySymbol => !propertySymbol.IsReadOnly,
_ => false,
};
public static ITypeSymbol? GetMemberType(this ISymbol symbol)
=> symbol switch
{
IFieldSymbol fieldSymbol => fieldSymbol.Type,
IPropertySymbol propertySymbol => propertySymbol.Type,
IMethodSymbol methodSymbol => methodSymbol.ReturnType,
IEventSymbol eventSymbol => eventSymbol.Type,
_ => null,
};
public static int GetArity(this ISymbol symbol)
=> symbol.Kind switch
{
SymbolKind.NamedType => ((INamedTypeSymbol)symbol).Arity,
SymbolKind.Method => ((IMethodSymbol)symbol).Arity,
_ => 0,
};
[return: NotNullIfNotNull(parameterName: "symbol")]
public static ISymbol? GetOriginalUnreducedDefinition(this ISymbol? symbol)
{
if (symbol.IsTupleField())
{
return symbol;
}
if (symbol.IsReducedExtension())
{
// note: ReducedFrom is only a method definition and includes no type arguments.
symbol = ((IMethodSymbol)symbol).GetConstructedReducedFrom();
}
if (symbol.IsFunctionValue())
{
if (symbol.ContainingSymbol is IMethodSymbol method)
{
symbol = method;
if (method.AssociatedSymbol != null)
{
symbol = method.AssociatedSymbol;
}
}
}
if (symbol.IsNormalAnonymousType() || symbol.IsAnonymousTypeProperty())
{
return symbol;
}
if (symbol is IParameterSymbol parameter)
{
var method = parameter.ContainingSymbol as IMethodSymbol;
if (method?.IsReducedExtension() == true)
{
symbol = method.GetConstructedReducedFrom()!.Parameters[parameter.Ordinal + 1];
}
}
return symbol?.OriginalDefinition;
}
public static bool IsFunctionValue([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol is ILocalSymbol && ((ILocalSymbol)symbol).IsFunctionValue;
public static bool IsThisParameter([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol?.Kind == SymbolKind.Parameter && ((IParameterSymbol)symbol).IsThis;
[return: NotNullIfNotNull(parameterName: "symbol")]
public static ISymbol? ConvertThisParameterToType(this ISymbol? symbol)
{
if (symbol.IsThisParameter())
{
return ((IParameterSymbol)symbol).Type;
}
return symbol;
}
public static bool IsParams([NotNullWhen(returnValue: true)] this ISymbol? symbol)
{
var parameters = symbol.GetParameters();
return parameters.Length > 0 && parameters[^1].IsParams;
}
public static ImmutableArray<IParameterSymbol> GetParameters(this ISymbol? symbol)
=> symbol switch
{
IMethodSymbol m => m.Parameters,
IPropertySymbol nt => nt.Parameters,
_ => ImmutableArray<IParameterSymbol>.Empty,
};
public static ImmutableArray<ITypeParameterSymbol> GetTypeParameters(this ISymbol? symbol)
=> symbol switch
{
IMethodSymbol m => m.TypeParameters,
INamedTypeSymbol nt => nt.TypeParameters,
_ => ImmutableArray<ITypeParameterSymbol>.Empty,
};
public static ImmutableArray<ITypeParameterSymbol> GetAllTypeParameters(this ISymbol? symbol)
{
var results = ArrayBuilder<ITypeParameterSymbol>.GetInstance();
while (symbol != null)
{
results.AddRange(symbol.GetTypeParameters());
symbol = symbol.ContainingType;
}
return results.ToImmutableAndFree();
}
public static ImmutableArray<ITypeSymbol> GetTypeArguments(this ISymbol? symbol)
=> symbol switch
{
IMethodSymbol m => m.TypeArguments,
INamedTypeSymbol nt => nt.TypeArguments,
_ => ImmutableArray.Create<ITypeSymbol>(),
};
public static ImmutableArray<ITypeSymbol> GetAllTypeArguments(this ISymbol symbol)
{
var results = ArrayBuilder<ITypeSymbol>.GetInstance();
results.AddRange(symbol.GetTypeArguments());
var containingType = symbol.ContainingType;
while (containingType != null)
{
results.AddRange(containingType.GetTypeArguments());
containingType = containingType.ContainingType;
}
return results.ToImmutableAndFree();
}
public static bool IsAttribute([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as ITypeSymbol)?.IsAttribute() == true;
/// <summary>
/// Returns <see langword="true"/> if the signature of this symbol requires the <see
/// langword="unsafe"/> modifier. For example a method that takes <c>List<int*[]></c>
/// is unsafe, as is <c>int* Goo { get; }</c>. This will return <see langword="false"/> for
/// symbols that cannot have the <see langword="unsafe"/> modifier on them.
/// </summary>
public static bool RequiresUnsafeModifier([NotNullWhen(returnValue: true)] this ISymbol? member)
{
// TODO(cyrusn): Defer to compiler code to handle this once it can.
return member?.Accept(new RequiresUnsafeModifierVisitor()) == true;
}
public static ITypeSymbol ConvertToType(
this ISymbol? symbol,
Compilation compilation,
bool extensionUsedAsInstance = false)
{
if (symbol is ITypeSymbol type)
{
return type;
}
if (symbol is IMethodSymbol method && method.Parameters.All(p => p.RefKind == RefKind.None))
{
var count = extensionUsedAsInstance ? Math.Max(0, method.Parameters.Length - 1) : method.Parameters.Length;
var skip = extensionUsedAsInstance ? 1 : 0;
// Convert the symbol to Func<...> or Action<...>
var delegateType = compilation.GetTypeByMetadataName(method.ReturnsVoid
? WithArity("System.Action", count)
: WithArity("System.Func", count + 1));
if (delegateType != null)
{
var types = method.Parameters
.Skip(skip)
.Select(p => (p.Type ?? compilation.GetSpecialType(SpecialType.System_Object)).WithNullableAnnotation(p.NullableAnnotation));
if (!method.ReturnsVoid)
{
// +1 for the return type.
types = types.Concat((method.ReturnType ?? compilation.GetSpecialType(SpecialType.System_Object)).WithNullableAnnotation(method.ReturnNullableAnnotation));
}
return delegateType.TryConstruct(types.ToArray());
}
}
// Otherwise, just default to object.
return compilation.ObjectType;
// local functions
static string WithArity(string typeName, int arity)
=> arity > 0 ? typeName + '`' + arity : typeName;
}
public static bool IsStaticType([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol != null && symbol.Kind == SymbolKind.NamedType && symbol.IsStatic;
public static bool IsNamespace([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol?.Kind == SymbolKind.Namespace;
public static bool IsOrContainsAccessibleAttribute(
[NotNullWhen(returnValue: true)] this ISymbol? symbol, ISymbol withinType, IAssemblySymbol withinAssembly, CancellationToken cancellationToken)
{
var namespaceOrType = symbol is IAliasSymbol alias ? alias.Target : symbol as INamespaceOrTypeSymbol;
if (namespaceOrType == null)
{
return false;
}
// PERF: Avoid allocating a lambda capture
foreach (var type in namespaceOrType.GetAllTypes(cancellationToken))
{
if (type.IsAttribute() && type.IsAccessibleWithin(withinType ?? withinAssembly))
{
return true;
}
}
return false;
}
public static IEnumerable<IPropertySymbol> GetValidAnonymousTypeProperties(this ISymbol symbol)
{
Contract.ThrowIfFalse(symbol.IsNormalAnonymousType());
return ((INamedTypeSymbol)symbol).GetMembers().OfType<IPropertySymbol>().Where(p => p.CanBeReferencedByName);
}
public static Accessibility ComputeResultantAccessibility(this ISymbol? symbol, ITypeSymbol finalDestination)
{
if (symbol == null)
{
return Accessibility.Private;
}
switch (symbol.DeclaredAccessibility)
{
default:
return symbol.DeclaredAccessibility;
case Accessibility.ProtectedAndInternal:
return symbol.ContainingAssembly.GivesAccessTo(finalDestination.ContainingAssembly)
? Accessibility.ProtectedAndInternal
: Accessibility.Internal;
case Accessibility.ProtectedOrInternal:
return symbol.ContainingAssembly.GivesAccessTo(finalDestination.ContainingAssembly)
? Accessibility.ProtectedOrInternal
: Accessibility.Protected;
}
}
/// <returns>
/// Returns true if symbol is a local variable and its declaring syntax node is
/// after the current position, false otherwise (including for non-local symbols)
/// </returns>
public static bool IsInaccessibleLocal(this ISymbol symbol, int position)
{
if (symbol.Kind != SymbolKind.Local)
{
return false;
}
// Implicitly declared locals (with Option Explicit Off in VB) are scoped to the entire
// method and should always be considered accessible from within the same method.
if (symbol.IsImplicitlyDeclared)
{
return false;
}
var declarationSyntax = symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).FirstOrDefault();
return declarationSyntax != null && position < declarationSyntax.SpanStart;
}
public static bool IsAccessor([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> symbol.IsPropertyAccessor() || symbol.IsEventAccessor();
public static bool IsPropertyAccessor([NotNullWhen(returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind.IsPropertyAccessor() == true;
public static bool IsEventAccessor([NotNullWhen(returnValue: true)] this ISymbol? symbol)
{
var method = symbol as IMethodSymbol;
return method != null &&
(method.MethodKind == MethodKind.EventAdd ||
method.MethodKind == MethodKind.EventRaise ||
method.MethodKind == MethodKind.EventRemove);
}
public static bool IsFromSource(this ISymbol symbol)
=> symbol.Locations.Any() && symbol.Locations.All(location => location.IsInSource);
public static bool IsNonImplicitAndFromSource(this ISymbol symbol)
=> !symbol.IsImplicitlyDeclared && symbol.IsFromSource();
public static ITypeSymbol? GetSymbolType(this ISymbol? symbol)
=> symbol switch
{
ILocalSymbol localSymbol => localSymbol.Type,
IFieldSymbol fieldSymbol => fieldSymbol.Type,
IPropertySymbol propertySymbol => propertySymbol.Type,
IParameterSymbol parameterSymbol => parameterSymbol.Type,
IAliasSymbol aliasSymbol => aliasSymbol.Target as ITypeSymbol,
_ => symbol as ITypeSymbol,
};
/// <summary>
/// If the <paramref name="symbol"/> is a method symbol, returns <see langword="true"/> if the method's return type is "awaitable", but not if it's <see langword="dynamic"/>.
/// If the <paramref name="symbol"/> is a type symbol, returns <see langword="true"/> if that type is "awaitable".
/// An "awaitable" is any type that exposes a GetAwaiter method which returns a valid "awaiter". This GetAwaiter method may be an instance method or an extension method.
/// </summary>
public static bool IsAwaitableNonDynamic([NotNullWhen(returnValue: true)] this ISymbol? symbol, SemanticModel semanticModel, int position)
{
var methodSymbol = symbol as IMethodSymbol;
ITypeSymbol? typeSymbol = null;
if (methodSymbol == null)
{
typeSymbol = symbol as ITypeSymbol;
if (typeSymbol == null)
{
return false;
}
}
else
{
if (methodSymbol.ReturnType == null)
{
return false;
}
}
// otherwise: needs valid GetAwaiter
var potentialGetAwaiters = semanticModel.LookupSymbols(position,
container: typeSymbol ?? methodSymbol!.ReturnType.OriginalDefinition,
name: WellKnownMemberNames.GetAwaiter,
includeReducedExtensionMethods: true);
var getAwaiters = potentialGetAwaiters.OfType<IMethodSymbol>().Where(x => !x.Parameters.Any());
return getAwaiters.Any(VerifyGetAwaiter);
}
public static bool IsValidGetAwaiter(this IMethodSymbol symbol)
=> symbol.Name == WellKnownMemberNames.GetAwaiter &&
VerifyGetAwaiter(symbol);
private static bool VerifyGetAwaiter(IMethodSymbol getAwaiter)
{
var returnType = getAwaiter.ReturnType;
if (returnType == null)
{
return false;
}
// bool IsCompleted { get }
if (!returnType.GetMembers().OfType<IPropertySymbol>().Any(p => p.Name == WellKnownMemberNames.IsCompleted && p.Type.SpecialType == SpecialType.System_Boolean && p.GetMethod != null))
{
return false;
}
var methods = returnType.GetMembers().OfType<IMethodSymbol>();
// NOTE: (vladres) The current version of C# Spec, §7.7.7.3 'Runtime evaluation of await expressions', requires that
// NOTE: the interface method INotifyCompletion.OnCompleted or ICriticalNotifyCompletion.UnsafeOnCompleted is invoked
// NOTE: (rather than any OnCompleted method conforming to a certain pattern).
// NOTE: Should this code be updated to match the spec?
// void OnCompleted(Action)
// Actions are delegates, so we'll just check for delegates.
if (!methods.Any(x => x.Name == WellKnownMemberNames.OnCompleted && x.ReturnsVoid && x.Parameters.Length == 1 && x.Parameters.First().Type.TypeKind == TypeKind.Delegate))
{
return false;
}
// void GetResult() || T GetResult()
return methods.Any(m => m.Name == WellKnownMemberNames.GetResult && !m.Parameters.Any());
}
public static bool IsValidGetEnumerator(this IMethodSymbol symbol)
=> symbol.Name == WellKnownMemberNames.GetEnumeratorMethodName &&
VerifyGetEnumerator(symbol);
private static bool VerifyGetEnumerator(IMethodSymbol getEnumerator)
{
var returnType = getEnumerator.ReturnType;
if (returnType == null)
{
return false;
}
var members = returnType.AllInterfaces.Concat(returnType.GetBaseTypesAndThis())
.SelectMany(x => x.GetMembers())
.Where(x => x.DeclaredAccessibility == Accessibility.Public)
.ToList();
// T Current { get }
if (!members.OfType<IPropertySymbol>().Any(p => p.Name == WellKnownMemberNames.CurrentPropertyName && p.GetMethod != null))
{
return false;
}
// bool MoveNext()
if (!members.OfType<IMethodSymbol>().Any(x =>
{
return x is
{
Name: WellKnownMemberNames.MoveNextMethodName,
ReturnType: { SpecialType: SpecialType.System_Boolean },
Parameters: { Length: 0 },
};
}))
{
return false;
}
return true;
}
public static bool IsValidGetAsyncEnumerator(this IMethodSymbol symbol)
=> symbol.Name == WellKnownMemberNames.GetAsyncEnumeratorMethodName &&
VerifyGetAsyncEnumerator(symbol);
private static bool VerifyGetAsyncEnumerator(IMethodSymbol getAsyncEnumerator)
{
var returnType = getAsyncEnumerator.ReturnType;
if (returnType == null)
{
return false;
}
var members = returnType.AllInterfaces.Concat(returnType.GetBaseTypesAndThis())
.SelectMany(x => x.GetMembers())
.Where(x => x.DeclaredAccessibility == Accessibility.Public)
.ToList();
// T Current { get }
if (!members.OfType<IPropertySymbol>().Any(p => p.Name == WellKnownMemberNames.CurrentPropertyName && p.GetMethod != null))
{
return false;
}
// Task<bool> MoveNext()
// We don't check for the return type, since it can be any awaitable wrapping a boolean,
// which is too complex to be worth checking here.
// We don't check number of parameters since MoveNextAsync allows optional parameters/params
if (!members.OfType<IMethodSymbol>().Any(x => x.Name == WellKnownMemberNames.MoveNextAsyncMethodName))
{
return false;
}
return true;
}
public static bool IsKind<TSymbol>(this ISymbol symbol, SymbolKind kind, [NotNullWhen(true)] out TSymbol? result) where TSymbol : class, ISymbol
{
if (!symbol.IsKind(kind))
{
result = null;
return false;
}
result = (TSymbol)symbol;
return true;
}
/// <summary>
/// Returns true for symbols whose name starts with an underscore and
/// are optionally followed by an integer, such as '_', '_1', '_2', etc.
/// These are treated as special discard symbol names.
/// </summary>
public static bool IsSymbolWithSpecialDiscardName(this ISymbol symbol)
=> symbol.Name.StartsWith("_") &&
(symbol.Name.Length == 1 || uint.TryParse(symbol.Name.Substring(1), out _));
/// <summary>
/// Returns <see langword="true"/>, if the symbol is marked with the <see cref="System.ObsoleteAttribute"/>.
/// </summary>
/// <param name="symbol"></param>
/// <returns><see langword="true"/> if the symbol is marked with the <see cref="System.ObsoleteAttribute"/>.</returns>
public static bool IsObsolete(this ISymbol symbol)
=> symbol.GetAttributes().Any(x => x.AttributeClass is
{
MetadataName: nameof(ObsoleteAttribute),
ContainingNamespace: { Name: nameof(System) },
});
}
}
| 1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class ITypeSymbolExtensions
{
public const string DefaultParameterName = "p";
private const string DefaultBuiltInParameterName = "v";
public static bool CanAddNullCheck([NotNullWhen(returnValue: true)] this ITypeSymbol? type)
{
if (type == null)
return false;
var isNullableValueType = type.IsNullable();
var isNonNullableReferenceType = type.IsReferenceType && type.NullableAnnotation != NullableAnnotation.Annotated;
return isNullableValueType || isNonNullableReferenceType;
}
public static IList<INamedTypeSymbol> GetAllInterfacesIncludingThis(this ITypeSymbol type)
{
var allInterfaces = type.AllInterfaces;
if (type is INamedTypeSymbol namedType && namedType.TypeKind == TypeKind.Interface && !allInterfaces.Contains(namedType))
{
var result = new List<INamedTypeSymbol>(allInterfaces.Length + 1);
result.Add(namedType);
result.AddRange(allInterfaces);
return result;
}
return allInterfaces;
}
public static bool IsAbstractClass([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.TypeKind == TypeKind.Class && symbol.IsAbstract;
public static bool IsSystemVoid([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.SpecialType == SpecialType.System_Void;
public static bool IsNullable([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
public static bool IsNonNullableValueType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
{
if (symbol?.IsValueType != true)
return false;
return !symbol.IsNullable();
}
public static bool IsNullable(
[NotNullWhen(true)] this ITypeSymbol? symbol,
[NotNullWhen(true)] out ITypeSymbol? underlyingType)
{
if (IsNullable(symbol))
{
underlyingType = ((INamedTypeSymbol)symbol).TypeArguments[0];
return true;
}
underlyingType = null;
return false;
}
public static bool IsModuleType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.TypeKind == TypeKind.Module;
public static bool IsInterfaceType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.TypeKind == TypeKind.Interface;
public static bool IsDelegateType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.TypeKind == TypeKind.Delegate;
public static bool IsFunctionPointerType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.TypeKind == TypeKind.FunctionPointer;
public static bool IsStructType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.TypeKind == TypeKind.Struct;
public static bool IsAnonymousType([NotNullWhen(returnValue: true)] this INamedTypeSymbol? symbol)
=> symbol?.IsAnonymousType == true;
private static HashSet<INamedTypeSymbol> GetOriginalInterfacesAndTheirBaseInterfaces(
this ITypeSymbol type,
HashSet<INamedTypeSymbol>? symbols = null)
{
symbols ??= new HashSet<INamedTypeSymbol>(SymbolEquivalenceComparer.Instance);
foreach (var interfaceType in type.Interfaces)
{
symbols.Add(interfaceType.OriginalDefinition);
symbols.AddRange(interfaceType.AllInterfaces.Select(i => i.OriginalDefinition));
}
return symbols;
}
public static IEnumerable<ITypeSymbol> GetBaseTypesAndThis(this ITypeSymbol? type)
{
var current = type;
while (current != null)
{
yield return current;
current = current.BaseType;
}
}
public static IEnumerable<INamedTypeSymbol> GetBaseTypes(this ITypeSymbol type)
{
var current = type.BaseType;
while (current != null)
{
yield return current;
current = current.BaseType;
}
}
public static IEnumerable<ITypeSymbol> GetContainingTypesAndThis(this ITypeSymbol? type)
{
var current = type;
while (current != null)
{
yield return current;
current = current.ContainingType;
}
}
public static IEnumerable<INamedTypeSymbol> GetContainingTypes(this ITypeSymbol type)
{
var current = type.ContainingType;
while (current != null)
{
yield return current;
current = current.ContainingType;
}
}
// Determine if "type" inherits from "baseType", ignoring constructed types, optionally including interfaces,
// dealing only with original types.
public static bool InheritsFromOrEquals(
this ITypeSymbol type, ITypeSymbol baseType, bool includeInterfaces)
{
if (!includeInterfaces)
{
return InheritsFromOrEquals(type, baseType);
}
return type.GetBaseTypesAndThis().Concat(type.AllInterfaces).Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, baseType));
}
// Determine if "type" inherits from "baseType", ignoring constructed types and interfaces, dealing
// only with original types.
public static bool InheritsFromOrEquals(
this ITypeSymbol type, ITypeSymbol baseType)
{
return type.GetBaseTypesAndThis().Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, baseType));
}
// Determine if "type" inherits from or implements "baseType", ignoring constructed types, and dealing
// only with original types.
public static bool InheritsFromOrImplementsOrEqualsIgnoringConstruction(
this ITypeSymbol type, ITypeSymbol baseType)
{
var originalBaseType = baseType.OriginalDefinition;
type = type.OriginalDefinition;
if (SymbolEquivalenceComparer.Instance.Equals(type, originalBaseType))
{
return true;
}
IEnumerable<ITypeSymbol> baseTypes = (baseType.TypeKind == TypeKind.Interface) ? type.AllInterfaces : type.GetBaseTypes();
return baseTypes.Contains(t => SymbolEquivalenceComparer.Instance.Equals(t.OriginalDefinition, originalBaseType));
}
// Determine if "type" inherits from "baseType", ignoring constructed types, and dealing
// only with original types.
public static bool InheritsFromIgnoringConstruction(
this ITypeSymbol type, ITypeSymbol baseType)
{
var originalBaseType = baseType.OriginalDefinition;
// We could just call GetBaseTypes and foreach over it, but this
// is a hot path in Find All References. This avoid the allocation
// of the enumerator type.
var currentBaseType = type.BaseType;
while (currentBaseType != null)
{
if (SymbolEquivalenceComparer.Instance.Equals(currentBaseType.OriginalDefinition, originalBaseType))
{
return true;
}
currentBaseType = currentBaseType.BaseType;
}
return false;
}
public static bool ImplementsIgnoringConstruction(
this ITypeSymbol type, ITypeSymbol interfaceType)
{
var originalInterfaceType = interfaceType.OriginalDefinition;
return type.AllInterfaces.Any(t => SymbolEquivalenceComparer.Instance.Equals(t.OriginalDefinition, originalInterfaceType));
}
public static bool Implements(
this ITypeSymbol type, ITypeSymbol interfaceType)
{
return type.AllInterfaces.Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, interfaceType));
}
public static bool IsAttribute(this ITypeSymbol symbol)
{
for (var b = symbol.BaseType; b != null; b = b.BaseType)
{
if (b.MetadataName == "Attribute" &&
b.ContainingType == null &&
b.ContainingNamespace != null &&
b.ContainingNamespace.Name == "System" &&
b.ContainingNamespace.ContainingNamespace != null &&
b.ContainingNamespace.ContainingNamespace.IsGlobalNamespace)
{
return true;
}
}
return false;
}
public static bool IsFormattableStringOrIFormattable([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
{
return symbol?.MetadataName is nameof(FormattableString) or nameof(IFormattable)
&& symbol.ContainingType == null
&& symbol.ContainingNamespace?.Name == "System"
&& symbol.ContainingNamespace.ContainingNamespace?.IsGlobalNamespace == true;
}
public static bool IsUnexpressibleTypeParameterConstraint(this ITypeSymbol typeSymbol)
{
if (typeSymbol.IsSealed || typeSymbol.IsValueType)
{
return true;
}
switch (typeSymbol.TypeKind)
{
case TypeKind.Array:
case TypeKind.Delegate:
return true;
}
switch (typeSymbol.SpecialType)
{
case SpecialType.System_Array:
case SpecialType.System_Delegate:
case SpecialType.System_MulticastDelegate:
case SpecialType.System_Enum:
case SpecialType.System_ValueType:
return true;
}
return false;
}
public static bool IsNumericType([NotNullWhen(returnValue: true)] this ITypeSymbol? type)
{
if (type != null)
{
switch (type.SpecialType)
{
case SpecialType.System_Byte:
case SpecialType.System_SByte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_Decimal:
case SpecialType.System_IntPtr when type.IsNativeIntegerType:
case SpecialType.System_UIntPtr when type.IsNativeIntegerType:
return true;
}
}
return false;
}
public static Accessibility DetermineMinimalAccessibility(this ITypeSymbol typeSymbol)
=> typeSymbol.Accept(MinimalAccessibilityVisitor.Instance);
public static bool ContainsAnonymousType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
{
switch (symbol)
{
case IArrayTypeSymbol a: return ContainsAnonymousType(a.ElementType);
case IPointerTypeSymbol p: return ContainsAnonymousType(p.PointedAtType);
case INamedTypeSymbol n: return ContainsAnonymousType(n);
default: return false;
}
}
private static bool ContainsAnonymousType(INamedTypeSymbol type)
{
if (type.IsAnonymousType)
{
return true;
}
foreach (var typeArg in type.GetAllTypeArguments())
{
if (ContainsAnonymousType(typeArg))
{
return true;
}
}
return false;
}
public static string CreateParameterName(this ITypeSymbol type, bool capitalize = false)
{
while (true)
{
switch (type)
{
case IArrayTypeSymbol arrayType:
type = arrayType.ElementType;
continue;
case IPointerTypeSymbol pointerType:
type = pointerType.PointedAtType;
continue;
}
break;
}
var shortName = GetParameterName(type);
return capitalize ? shortName.ToPascalCase() : shortName.ToCamelCase();
}
private static string GetParameterName(ITypeSymbol? type)
{
if (type == null || type.IsAnonymousType() || type.IsTupleType)
{
return DefaultParameterName;
}
if (type.IsSpecialType() || type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
{
return DefaultBuiltInParameterName;
}
var shortName = type.GetShortName();
return shortName.Length == 0
? DefaultParameterName
: shortName;
}
public static bool IsSpecialType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
{
if (symbol != null)
{
switch (symbol.SpecialType)
{
case SpecialType.System_Object:
case SpecialType.System_Void:
case SpecialType.System_Boolean:
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Decimal:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_Int16:
case SpecialType.System_Int32:
case SpecialType.System_Int64:
case SpecialType.System_Char:
case SpecialType.System_String:
case SpecialType.System_UInt16:
case SpecialType.System_UInt32:
case SpecialType.System_UInt64:
case SpecialType.System_IntPtr when symbol.IsNativeIntegerType:
case SpecialType.System_UIntPtr when symbol.IsNativeIntegerType:
return true;
}
}
return false;
}
public static bool CanSupportCollectionInitializer(this ITypeSymbol typeSymbol, ISymbol within)
{
return
typeSymbol.AllInterfaces.Any(i => i.SpecialType == SpecialType.System_Collections_IEnumerable) &&
typeSymbol.GetBaseTypesAndThis()
.Union(typeSymbol.GetOriginalInterfacesAndTheirBaseInterfaces())
.SelectAccessibleMembers<IMethodSymbol>(WellKnownMemberNames.CollectionInitializerAddMethodName, within ?? typeSymbol)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Any());
}
public static INamedTypeSymbol? GetDelegateType(this ITypeSymbol? typeSymbol, Compilation compilation)
{
if (typeSymbol != null)
{
var expressionOfT = compilation.ExpressionOfTType();
if (typeSymbol.OriginalDefinition.Equals(expressionOfT))
{
var typeArgument = ((INamedTypeSymbol)typeSymbol).TypeArguments[0];
return typeArgument as INamedTypeSymbol;
}
if (typeSymbol.IsDelegateType())
{
return typeSymbol as INamedTypeSymbol;
}
}
return null;
}
public static IEnumerable<T> GetAccessibleMembersInBaseTypes<T>(this ITypeSymbol containingType, ISymbol within) where T : class, ISymbol
{
if (containingType == null)
{
return SpecializedCollections.EmptyEnumerable<T>();
}
var types = containingType.GetBaseTypes();
return types.SelectMany(x => x.GetMembers().OfType<T>().Where(m => m.IsAccessibleWithin(within)));
}
public static ImmutableArray<T> GetAccessibleMembersInThisAndBaseTypes<T>(this ITypeSymbol? containingType, ISymbol within) where T : class, ISymbol
{
if (containingType == null)
{
return ImmutableArray<T>.Empty;
}
return containingType.GetBaseTypesAndThis().SelectAccessibleMembers<T>(within).ToImmutableArray();
}
public static bool? AreMoreSpecificThan(this IList<ITypeSymbol> t1, IList<ITypeSymbol> t2)
{
if (t1.Count != t2.Count)
{
return null;
}
// For t1 to be more specific than t2, it has to be not less specific in every member,
// and more specific in at least one.
bool? result = null;
for (var i = 0; i < t1.Count; ++i)
{
var r = t1[i].IsMoreSpecificThan(t2[i]);
if (r == null)
{
// We learned nothing. Do nothing.
}
else if (result == null)
{
// We have found the first more specific type. See if
// all the rest on this side are not less specific.
result = r;
}
else if (result != r)
{
// We have more specific types on both left and right, so we
// cannot succeed in picking a better type list. Bail out now.
return null;
}
}
return result;
}
public static IEnumerable<T> SelectAccessibleMembers<T>(this IEnumerable<ITypeSymbol>? types, ISymbol within) where T : class, ISymbol
{
if (types == null)
{
return ImmutableArray<T>.Empty;
}
return types.SelectMany(x => x.GetMembers().OfType<T>().Where(m => m.IsAccessibleWithin(within)));
}
private static IEnumerable<T> SelectAccessibleMembers<T>(this IEnumerable<ITypeSymbol>? types, string memberName, ISymbol within) where T : class, ISymbol
{
if (types == null)
{
return ImmutableArray<T>.Empty;
}
return types.SelectMany(x => x.GetMembers(memberName).OfType<T>().Where(m => m.IsAccessibleWithin(within)));
}
private static bool? IsMoreSpecificThan(this ITypeSymbol t1, ITypeSymbol t2)
{
// SPEC: A type parameter is less specific than a non-type parameter.
var isTypeParameter1 = t1 is ITypeParameterSymbol;
var isTypeParameter2 = t2 is ITypeParameterSymbol;
if (isTypeParameter1 && !isTypeParameter2)
{
return false;
}
if (!isTypeParameter1 && isTypeParameter2)
{
return true;
}
if (isTypeParameter1)
{
Debug.Assert(isTypeParameter2);
return null;
}
if (t1.TypeKind != t2.TypeKind)
{
return null;
}
// There is an identity conversion between the types and they are both substitutions on type parameters.
// They had better be the same kind.
// UNDONE: Strip off the dynamics.
// SPEC: An array type is more specific than another
// SPEC: array type (with the same number of dimensions)
// SPEC: if the element type of the first is
// SPEC: more specific than the element type of the second.
if (t1 is IArrayTypeSymbol)
{
var arr1 = (IArrayTypeSymbol)t1;
var arr2 = (IArrayTypeSymbol)t2;
// We should not have gotten here unless there were identity conversions
// between the two types.
return arr1.ElementType.IsMoreSpecificThan(arr2.ElementType);
}
// SPEC EXTENSION: We apply the same rule to pointer types.
if (t1 is IPointerTypeSymbol)
{
var p1 = (IPointerTypeSymbol)t1;
var p2 = (IPointerTypeSymbol)t2;
return p1.PointedAtType.IsMoreSpecificThan(p2.PointedAtType);
}
// SPEC: A constructed type is more specific than another
// SPEC: constructed type (with the same number of type arguments) if at least one type
// SPEC: argument is more specific and no type argument is less specific than the
// SPEC: corresponding type argument in the other.
var n1 = t1 as INamedTypeSymbol;
var n2 = t2 as INamedTypeSymbol;
if (n1 == null)
{
return null;
}
// We should not have gotten here unless there were identity conversions between the
// two types.
var allTypeArgs1 = n1.GetAllTypeArguments().ToList();
var allTypeArgs2 = n2.GetAllTypeArguments().ToList();
return allTypeArgs1.AreMoreSpecificThan(allTypeArgs2);
}
public static bool IsOrDerivesFromExceptionType([NotNullWhen(returnValue: true)] this ITypeSymbol? type, Compilation compilation)
{
if (type != null)
{
switch (type.Kind)
{
case SymbolKind.NamedType:
foreach (var baseType in type.GetBaseTypesAndThis())
{
if (baseType.Equals(compilation.ExceptionType()))
{
return true;
}
}
break;
case SymbolKind.TypeParameter:
foreach (var constraint in ((ITypeParameterSymbol)type).ConstraintTypes)
{
if (constraint.IsOrDerivesFromExceptionType(compilation))
{
return true;
}
}
break;
}
}
return false;
}
public static bool IsEnumType([NotNullWhen(true)] this ITypeSymbol? type)
=> IsEnumType(type, out _);
public static bool IsEnumType([NotNullWhen(true)] this ITypeSymbol? type, [NotNullWhen(true)] out INamedTypeSymbol? enumType)
{
if (type != null && type.IsValueType && type.TypeKind == TypeKind.Enum)
{
enumType = (INamedTypeSymbol)type;
return true;
}
enumType = null;
return false;
}
public static bool? IsMutableValueType(this ITypeSymbol type)
{
if (type.IsNullable())
{
// Nullable<T> can only be mutable if T is mutable. This case ensures types like 'int?' are treated as
// immutable.
type = type.GetTypeArguments()[0];
}
switch (type.SpecialType)
{
case SpecialType.System_Boolean:
case SpecialType.System_Char:
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_Decimal:
case SpecialType.System_Single:
case SpecialType.System_Double:
return false;
case SpecialType.System_IntPtr:
case SpecialType.System_UIntPtr:
return false;
case SpecialType.System_DateTime:
return false;
default:
break;
}
if (type.IsErrorType())
{
return null;
}
if (type.TypeKind != TypeKind.Struct)
{
return false;
}
var hasPrivateField = false;
foreach (var member in type.GetMembers())
{
if (!(member is IFieldSymbol fieldSymbol))
{
continue;
}
hasPrivateField |= fieldSymbol.DeclaredAccessibility == Accessibility.Private;
if (!fieldSymbol.IsConst && !fieldSymbol.IsReadOnly && !fieldSymbol.IsStatic)
{
return true;
}
}
if (!hasPrivateField)
{
// Some reference assemblies omit information about private fields. If we can't be sure the field is
// immutable, treat it as potentially mutable.
foreach (var attributeData in type.ContainingAssembly.GetAttributes())
{
if (attributeData.AttributeClass?.Name == nameof(ReferenceAssemblyAttribute)
&& attributeData.AttributeClass.ToNameDisplayString() == typeof(ReferenceAssemblyAttribute).FullName)
{
return null;
}
}
}
return false;
}
public static bool IsDisposable([NotNullWhen(returnValue: true)] this ITypeSymbol? type, [NotNullWhen(returnValue: true)] ITypeSymbol? iDisposableType)
=> iDisposableType != null &&
(Equals(iDisposableType, type) ||
type?.AllInterfaces.Contains(iDisposableType) == true);
public static ITypeSymbol WithNullableAnnotationFrom(this ITypeSymbol type, ITypeSymbol symbolForNullableAnnotation)
=> type.WithNullableAnnotation(symbolForNullableAnnotation.NullableAnnotation);
[return: NotNullIfNotNull(parameterName: "symbol")]
public static ITypeSymbol? RemoveNullableIfPresent(this ITypeSymbol? symbol)
{
if (symbol.IsNullable())
{
return symbol.GetTypeArguments().Single();
}
return symbol;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class ITypeSymbolExtensions
{
public const string DefaultParameterName = "p";
private const string DefaultBuiltInParameterName = "v";
public static bool CanAddNullCheck([NotNullWhen(returnValue: true)] this ITypeSymbol? type)
{
if (type == null)
return false;
var isNullableValueType = type.IsNullable();
var isNonNullableReferenceType = type.IsReferenceType && type.NullableAnnotation != NullableAnnotation.Annotated;
return isNullableValueType || isNonNullableReferenceType;
}
public static IList<INamedTypeSymbol> GetAllInterfacesIncludingThis(this ITypeSymbol type)
{
var allInterfaces = type.AllInterfaces;
if (type is INamedTypeSymbol namedType && namedType.TypeKind == TypeKind.Interface && !allInterfaces.Contains(namedType))
{
var result = new List<INamedTypeSymbol>(allInterfaces.Length + 1);
result.Add(namedType);
result.AddRange(allInterfaces);
return result;
}
return allInterfaces;
}
public static bool IsAbstractClass([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.TypeKind == TypeKind.Class && symbol.IsAbstract;
public static bool IsSystemVoid([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.SpecialType == SpecialType.System_Void;
public static bool IsNullable([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
public static bool IsNonNullableValueType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
{
if (symbol?.IsValueType != true)
return false;
return !symbol.IsNullable();
}
public static bool IsNullable(
[NotNullWhen(true)] this ITypeSymbol? symbol,
[NotNullWhen(true)] out ITypeSymbol? underlyingType)
{
if (IsNullable(symbol))
{
underlyingType = ((INamedTypeSymbol)symbol).TypeArguments[0];
return true;
}
underlyingType = null;
return false;
}
public static bool IsModuleType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.TypeKind == TypeKind.Module;
public static bool IsInterfaceType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.TypeKind == TypeKind.Interface;
public static bool IsDelegateType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.TypeKind == TypeKind.Delegate;
public static bool IsFunctionPointerType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.TypeKind == TypeKind.FunctionPointer;
public static bool IsStructType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
=> symbol?.TypeKind == TypeKind.Struct;
public static bool IsAnonymousType([NotNullWhen(returnValue: true)] this INamedTypeSymbol? symbol)
=> symbol?.IsAnonymousType == true;
private static HashSet<INamedTypeSymbol> GetOriginalInterfacesAndTheirBaseInterfaces(
this ITypeSymbol type,
HashSet<INamedTypeSymbol>? symbols = null)
{
symbols ??= new HashSet<INamedTypeSymbol>(SymbolEquivalenceComparer.Instance);
foreach (var interfaceType in type.Interfaces)
{
symbols.Add(interfaceType.OriginalDefinition);
symbols.AddRange(interfaceType.AllInterfaces.Select(i => i.OriginalDefinition));
}
return symbols;
}
public static IEnumerable<ITypeSymbol> GetBaseTypesAndThis(this ITypeSymbol? type)
{
var current = type;
while (current != null)
{
yield return current;
current = current.BaseType;
}
}
public static IEnumerable<INamedTypeSymbol> GetBaseTypes(this ITypeSymbol type)
{
var current = type.BaseType;
while (current != null)
{
yield return current;
current = current.BaseType;
}
}
public static IEnumerable<ITypeSymbol> GetContainingTypesAndThis(this ITypeSymbol? type)
{
var current = type;
while (current != null)
{
yield return current;
current = current.ContainingType;
}
}
public static IEnumerable<INamedTypeSymbol> GetContainingTypes(this ITypeSymbol type)
{
var current = type.ContainingType;
while (current != null)
{
yield return current;
current = current.ContainingType;
}
}
// Determine if "type" inherits from "baseType", ignoring constructed types, optionally including interfaces,
// dealing only with original types.
public static bool InheritsFromOrEquals(
this ITypeSymbol type, ITypeSymbol baseType, bool includeInterfaces)
{
if (!includeInterfaces)
{
return InheritsFromOrEquals(type, baseType);
}
return type.GetBaseTypesAndThis().Concat(type.AllInterfaces).Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, baseType));
}
// Determine if "type" inherits from "baseType", ignoring constructed types and interfaces, dealing
// only with original types.
public static bool InheritsFromOrEquals(
this ITypeSymbol type, ITypeSymbol baseType)
{
return type.GetBaseTypesAndThis().Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, baseType));
}
// Determine if "type" inherits from or implements "baseType", ignoring constructed types, and dealing
// only with original types.
public static bool InheritsFromOrImplementsOrEqualsIgnoringConstruction(
this ITypeSymbol type, ITypeSymbol baseType)
{
var originalBaseType = baseType.OriginalDefinition;
type = type.OriginalDefinition;
if (SymbolEquivalenceComparer.Instance.Equals(type, originalBaseType))
{
return true;
}
IEnumerable<ITypeSymbol> baseTypes = (baseType.TypeKind == TypeKind.Interface) ? type.AllInterfaces : type.GetBaseTypes();
return baseTypes.Contains(t => SymbolEquivalenceComparer.Instance.Equals(t.OriginalDefinition, originalBaseType));
}
// Determine if "type" inherits from "baseType", ignoring constructed types, and dealing
// only with original types.
public static bool InheritsFromIgnoringConstruction(
this ITypeSymbol type, ITypeSymbol baseType)
{
var originalBaseType = baseType.OriginalDefinition;
// We could just call GetBaseTypes and foreach over it, but this
// is a hot path in Find All References. This avoid the allocation
// of the enumerator type.
var currentBaseType = type.BaseType;
while (currentBaseType != null)
{
if (SymbolEquivalenceComparer.Instance.Equals(currentBaseType.OriginalDefinition, originalBaseType))
{
return true;
}
currentBaseType = currentBaseType.BaseType;
}
return false;
}
public static bool ImplementsIgnoringConstruction(
this ITypeSymbol type, ITypeSymbol interfaceType)
{
var originalInterfaceType = interfaceType.OriginalDefinition;
return type.AllInterfaces.Any(t => SymbolEquivalenceComparer.Instance.Equals(t.OriginalDefinition, originalInterfaceType));
}
public static bool Implements(
this ITypeSymbol type, ITypeSymbol interfaceType)
{
return type.AllInterfaces.Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, interfaceType));
}
public static bool IsAttribute(this ITypeSymbol symbol)
{
for (var b = symbol.BaseType; b != null; b = b.BaseType)
{
if (b.MetadataName == "Attribute" &&
b.ContainingType == null &&
b.ContainingNamespace != null &&
b.ContainingNamespace.Name == "System" &&
b.ContainingNamespace.ContainingNamespace != null &&
b.ContainingNamespace.ContainingNamespace.IsGlobalNamespace)
{
return true;
}
}
return false;
}
public static bool IsFormattableStringOrIFormattable([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
{
return symbol?.MetadataName is nameof(FormattableString) or nameof(IFormattable)
&& symbol.ContainingType == null
&& symbol.ContainingNamespace?.Name == "System"
&& symbol.ContainingNamespace.ContainingNamespace?.IsGlobalNamespace == true;
}
public static bool IsUnexpressibleTypeParameterConstraint(this ITypeSymbol typeSymbol)
{
if (typeSymbol.IsSealed || typeSymbol.IsValueType)
{
return true;
}
switch (typeSymbol.TypeKind)
{
case TypeKind.Array:
case TypeKind.Delegate:
return true;
}
switch (typeSymbol.SpecialType)
{
case SpecialType.System_Array:
case SpecialType.System_Delegate:
case SpecialType.System_MulticastDelegate:
case SpecialType.System_Enum:
case SpecialType.System_ValueType:
return true;
}
return false;
}
public static bool IsNumericType([NotNullWhen(returnValue: true)] this ITypeSymbol? type)
{
if (type != null)
{
switch (type.SpecialType)
{
case SpecialType.System_Byte:
case SpecialType.System_SByte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_Decimal:
case SpecialType.System_IntPtr when type.IsNativeIntegerType:
case SpecialType.System_UIntPtr when type.IsNativeIntegerType:
return true;
}
}
return false;
}
public static Accessibility DetermineMinimalAccessibility(this ITypeSymbol typeSymbol)
=> typeSymbol.Accept(MinimalAccessibilityVisitor.Instance);
public static bool ContainsAnonymousType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
{
switch (symbol)
{
case IArrayTypeSymbol a: return ContainsAnonymousType(a.ElementType);
case IPointerTypeSymbol p: return ContainsAnonymousType(p.PointedAtType);
case INamedTypeSymbol n: return ContainsAnonymousType(n);
default: return false;
}
}
private static bool ContainsAnonymousType(INamedTypeSymbol type)
{
if (type.IsAnonymousType || type.IsAnonymousDelegateType())
return true;
foreach (var typeArg in type.GetAllTypeArguments())
{
if (ContainsAnonymousType(typeArg))
return true;
}
return false;
}
public static string CreateParameterName(this ITypeSymbol type, bool capitalize = false)
{
while (true)
{
switch (type)
{
case IArrayTypeSymbol arrayType:
type = arrayType.ElementType;
continue;
case IPointerTypeSymbol pointerType:
type = pointerType.PointedAtType;
continue;
}
break;
}
var shortName = GetParameterName(type);
return capitalize ? shortName.ToPascalCase() : shortName.ToCamelCase();
}
private static string GetParameterName(ITypeSymbol? type)
{
if (type == null || type.IsAnonymousType() || type.IsTupleType)
{
return DefaultParameterName;
}
if (type.IsSpecialType() || type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
{
return DefaultBuiltInParameterName;
}
var shortName = type.GetShortName();
return shortName.Length == 0
? DefaultParameterName
: shortName;
}
public static bool IsSpecialType([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol)
{
if (symbol != null)
{
switch (symbol.SpecialType)
{
case SpecialType.System_Object:
case SpecialType.System_Void:
case SpecialType.System_Boolean:
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Decimal:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_Int16:
case SpecialType.System_Int32:
case SpecialType.System_Int64:
case SpecialType.System_Char:
case SpecialType.System_String:
case SpecialType.System_UInt16:
case SpecialType.System_UInt32:
case SpecialType.System_UInt64:
case SpecialType.System_IntPtr when symbol.IsNativeIntegerType:
case SpecialType.System_UIntPtr when symbol.IsNativeIntegerType:
return true;
}
}
return false;
}
public static bool CanSupportCollectionInitializer(this ITypeSymbol typeSymbol, ISymbol within)
{
return
typeSymbol.AllInterfaces.Any(i => i.SpecialType == SpecialType.System_Collections_IEnumerable) &&
typeSymbol.GetBaseTypesAndThis()
.Union(typeSymbol.GetOriginalInterfacesAndTheirBaseInterfaces())
.SelectAccessibleMembers<IMethodSymbol>(WellKnownMemberNames.CollectionInitializerAddMethodName, within ?? typeSymbol)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Any());
}
public static INamedTypeSymbol? GetDelegateType(this ITypeSymbol? typeSymbol, Compilation compilation)
{
if (typeSymbol != null)
{
var expressionOfT = compilation.ExpressionOfTType();
if (typeSymbol.OriginalDefinition.Equals(expressionOfT))
{
var typeArgument = ((INamedTypeSymbol)typeSymbol).TypeArguments[0];
return typeArgument as INamedTypeSymbol;
}
if (typeSymbol.IsDelegateType())
{
return typeSymbol as INamedTypeSymbol;
}
}
return null;
}
public static IEnumerable<T> GetAccessibleMembersInBaseTypes<T>(this ITypeSymbol containingType, ISymbol within) where T : class, ISymbol
{
if (containingType == null)
{
return SpecializedCollections.EmptyEnumerable<T>();
}
var types = containingType.GetBaseTypes();
return types.SelectMany(x => x.GetMembers().OfType<T>().Where(m => m.IsAccessibleWithin(within)));
}
public static ImmutableArray<T> GetAccessibleMembersInThisAndBaseTypes<T>(this ITypeSymbol? containingType, ISymbol within) where T : class, ISymbol
{
if (containingType == null)
{
return ImmutableArray<T>.Empty;
}
return containingType.GetBaseTypesAndThis().SelectAccessibleMembers<T>(within).ToImmutableArray();
}
public static bool? AreMoreSpecificThan(this IList<ITypeSymbol> t1, IList<ITypeSymbol> t2)
{
if (t1.Count != t2.Count)
{
return null;
}
// For t1 to be more specific than t2, it has to be not less specific in every member,
// and more specific in at least one.
bool? result = null;
for (var i = 0; i < t1.Count; ++i)
{
var r = t1[i].IsMoreSpecificThan(t2[i]);
if (r == null)
{
// We learned nothing. Do nothing.
}
else if (result == null)
{
// We have found the first more specific type. See if
// all the rest on this side are not less specific.
result = r;
}
else if (result != r)
{
// We have more specific types on both left and right, so we
// cannot succeed in picking a better type list. Bail out now.
return null;
}
}
return result;
}
public static IEnumerable<T> SelectAccessibleMembers<T>(this IEnumerable<ITypeSymbol>? types, ISymbol within) where T : class, ISymbol
{
if (types == null)
{
return ImmutableArray<T>.Empty;
}
return types.SelectMany(x => x.GetMembers().OfType<T>().Where(m => m.IsAccessibleWithin(within)));
}
private static IEnumerable<T> SelectAccessibleMembers<T>(this IEnumerable<ITypeSymbol>? types, string memberName, ISymbol within) where T : class, ISymbol
{
if (types == null)
{
return ImmutableArray<T>.Empty;
}
return types.SelectMany(x => x.GetMembers(memberName).OfType<T>().Where(m => m.IsAccessibleWithin(within)));
}
private static bool? IsMoreSpecificThan(this ITypeSymbol t1, ITypeSymbol t2)
{
// SPEC: A type parameter is less specific than a non-type parameter.
var isTypeParameter1 = t1 is ITypeParameterSymbol;
var isTypeParameter2 = t2 is ITypeParameterSymbol;
if (isTypeParameter1 && !isTypeParameter2)
{
return false;
}
if (!isTypeParameter1 && isTypeParameter2)
{
return true;
}
if (isTypeParameter1)
{
Debug.Assert(isTypeParameter2);
return null;
}
if (t1.TypeKind != t2.TypeKind)
{
return null;
}
// There is an identity conversion between the types and they are both substitutions on type parameters.
// They had better be the same kind.
// UNDONE: Strip off the dynamics.
// SPEC: An array type is more specific than another
// SPEC: array type (with the same number of dimensions)
// SPEC: if the element type of the first is
// SPEC: more specific than the element type of the second.
if (t1 is IArrayTypeSymbol)
{
var arr1 = (IArrayTypeSymbol)t1;
var arr2 = (IArrayTypeSymbol)t2;
// We should not have gotten here unless there were identity conversions
// between the two types.
return arr1.ElementType.IsMoreSpecificThan(arr2.ElementType);
}
// SPEC EXTENSION: We apply the same rule to pointer types.
if (t1 is IPointerTypeSymbol)
{
var p1 = (IPointerTypeSymbol)t1;
var p2 = (IPointerTypeSymbol)t2;
return p1.PointedAtType.IsMoreSpecificThan(p2.PointedAtType);
}
// SPEC: A constructed type is more specific than another
// SPEC: constructed type (with the same number of type arguments) if at least one type
// SPEC: argument is more specific and no type argument is less specific than the
// SPEC: corresponding type argument in the other.
var n1 = t1 as INamedTypeSymbol;
var n2 = t2 as INamedTypeSymbol;
if (n1 == null)
{
return null;
}
// We should not have gotten here unless there were identity conversions between the
// two types.
var allTypeArgs1 = n1.GetAllTypeArguments().ToList();
var allTypeArgs2 = n2.GetAllTypeArguments().ToList();
return allTypeArgs1.AreMoreSpecificThan(allTypeArgs2);
}
public static bool IsOrDerivesFromExceptionType([NotNullWhen(returnValue: true)] this ITypeSymbol? type, Compilation compilation)
{
if (type != null)
{
switch (type.Kind)
{
case SymbolKind.NamedType:
foreach (var baseType in type.GetBaseTypesAndThis())
{
if (baseType.Equals(compilation.ExceptionType()))
{
return true;
}
}
break;
case SymbolKind.TypeParameter:
foreach (var constraint in ((ITypeParameterSymbol)type).ConstraintTypes)
{
if (constraint.IsOrDerivesFromExceptionType(compilation))
{
return true;
}
}
break;
}
}
return false;
}
public static bool IsEnumType([NotNullWhen(true)] this ITypeSymbol? type)
=> IsEnumType(type, out _);
public static bool IsEnumType([NotNullWhen(true)] this ITypeSymbol? type, [NotNullWhen(true)] out INamedTypeSymbol? enumType)
{
if (type != null && type.IsValueType && type.TypeKind == TypeKind.Enum)
{
enumType = (INamedTypeSymbol)type;
return true;
}
enumType = null;
return false;
}
public static bool? IsMutableValueType(this ITypeSymbol type)
{
if (type.IsNullable())
{
// Nullable<T> can only be mutable if T is mutable. This case ensures types like 'int?' are treated as
// immutable.
type = type.GetTypeArguments()[0];
}
switch (type.SpecialType)
{
case SpecialType.System_Boolean:
case SpecialType.System_Char:
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_Decimal:
case SpecialType.System_Single:
case SpecialType.System_Double:
return false;
case SpecialType.System_IntPtr:
case SpecialType.System_UIntPtr:
return false;
case SpecialType.System_DateTime:
return false;
default:
break;
}
if (type.IsErrorType())
{
return null;
}
if (type.TypeKind != TypeKind.Struct)
{
return false;
}
var hasPrivateField = false;
foreach (var member in type.GetMembers())
{
if (!(member is IFieldSymbol fieldSymbol))
{
continue;
}
hasPrivateField |= fieldSymbol.DeclaredAccessibility == Accessibility.Private;
if (!fieldSymbol.IsConst && !fieldSymbol.IsReadOnly && !fieldSymbol.IsStatic)
{
return true;
}
}
if (!hasPrivateField)
{
// Some reference assemblies omit information about private fields. If we can't be sure the field is
// immutable, treat it as potentially mutable.
foreach (var attributeData in type.ContainingAssembly.GetAttributes())
{
if (attributeData.AttributeClass?.Name == nameof(ReferenceAssemblyAttribute)
&& attributeData.AttributeClass.ToNameDisplayString() == typeof(ReferenceAssemblyAttribute).FullName)
{
return null;
}
}
}
return false;
}
public static bool IsDisposable([NotNullWhen(returnValue: true)] this ITypeSymbol? type, [NotNullWhen(returnValue: true)] ITypeSymbol? iDisposableType)
=> iDisposableType != null &&
(Equals(iDisposableType, type) ||
type?.AllInterfaces.Contains(iDisposableType) == true);
public static ITypeSymbol WithNullableAnnotationFrom(this ITypeSymbol type, ITypeSymbol symbolForNullableAnnotation)
=> type.WithNullableAnnotation(symbolForNullableAnnotation.NullableAnnotation);
[return: NotNullIfNotNull(parameterName: "symbol")]
public static ITypeSymbol? RemoveNullableIfPresent(this ITypeSymbol? symbol)
{
if (symbol.IsNullable())
{
return symbol.GetTypeArguments().Single();
}
return symbol;
}
}
}
| 1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Features/Lsif/Generator/Writing/LsifFormat.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing
{
internal enum LsifFormat
{
/// <summary>
/// Line format, where each line is a JSON object.
/// </summary>
Line,
/// <summary>
/// JSON format, where the entire output is a single JSON array.
/// </summary>
Json
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing
{
internal enum LsifFormat
{
/// <summary>
/// Line format, where each line is a JSON object.
/// </summary>
Line,
/// <summary>
/// JSON format, where the entire output is a single JSON array.
/// </summary>
Json
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/CSharp/Portable/Binder/BinderFactory.BinderFactoryVisitor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class BinderFactory
{
private sealed class BinderFactoryVisitor : CSharpSyntaxVisitor<Binder>
{
private int _position;
private CSharpSyntaxNode _memberDeclarationOpt;
private Symbol _memberOpt;
private readonly BinderFactory _factory;
internal BinderFactoryVisitor(BinderFactory factory)
{
_factory = factory;
}
internal void Initialize(int position, CSharpSyntaxNode memberDeclarationOpt, Symbol memberOpt)
{
Debug.Assert((memberDeclarationOpt == null) == (memberOpt == null));
_position = position;
_memberDeclarationOpt = memberDeclarationOpt;
_memberOpt = memberOpt;
}
private CSharpCompilation compilation
{
get
{
return _factory._compilation;
}
}
private SyntaxTree syntaxTree
{
get
{
return _factory._syntaxTree;
}
}
private BuckStopsHereBinder buckStopsHereBinder
{
get
{
return _factory._buckStopsHereBinder;
}
}
private ConcurrentCache<BinderCacheKey, Binder> binderCache
{
get
{
return _factory._binderCache;
}
}
private bool InScript
{
get
{
return _factory.InScript;
}
}
public override Binder DefaultVisit(SyntaxNode parent)
{
return VisitCore(parent.Parent);
}
// node, for which we are trying to find a binder is not supposed to be null
// so we do not need to handle null in the Visit
public override Binder Visit(SyntaxNode node)
{
return VisitCore(node);
}
//PERF: nonvirtual implementation of Visit
private Binder VisitCore(SyntaxNode node)
{
return ((CSharpSyntaxNode)node).Accept(this);
}
public override Binder VisitGlobalStatement(GlobalStatementSyntax node)
{
if (SyntaxFacts.IsSimpleProgramTopLevelStatement(node))
{
var compilationUnit = (CompilationUnitSyntax)node.Parent;
if (compilationUnit != syntaxTree.GetRoot())
{
throw new ArgumentOutOfRangeException(nameof(node), "node not part of tree");
}
var key = CreateBinderCacheKey(compilationUnit, NodeUsage.MethodBody);
Binder result;
if (!binderCache.TryGetValue(key, out result))
{
SynthesizedSimpleProgramEntryPointSymbol simpleProgram = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(compilation, (CompilationUnitSyntax)node.Parent, fallbackToMainEntryPoint: false);
ExecutableCodeBinder bodyBinder = simpleProgram.GetBodyBinder(_factory._ignoreAccessibility);
result = bodyBinder.GetBinder(compilationUnit);
binderCache.TryAdd(key, result);
}
return result;
}
return base.VisitGlobalStatement(node);
}
// This is used mainly by the method body binder. During construction of the method symbol,
// the contexts are built "by hand" rather than by this builder (see
// MethodMemberBuilder.EnsureDeclarationBound).
public override Binder VisitMethodDeclaration(MethodDeclarationSyntax methodDecl)
{
if (!LookupPosition.IsInMethodDeclaration(_position, methodDecl))
{
return VisitCore(methodDecl.Parent);
}
NodeUsage usage;
if (LookupPosition.IsInBody(_position, methodDecl))
{
usage = NodeUsage.MethodBody;
}
else if (LookupPosition.IsInMethodTypeParameterScope(_position, methodDecl))
{
usage = NodeUsage.MethodTypeParameters;
}
else
{
// Normal - is when method itself is not involved (will use outer binder)
// that would be if position is within the return type or method name
usage = NodeUsage.Normal;
}
var key = CreateBinderCacheKey(methodDecl, usage);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
var parentType = methodDecl.Parent as TypeDeclarationSyntax;
if (parentType != null)
{
resultBinder = VisitTypeDeclarationCore(parentType, NodeUsage.NamedTypeBodyOrTypeParameters);
}
else
{
resultBinder = VisitCore(methodDecl.Parent);
}
SourceMemberMethodSymbol method = null;
if (usage != NodeUsage.Normal && methodDecl.TypeParameterList != null)
{
method = GetMethodSymbol(methodDecl, resultBinder);
resultBinder = new WithMethodTypeParametersBinder(method, resultBinder);
}
if (usage == NodeUsage.MethodBody)
{
method = method ?? GetMethodSymbol(methodDecl, resultBinder);
resultBinder = new InMethodBinder(method, resultBinder);
}
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(methodDecl.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
public override Binder VisitConstructorDeclaration(ConstructorDeclarationSyntax parent)
{
// If the position isn't in the scope of the method, then proceed to the parent syntax node.
if (!LookupPosition.IsInMethodDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
bool inBodyOrInitializer = LookupPosition.IsInConstructorParameterScope(_position, parent);
var extraInfo = inBodyOrInitializer ? NodeUsage.ConstructorBodyOrInitializer : NodeUsage.Normal; // extra info for the cache.
var key = CreateBinderCacheKey(parent, extraInfo);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
resultBinder = VisitCore(parent.Parent);
// NOTE: Don't get the method symbol unless we're sure we need it.
if (inBodyOrInitializer)
{
var method = GetMethodSymbol(parent, resultBinder);
if ((object)method != null)
{
// Ctors cannot be generic
//TODO: the error should be given in a different place, but should we ignore or consider the type args?
Debug.Assert(method.Arity == 0, "Generic Ctor, What to do?");
resultBinder = new InMethodBinder(method, resultBinder);
}
}
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(parent.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
public override Binder VisitDestructorDeclaration(DestructorDeclarationSyntax parent)
{
// If the position isn't in the scope of the method, then proceed to the parent syntax node.
if (!LookupPosition.IsInMethodDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
var key = CreateBinderCacheKey(parent, usage: NodeUsage.Normal);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
// Destructors have neither parameters nor type parameters, so there's nothing special to do here.
resultBinder = VisitCore(parent.Parent);
SourceMemberMethodSymbol method = GetMethodSymbol(parent, resultBinder);
resultBinder = new InMethodBinder(method, resultBinder);
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(parent.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
public override Binder VisitAccessorDeclaration(AccessorDeclarationSyntax parent)
{
// If the position isn't in the scope of the method, then proceed to the parent syntax node.
if (!LookupPosition.IsInMethodDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
bool inBody = LookupPosition.IsInBody(_position, parent);
var extraInfo = inBody ? NodeUsage.AccessorBody : NodeUsage.Normal; // extra info for the cache.
var key = CreateBinderCacheKey(parent, extraInfo);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
resultBinder = VisitCore(parent.Parent);
if (inBody)
{
var propertyOrEventDecl = parent.Parent.Parent;
MethodSymbol accessor = null;
switch (propertyOrEventDecl.Kind())
{
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
{
var propertySymbol = GetPropertySymbol((BasePropertyDeclarationSyntax)propertyOrEventDecl, resultBinder);
if ((object)propertySymbol != null)
{
accessor = (parent.Kind() == SyntaxKind.GetAccessorDeclaration) ? propertySymbol.GetMethod : propertySymbol.SetMethod;
}
break;
}
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
{
// NOTE: it's an error for field-like events to have accessors,
// but we want to bind them anyway for error tolerance reasons.
var eventSymbol = GetEventSymbol((EventDeclarationSyntax)propertyOrEventDecl, resultBinder);
if ((object)eventSymbol != null)
{
accessor = (parent.Kind() == SyntaxKind.AddAccessorDeclaration) ? eventSymbol.AddMethod : eventSymbol.RemoveMethod;
}
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(propertyOrEventDecl.Kind());
}
if ((object)accessor != null)
{
resultBinder = new InMethodBinder(accessor, resultBinder);
}
}
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
private Binder VisitOperatorOrConversionDeclaration(BaseMethodDeclarationSyntax parent)
{
// If the position isn't in the scope of the method, then proceed to the parent syntax node.
if (!LookupPosition.IsInMethodDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
bool inBody = LookupPosition.IsInBody(_position, parent);
var extraInfo = inBody ? NodeUsage.OperatorBody : NodeUsage.Normal; // extra info for the cache.
var key = CreateBinderCacheKey(parent, extraInfo);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
resultBinder = VisitCore(parent.Parent);
MethodSymbol method = GetMethodSymbol(parent, resultBinder);
if ((object)method != null && inBody)
{
resultBinder = new InMethodBinder(method, resultBinder);
}
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(parent.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
public override Binder VisitOperatorDeclaration(OperatorDeclarationSyntax parent)
{
return VisitOperatorOrConversionDeclaration(parent);
}
public override Binder VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax parent)
{
return VisitOperatorOrConversionDeclaration(parent);
}
public override Binder VisitFieldDeclaration(FieldDeclarationSyntax parent)
{
return VisitCore(parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers);
}
public override Binder VisitEventDeclaration(EventDeclarationSyntax parent)
{
return VisitCore(parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers);
}
public override Binder VisitEventFieldDeclaration(EventFieldDeclarationSyntax parent)
{
return VisitCore(parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers);
}
public override Binder VisitPropertyDeclaration(PropertyDeclarationSyntax parent)
{
if (!LookupPosition.IsInBody(_position, parent))
{
return VisitCore(parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers);
}
return VisitPropertyOrIndexerExpressionBody(parent);
}
public override Binder VisitIndexerDeclaration(IndexerDeclarationSyntax parent)
{
if (!LookupPosition.IsInBody(_position, parent))
{
return VisitCore(parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers);
}
return VisitPropertyOrIndexerExpressionBody(parent);
}
private Binder VisitPropertyOrIndexerExpressionBody(BasePropertyDeclarationSyntax parent)
{
var key = CreateBinderCacheKey(parent, NodeUsage.AccessorBody);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
resultBinder = VisitCore(parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers);
var propertySymbol = GetPropertySymbol(parent, resultBinder);
var accessor = propertySymbol.GetMethod;
if ((object)accessor != null)
{
resultBinder = new InMethodBinder(accessor, resultBinder);
}
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
private NamedTypeSymbol GetContainerType(Binder binder, CSharpSyntaxNode node)
{
Symbol containingSymbol = binder.ContainingMemberOrLambda;
var container = containingSymbol as NamedTypeSymbol;
if ((object)container == null)
{
Debug.Assert(containingSymbol is NamespaceSymbol);
if (node.Parent.Kind() == SyntaxKind.CompilationUnit && syntaxTree.Options.Kind != SourceCodeKind.Regular)
{
container = compilation.ScriptClass;
}
else
{
container = ((NamespaceSymbol)containingSymbol).ImplicitType;
}
}
return container;
}
/// <summary>
/// Get the name of the method so that it can be looked up in the containing type.
/// </summary>
/// <param name="baseMethodDeclarationSyntax">Non-null declaration syntax.</param>
/// <param name="outerBinder">Binder for the scope around the method (may be null for operators, constructors, and destructors).</param>
private static string GetMethodName(BaseMethodDeclarationSyntax baseMethodDeclarationSyntax, Binder outerBinder)
{
switch (baseMethodDeclarationSyntax.Kind())
{
case SyntaxKind.ConstructorDeclaration:
return (baseMethodDeclarationSyntax.Modifiers.Any(SyntaxKind.StaticKeyword) ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName);
case SyntaxKind.DestructorDeclaration:
return WellKnownMemberNames.DestructorName;
case SyntaxKind.OperatorDeclaration:
var operatorDeclaration = (OperatorDeclarationSyntax)baseMethodDeclarationSyntax;
return ExplicitInterfaceHelpers.GetMemberName(outerBinder, operatorDeclaration.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(operatorDeclaration));
case SyntaxKind.ConversionOperatorDeclaration:
var conversionDeclaration = (ConversionOperatorDeclarationSyntax)baseMethodDeclarationSyntax;
return ExplicitInterfaceHelpers.GetMemberName(outerBinder, conversionDeclaration.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(conversionDeclaration));
case SyntaxKind.MethodDeclaration:
MethodDeclarationSyntax methodDeclSyntax = (MethodDeclarationSyntax)baseMethodDeclarationSyntax;
return ExplicitInterfaceHelpers.GetMemberName(outerBinder, methodDeclSyntax.ExplicitInterfaceSpecifier, methodDeclSyntax.Identifier.ValueText);
default:
throw ExceptionUtilities.UnexpectedValue(baseMethodDeclarationSyntax.Kind());
}
}
/// <summary>
/// Get the name of the property, indexer, or event so that it can be looked up in the containing type.
/// </summary>
/// <param name="basePropertyDeclarationSyntax">Non-null declaration syntax.</param>
/// <param name="outerBinder">Non-null binder for the scope around the member.</param>
private static string GetPropertyOrEventName(BasePropertyDeclarationSyntax basePropertyDeclarationSyntax, Binder outerBinder)
{
ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = basePropertyDeclarationSyntax.ExplicitInterfaceSpecifier;
switch (basePropertyDeclarationSyntax.Kind())
{
case SyntaxKind.PropertyDeclaration:
var propertyDecl = (PropertyDeclarationSyntax)basePropertyDeclarationSyntax;
return ExplicitInterfaceHelpers.GetMemberName(outerBinder, explicitInterfaceSpecifierSyntax, propertyDecl.Identifier.ValueText);
case SyntaxKind.IndexerDeclaration:
return ExplicitInterfaceHelpers.GetMemberName(outerBinder, explicitInterfaceSpecifierSyntax, WellKnownMemberNames.Indexer);
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
var eventDecl = (EventDeclarationSyntax)basePropertyDeclarationSyntax;
return ExplicitInterfaceHelpers.GetMemberName(outerBinder, explicitInterfaceSpecifierSyntax, eventDecl.Identifier.ValueText);
default:
throw ExceptionUtilities.UnexpectedValue(basePropertyDeclarationSyntax.Kind());
}
}
// Get the correct methods symbol within container that corresponds to the given method syntax.
private SourceMemberMethodSymbol GetMethodSymbol(BaseMethodDeclarationSyntax baseMethodDeclarationSyntax, Binder outerBinder)
{
if (baseMethodDeclarationSyntax == _memberDeclarationOpt)
{
return (SourceMemberMethodSymbol)_memberOpt;
}
NamedTypeSymbol container = GetContainerType(outerBinder, baseMethodDeclarationSyntax);
if ((object)container == null)
{
return null;
}
string methodName = GetMethodName(baseMethodDeclarationSyntax, outerBinder);
return (SourceMemberMethodSymbol)GetMemberSymbol(methodName, baseMethodDeclarationSyntax.FullSpan, container, SymbolKind.Method);
}
private SourcePropertySymbol GetPropertySymbol(BasePropertyDeclarationSyntax basePropertyDeclarationSyntax, Binder outerBinder)
{
Debug.Assert(basePropertyDeclarationSyntax.Kind() == SyntaxKind.PropertyDeclaration || basePropertyDeclarationSyntax.Kind() == SyntaxKind.IndexerDeclaration);
if (basePropertyDeclarationSyntax == _memberDeclarationOpt)
{
return (SourcePropertySymbol)_memberOpt;
}
NamedTypeSymbol container = GetContainerType(outerBinder, basePropertyDeclarationSyntax);
if ((object)container == null)
{
return null;
}
string propertyName = GetPropertyOrEventName(basePropertyDeclarationSyntax, outerBinder);
return (SourcePropertySymbol)GetMemberSymbol(propertyName, basePropertyDeclarationSyntax.Span, container, SymbolKind.Property);
}
private SourceEventSymbol GetEventSymbol(EventDeclarationSyntax eventDeclarationSyntax, Binder outerBinder)
{
if (eventDeclarationSyntax == _memberDeclarationOpt)
{
return (SourceEventSymbol)_memberOpt;
}
NamedTypeSymbol container = GetContainerType(outerBinder, eventDeclarationSyntax);
if ((object)container == null)
{
return null;
}
string eventName = GetPropertyOrEventName(eventDeclarationSyntax, outerBinder);
return (SourceEventSymbol)GetMemberSymbol(eventName, eventDeclarationSyntax.Span, container, SymbolKind.Event);
}
private Symbol GetMemberSymbol(string memberName, TextSpan memberSpan, NamedTypeSymbol container, SymbolKind kind)
{
// return container.GetMembers(methodSyntax.Identifier.ValueText).OfType<SourceMethodSymbol>().Single(m => m.Locations.Any(l => l.SourceTree == tree && methodSyntax.Span.Contains(l.SourceSpan)));
foreach (Symbol sym in container.GetMembers(memberName))
{
if (sym.Kind != kind)
{
continue;
}
if (sym.Kind == SymbolKind.Method)
{
if (InSpan(sym.Locations[0], this.syntaxTree, memberSpan))
{
return sym;
}
// If this is a partial method, the method represents the defining part,
// not the implementation (method.Locations includes both parts). If the
// span is in fact in the implementation, return that method instead.
var implementation = ((MethodSymbol)sym).PartialImplementationPart;
if ((object)implementation != null)
{
if (InSpan(implementation.Locations[0], this.syntaxTree, memberSpan))
{
return implementation;
}
}
}
else if (InSpan(sym.Locations, this.syntaxTree, memberSpan))
{
return sym;
}
}
return null;
}
/// <summary>
/// Returns true if the location is within the syntax tree and span.
/// </summary>
private static bool InSpan(Location location, SyntaxTree syntaxTree, TextSpan span)
{
Debug.Assert(syntaxTree != null);
return (location.SourceTree == syntaxTree) && span.Contains(location.SourceSpan);
}
/// <summary>
/// Returns true if one of the locations is within the syntax tree and span.
/// </summary>
private static bool InSpan(ImmutableArray<Location> locations, SyntaxTree syntaxTree, TextSpan span)
{
Debug.Assert(syntaxTree != null);
foreach (var loc in locations)
{
if (InSpan(loc, syntaxTree, span))
{
return true;
}
}
return false;
}
public override Binder VisitDelegateDeclaration(DelegateDeclarationSyntax parent)
{
if (!LookupPosition.IsInDelegateDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
var key = CreateBinderCacheKey(parent, usage: NodeUsage.Normal);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
Binder outer = VisitCore(parent.Parent); // a binder for the body of the enclosing type or namespace
var container = ((NamespaceOrTypeSymbol)outer.ContainingMemberOrLambda).GetSourceTypeMember(parent);
// NOTE: Members of the delegate type are in scope in the entire delegate declaration syntax.
// NOTE: Hence we can assume that we are in body of the delegate type and explicitly insert the InContainerBinder in the binder chain.
resultBinder = new InContainerBinder(container, outer);
if (parent.TypeParameterList != null)
{
resultBinder = new WithClassTypeParametersBinder(container, resultBinder);
}
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(parent.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
public override Binder VisitEnumDeclaration(EnumDeclarationSyntax parent)
{
// This method has nothing to contribute unless the position is actually inside the enum (i.e. not in the declaration part)
bool inBody = LookupPosition.IsBetweenTokens(_position, parent.OpenBraceToken, parent.CloseBraceToken) ||
LookupPosition.IsInAttributeSpecification(_position, parent.AttributeLists);
if (!inBody)
{
return VisitCore(parent.Parent);
}
var key = CreateBinderCacheKey(parent, usage: NodeUsage.Normal);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
Binder outer = VisitCore(parent.Parent); // a binder for the body of the type enclosing this type
var container = ((NamespaceOrTypeSymbol)outer.ContainingMemberOrLambda).GetSourceTypeMember(parent.Identifier.ValueText, 0, SyntaxKind.EnumDeclaration, parent);
resultBinder = new InContainerBinder(container, outer);
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(parent.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
// PERF: do not override VisitTypeDeclaration,
// because C# will not call it and will call least derived one instead
// resulting in unnecessary virtual dispatch
private Binder VisitTypeDeclarationCore(TypeDeclarationSyntax parent)
{
if (!LookupPosition.IsInTypeDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
NodeUsage extraInfo = NodeUsage.Normal;
// we are visiting type declarations fairly frequently
// and position is more likely to be in the body, so lets check for "inBody" first.
if (parent.OpenBraceToken != default &&
parent.CloseBraceToken != default &&
(LookupPosition.IsBetweenTokens(_position, parent.OpenBraceToken, parent.CloseBraceToken) ||
LookupPosition.IsInAttributeSpecification(_position, parent.AttributeLists)))
{
extraInfo = NodeUsage.NamedTypeBodyOrTypeParameters;
}
else if (LookupPosition.IsInTypeParameterList(_position, parent))
{
extraInfo = NodeUsage.NamedTypeBodyOrTypeParameters;
}
else if (LookupPosition.IsBetweenTokens(_position, parent.Keyword, parent.OpenBraceToken))
{
extraInfo = NodeUsage.NamedTypeBaseListOrParameterList;
}
return VisitTypeDeclarationCore(parent, extraInfo);
}
internal Binder VisitTypeDeclarationCore(TypeDeclarationSyntax parent, NodeUsage extraInfo)
{
var key = CreateBinderCacheKey(parent, extraInfo);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
// if node is in the optional type parameter list, then members and type parameters are in scope
// (needed when binding attributes applied to type parameters).
// if node is in the base clause, type parameters are in scope.
// if node is in the body, then members and type parameters are in scope.
// a binder for the body of the type enclosing this type
resultBinder = VisitCore(parent.Parent);
if (extraInfo != NodeUsage.Normal)
{
var typeSymbol = ((NamespaceOrTypeSymbol)resultBinder.ContainingMemberOrLambda).GetSourceTypeMember(parent);
if (extraInfo == NodeUsage.NamedTypeBaseListOrParameterList)
{
// even though there could be no type parameter, we need this binder
// for its "IsAccessible"
resultBinder = new WithClassTypeParametersBinder(typeSymbol, resultBinder);
}
else
{
resultBinder = new InContainerBinder(typeSymbol, resultBinder);
if (parent.TypeParameterList != null)
{
resultBinder = new WithClassTypeParametersBinder(typeSymbol, resultBinder);
}
}
}
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(parent.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
public override Binder VisitClassDeclaration(ClassDeclarationSyntax node)
{
return VisitTypeDeclarationCore(node);
}
public override Binder VisitStructDeclaration(StructDeclarationSyntax node)
{
return VisitTypeDeclarationCore(node);
}
public override Binder VisitInterfaceDeclaration(InterfaceDeclarationSyntax node)
{
return VisitTypeDeclarationCore(node);
}
public override Binder VisitRecordDeclaration(RecordDeclarationSyntax node)
=> VisitTypeDeclarationCore(node);
public sealed override Binder VisitNamespaceDeclaration(NamespaceDeclarationSyntax parent)
{
if (!LookupPosition.IsInNamespaceDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
// test for position equality in case the open brace token is missing:
// namespace X class C { }
bool inBody = LookupPosition.IsBetweenTokens(_position, parent.OpenBraceToken, parent.CloseBraceToken);
bool inUsing = IsInUsing(parent);
return VisitNamespaceDeclaration(parent, _position, inBody, inUsing);
}
public override Binder VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax parent)
{
if (!LookupPosition.IsInNamespaceDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
// Anywhere after the `;` is in the 'body' of this namespace.
bool inBody = _position >= parent.SemicolonToken.EndPosition;
bool inUsing = IsInUsing(parent);
return VisitNamespaceDeclaration(parent, _position, inBody, inUsing);
}
internal Binder VisitNamespaceDeclaration(BaseNamespaceDeclarationSyntax parent, int position, bool inBody, bool inUsing)
{
Debug.Assert(!inUsing || inBody, "inUsing => inBody");
var extraInfo = inUsing ? NodeUsage.NamespaceUsings : (inBody ? NodeUsage.NamespaceBody : NodeUsage.Normal); // extra info for the cache.
var key = CreateBinderCacheKey(parent, extraInfo);
Binder result;
if (!binderCache.TryGetValue(key, out result))
{
Binder outer;
var container = parent.Parent;
if (InScript && container.Kind() == SyntaxKind.CompilationUnit)
{
// Although namespaces are not allowed in script code we still bind them so that we don't report useless errors.
// A namespace in script code is not bound within the scope of a Script class,
// but still within scope of compilation unit extern aliases and usings.
outer = VisitCompilationUnit((CompilationUnitSyntax)container, inUsing: false, inScript: false);
}
else
{
outer = _factory.GetBinder(parent.Parent, position);
}
if (!inBody)
{
// not between the curlies
result = outer;
}
else
{
// if between the curlies, members are in scope
result = MakeNamespaceBinder(parent, parent.Name, outer, inUsing);
}
binderCache.TryAdd(key, result);
}
return result;
}
private static Binder MakeNamespaceBinder(CSharpSyntaxNode node, NameSyntax name, Binder outer, bool inUsing)
{
if (name is QualifiedNameSyntax dotted)
{
outer = MakeNamespaceBinder(dotted.Left, dotted.Left, outer, inUsing: false);
name = dotted.Right;
Debug.Assert(name is not QualifiedNameSyntax);
}
NamespaceOrTypeSymbol container;
if (outer is InContainerBinder inContainerBinder)
{
container = inContainerBinder.Container;
}
else
{
Debug.Assert(outer is SimpleProgramUnitBinder);
container = outer.Compilation.GlobalNamespace;
}
NamespaceSymbol ns = ((NamespaceSymbol)container).GetNestedNamespace(name);
if ((object)ns == null) return outer;
if (node is BaseNamespaceDeclarationSyntax namespaceDecl)
{
outer = AddInImportsBinders((SourceNamespaceSymbol)outer.Compilation.SourceModule.GetModuleNamespace(ns), namespaceDecl, outer, inUsing);
}
else
{
Debug.Assert(!inUsing);
}
return new InContainerBinder(ns, outer);
}
public override Binder VisitCompilationUnit(CompilationUnitSyntax parent)
{
return VisitCompilationUnit(
parent,
inUsing: IsInUsing(parent),
inScript: InScript);
}
internal Binder VisitCompilationUnit(CompilationUnitSyntax compilationUnit, bool inUsing, bool inScript)
{
if (compilationUnit != syntaxTree.GetRoot())
{
throw new ArgumentOutOfRangeException(nameof(compilationUnit), "node not part of tree");
}
var extraInfo = inUsing
? (inScript ? NodeUsage.CompilationUnitScriptUsings : NodeUsage.CompilationUnitUsings)
: (inScript ? NodeUsage.CompilationUnitScript : NodeUsage.Normal); // extra info for the cache.
var key = CreateBinderCacheKey(compilationUnit, extraInfo);
Binder result;
if (!binderCache.TryGetValue(key, out result))
{
result = this.buckStopsHereBinder;
if (inScript)
{
Debug.Assert((object)compilation.ScriptClass != null);
//
// Binder chain in script/interactive code:
//
// + global imports
// + current and previous submission imports (except using aliases)
// + global namespace
// + host object members
// + previous submissions and corresponding using aliases
// + script class members and using aliases
//
bool isSubmissionTree = compilation.IsSubmissionSyntaxTree(compilationUnit.SyntaxTree);
var scriptClass = compilation.ScriptClass;
bool isSubmissionClass = scriptClass.IsSubmissionClass;
if (!inUsing)
{
result = WithUsingNamespacesAndTypesBinder.Create(compilation.GlobalImports, result, withImportChainEntry: true);
if (isSubmissionClass)
{
// NB: Only the non-alias imports are
// ever consumed. Aliases are actually checked in InSubmissionClassBinder (below).
// Note: #loaded trees don't consume previous submission imports.
result = WithUsingNamespacesAndTypesBinder.Create((SourceNamespaceSymbol)compilation.SourceModule.GlobalNamespace, compilationUnit, result,
withPreviousSubmissionImports: compilation.PreviousSubmission != null && isSubmissionTree,
withImportChainEntry: true);
}
}
result = new InContainerBinder(compilation.GlobalNamespace, result);
if (compilation.HostObjectType != null)
{
result = new HostObjectModelBinder(result);
}
if (isSubmissionClass)
{
result = new InSubmissionClassBinder(scriptClass, result, compilationUnit, inUsing);
}
else
{
result = AddInImportsBinders((SourceNamespaceSymbol)compilation.SourceModule.GlobalNamespace, compilationUnit, result, inUsing);
result = new InContainerBinder(scriptClass, result);
}
}
else
{
//
// Binder chain in regular code:
//
// + compilation unit imported namespaces and types
// + compilation unit extern and using aliases
// + global namespace
//
var globalNamespace = compilation.GlobalNamespace;
result = AddInImportsBinders((SourceNamespaceSymbol)compilation.SourceModule.GlobalNamespace, compilationUnit, result, inUsing);
result = new InContainerBinder(globalNamespace, result);
if (!inUsing &&
SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(compilation, compilationUnit, fallbackToMainEntryPoint: true) is SynthesizedSimpleProgramEntryPointSymbol simpleProgram)
{
ExecutableCodeBinder bodyBinder = simpleProgram.GetBodyBinder(_factory._ignoreAccessibility);
result = new SimpleProgramUnitBinder(result, (SimpleProgramBinder)bodyBinder.GetBinder(simpleProgram.SyntaxNode));
}
}
binderCache.TryAdd(key, result);
}
return result;
}
private static Binder AddInImportsBinders(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next, bool inUsing)
{
Debug.Assert(declarationSyntax.Kind() is SyntaxKind.CompilationUnit or SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration);
if (inUsing)
{
// Extern aliases are in scope
return WithExternAliasesBinder.Create(declaringSymbol, declarationSyntax, next);
}
else
{
// All imports are in scope
return WithExternAndUsingAliasesBinder.Create(declaringSymbol, declarationSyntax, WithUsingNamespacesAndTypesBinder.Create(declaringSymbol, declarationSyntax, next));
}
}
internal static BinderCacheKey CreateBinderCacheKey(CSharpSyntaxNode node, NodeUsage usage)
{
Debug.Assert(BitArithmeticUtilities.CountBits((uint)usage) <= 1, "Not a flags enum.");
return new BinderCacheKey(node, usage);
}
/// <summary>
/// Returns true if containingNode has a child that contains the specified position
/// and has kind UsingDirective.
/// </summary>
/// <remarks>
/// Usings can't see other usings, so this is extra info when looking at a namespace
/// or compilation unit scope.
/// </remarks>
private bool IsInUsing(CSharpSyntaxNode containingNode)
{
TextSpan containingSpan = containingNode.Span;
SyntaxToken token;
if (containingNode.Kind() != SyntaxKind.CompilationUnit && _position == containingSpan.End)
{
// This occurs at EOF
token = containingNode.GetLastToken();
Debug.Assert(token == this.syntaxTree.GetRoot().GetLastToken());
}
else if (_position < containingSpan.Start || _position > containingSpan.End) //NB: > not >=
{
return false;
}
else
{
token = containingNode.FindToken(_position);
}
var node = token.Parent;
while (node != null && node != containingNode)
{
// ACASEY: the restriction that we're only interested in children
// of containingNode (vs descendants) seems to be required for cases like
// GetSemanticInfoTests.BindAliasQualifier, which binds an alias name
// within a using directive.
if (node.IsKind(SyntaxKind.UsingDirective) && node.Parent == containingNode)
{
return true;
}
node = node.Parent;
}
return false;
}
public override Binder VisitDocumentationCommentTrivia(DocumentationCommentTriviaSyntax parent)
{
// Need to step across the structured trivia boundary explicitly - can't just follow Parent references.
return VisitCore(parent.ParentTrivia.Token.Parent);
}
/// <remarks>
/// Used to detect whether we are in a cref parameter type.
/// </remarks>
public override Binder VisitCrefParameter(CrefParameterSyntax parent)
{
XmlCrefAttributeSyntax containingAttribute = parent.FirstAncestorOrSelf<XmlCrefAttributeSyntax>(ascendOutOfTrivia: false);
return VisitXmlCrefAttributeInternal(containingAttribute, NodeUsage.CrefParameterOrReturnType);
}
/// <remarks>
/// Used to detect whether we are in a cref return type.
/// </remarks>
public override Binder VisitConversionOperatorMemberCref(ConversionOperatorMemberCrefSyntax parent)
{
if (parent.Type.Span.Contains(_position))
{
XmlCrefAttributeSyntax containingAttribute = parent.FirstAncestorOrSelf<XmlCrefAttributeSyntax>(ascendOutOfTrivia: false);
return VisitXmlCrefAttributeInternal(containingAttribute, NodeUsage.CrefParameterOrReturnType);
}
return base.VisitConversionOperatorMemberCref(parent);
}
public override Binder VisitXmlCrefAttribute(XmlCrefAttributeSyntax parent)
{
if (!LookupPosition.IsInXmlAttributeValue(_position, parent))
{
return VisitCore(parent.Parent);
}
var extraInfo = NodeUsage.Normal; // extra info for the cache.
return VisitXmlCrefAttributeInternal(parent, extraInfo);
}
private Binder VisitXmlCrefAttributeInternal(XmlCrefAttributeSyntax parent, NodeUsage extraInfo)
{
Debug.Assert(extraInfo == NodeUsage.Normal || extraInfo == NodeUsage.CrefParameterOrReturnType,
"Unexpected extraInfo " + extraInfo);
var key = CreateBinderCacheKey(parent, extraInfo);
Binder result;
if (!binderCache.TryGetValue(key, out result))
{
CrefSyntax crefSyntax = parent.Cref;
MemberDeclarationSyntax memberSyntax = GetAssociatedMemberForXmlSyntax(parent);
bool inParameterOrReturnType = extraInfo == NodeUsage.CrefParameterOrReturnType;
result = (object)memberSyntax == null
? MakeCrefBinderInternal(crefSyntax, VisitCore(parent.Parent), inParameterOrReturnType)
: MakeCrefBinder(crefSyntax, memberSyntax, _factory, inParameterOrReturnType);
binderCache.TryAdd(key, result);
}
return result;
}
public override Binder VisitXmlNameAttribute(XmlNameAttributeSyntax parent)
{
if (!LookupPosition.IsInXmlAttributeValue(_position, parent))
{
return VisitCore(parent.Parent);
}
XmlNameAttributeElementKind elementKind = parent.GetElementKind();
NodeUsage extraInfo;
switch (elementKind)
{
case XmlNameAttributeElementKind.Parameter:
case XmlNameAttributeElementKind.ParameterReference:
extraInfo = NodeUsage.DocumentationCommentParameter;
break;
case XmlNameAttributeElementKind.TypeParameter:
extraInfo = NodeUsage.DocumentationCommentTypeParameter;
break;
case XmlNameAttributeElementKind.TypeParameterReference:
extraInfo = NodeUsage.DocumentationCommentTypeParameterReference;
break;
default:
throw ExceptionUtilities.UnexpectedValue(elementKind);
}
// Cleverness: rather than using this node as the key, we're going to use the
// enclosing doc comment, because all name attributes with the same element
// kind, in the same doc comment can share the same binder.
var key = CreateBinderCacheKey(GetEnclosingDocumentationComment(parent), extraInfo);
Binder result;
if (!binderCache.TryGetValue(key, out result))
{
result = this.buckStopsHereBinder;
Binder outerBinder = VisitCore(GetEnclosingDocumentationComment(parent));
if ((object)outerBinder != null)
{
// The rest of the doc comment is going to report something for containing symbol -
// that shouldn't change just because we're in a name attribute.
result = result.WithContainingMemberOrLambda(outerBinder.ContainingMemberOrLambda);
}
MemberDeclarationSyntax memberSyntax = GetAssociatedMemberForXmlSyntax(parent);
if ((object)memberSyntax != null)
{
switch (elementKind)
{
case XmlNameAttributeElementKind.Parameter:
case XmlNameAttributeElementKind.ParameterReference:
result = GetParameterNameAttributeValueBinder(memberSyntax, result);
break;
case XmlNameAttributeElementKind.TypeParameter:
result = GetTypeParameterNameAttributeValueBinder(memberSyntax, includeContainingSymbols: false, nextBinder: result);
break;
case XmlNameAttributeElementKind.TypeParameterReference:
result = GetTypeParameterNameAttributeValueBinder(memberSyntax, includeContainingSymbols: true, nextBinder: result);
break;
}
}
binderCache.TryAdd(key, result);
}
return result;
}
/// <summary>
/// We're in a <param> or <paramref> element, so we want a binder that can see
/// the parameters of the associated member and nothing else.
/// </summary>
private Binder GetParameterNameAttributeValueBinder(MemberDeclarationSyntax memberSyntax, Binder nextBinder)
{
if (memberSyntax is BaseMethodDeclarationSyntax { ParameterList: { ParameterCount: > 0 } } baseMethodDeclSyntax)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
MethodSymbol method = GetMethodSymbol(baseMethodDeclSyntax, outerBinder);
return new WithParametersBinder(method.Parameters, nextBinder);
}
if (memberSyntax is RecordDeclarationSyntax { ParameterList: { ParameterCount: > 0 } })
{
Binder outerBinder = VisitCore(memberSyntax);
SourceNamedTypeSymbol recordType = ((NamespaceOrTypeSymbol)outerBinder.ContainingMemberOrLambda).GetSourceTypeMember((TypeDeclarationSyntax)memberSyntax);
var primaryConstructor = recordType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().SingleOrDefault();
if (primaryConstructor.SyntaxRef.SyntaxTree == memberSyntax.SyntaxTree &&
primaryConstructor.GetSyntax() == memberSyntax)
{
return new WithParametersBinder(primaryConstructor.Parameters, nextBinder);
}
}
// As in Dev11, we do not allow <param name="value"> on events.
SyntaxKind memberKind = memberSyntax.Kind();
if (memberKind == SyntaxKind.PropertyDeclaration || memberKind == SyntaxKind.IndexerDeclaration)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
BasePropertyDeclarationSyntax propertyDeclSyntax = (BasePropertyDeclarationSyntax)memberSyntax;
PropertySymbol property = GetPropertySymbol(propertyDeclSyntax, outerBinder);
ImmutableArray<ParameterSymbol> parameters = property.Parameters;
// BREAK: Dev11 also allows "value" for readonly properties, but that doesn't
// make sense and we don't have a symbol.
if ((object)property.SetMethod != null)
{
Debug.Assert(property.SetMethod.ParameterCount > 0);
parameters = parameters.Add(property.SetMethod.Parameters.Last());
}
if (parameters.Any())
{
return new WithParametersBinder(parameters, nextBinder);
}
}
else if (memberKind == SyntaxKind.DelegateDeclaration)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
SourceNamedTypeSymbol delegateType = ((NamespaceOrTypeSymbol)outerBinder.ContainingMemberOrLambda).GetSourceTypeMember((DelegateDeclarationSyntax)memberSyntax);
Debug.Assert((object)delegateType != null);
MethodSymbol invokeMethod = delegateType.DelegateInvokeMethod;
Debug.Assert((object)invokeMethod != null);
ImmutableArray<ParameterSymbol> parameters = invokeMethod.Parameters;
if (parameters.Any())
{
return new WithParametersBinder(parameters, nextBinder);
}
}
return nextBinder;
}
/// <summary>
/// We're in a <typeparam> or <typeparamref> element, so we want a binder that can see
/// the type parameters of the associated member and nothing else.
/// </summary>
private Binder GetTypeParameterNameAttributeValueBinder(MemberDeclarationSyntax memberSyntax, bool includeContainingSymbols, Binder nextBinder)
{
if (includeContainingSymbols)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
for (NamedTypeSymbol curr = outerBinder.ContainingType; (object)curr != null; curr = curr.ContainingType)
{
if (curr.Arity > 0)
{
nextBinder = new WithClassTypeParametersBinder(curr, nextBinder);
}
}
}
// NOTE: don't care about enums, since they don't have type parameters.
TypeDeclarationSyntax typeDeclSyntax = memberSyntax as TypeDeclarationSyntax;
if ((object)typeDeclSyntax != null && typeDeclSyntax.Arity > 0)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
SourceNamedTypeSymbol typeSymbol = ((NamespaceOrTypeSymbol)outerBinder.ContainingMemberOrLambda).GetSourceTypeMember(typeDeclSyntax);
// NOTE: don't include anything else in the binder chain.
return new WithClassTypeParametersBinder(typeSymbol, nextBinder);
}
if (memberSyntax.Kind() == SyntaxKind.MethodDeclaration)
{
MethodDeclarationSyntax methodDeclSyntax = (MethodDeclarationSyntax)memberSyntax;
if (methodDeclSyntax.Arity > 0)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
MethodSymbol method = GetMethodSymbol(methodDeclSyntax, outerBinder);
return new WithMethodTypeParametersBinder(method, nextBinder);
}
}
else if (memberSyntax.Kind() == SyntaxKind.DelegateDeclaration)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
SourceNamedTypeSymbol delegateType = ((NamespaceOrTypeSymbol)outerBinder.ContainingMemberOrLambda).GetSourceTypeMember((DelegateDeclarationSyntax)memberSyntax);
ImmutableArray<TypeParameterSymbol> typeParameters = delegateType.TypeParameters;
if (typeParameters.Any())
{
return new WithClassTypeParametersBinder(delegateType, nextBinder);
}
}
return nextBinder;
}
}
#region In outer type - BinderFactory
/// <summary>
/// Given a CrefSyntax and an associated member declaration syntax node,
/// construct an appropriate binder for binding the cref.
/// </summary>
/// <param name="crefSyntax">Cref that will be bound.</param>
/// <param name="memberSyntax">The member to which the documentation comment (logically) containing
/// the cref syntax applies.</param>
/// <param name="factory">Corresponding binder factory.</param>
/// <param name="inParameterOrReturnType">True to get a special binder for cref parameter and return types.</param>
/// <remarks>
/// The CrefSyntax does not actually have to be within the documentation comment on the member - it
/// could be included from another file.
/// </remarks>
internal static Binder MakeCrefBinder(CrefSyntax crefSyntax, MemberDeclarationSyntax memberSyntax, BinderFactory factory, bool inParameterOrReturnType = false)
{
Debug.Assert(crefSyntax != null);
Debug.Assert(memberSyntax != null);
Binder binder = memberSyntax is BaseTypeDeclarationSyntax typeDeclSyntax
? getBinder(typeDeclSyntax)
: factory.GetBinder(memberSyntax);
return MakeCrefBinderInternal(crefSyntax, binder, inParameterOrReturnType);
Binder getBinder(BaseTypeDeclarationSyntax baseTypeDeclaration)
{
if (baseTypeDeclaration is RecordDeclarationSyntax { SemicolonToken: { RawKind: (int)SyntaxKind.SemicolonToken } } recordDeclaration)
{
return factory.GetInRecordBodyBinder(recordDeclaration);
}
return factory.GetBinder(baseTypeDeclaration, baseTypeDeclaration.OpenBraceToken.SpanStart);
}
}
/// <summary>
/// Internal version of MakeCrefBinder that allows the caller to explicitly set the underlying binder.
/// </summary>
private static Binder MakeCrefBinderInternal(CrefSyntax crefSyntax, Binder binder, bool inParameterOrReturnType)
{
// After much deliberation, we eventually decided to suppress lookup of inherited members within
// crefs, in order to match dev11's behavior (Changeset #829014). Unfortunately, it turns out
// that dev11 does not suppress these members when performing lookup within parameter and return
// types, within crefs (DevDiv #586815, #598371).
// NOTE: always allow pointer types.
BinderFlags flags = BinderFlags.Cref | BinderFlags.SuppressConstraintChecks | BinderFlags.UnsafeRegion;
if (inParameterOrReturnType)
{
flags |= BinderFlags.CrefParameterOrReturnType;
}
binder = binder.WithAdditionalFlags(flags);
binder = new WithCrefTypeParametersBinder(crefSyntax, binder);
return binder;
}
internal static MemberDeclarationSyntax GetAssociatedMemberForXmlSyntax(CSharpSyntaxNode xmlSyntax)
{
Debug.Assert(xmlSyntax is XmlAttributeSyntax || xmlSyntax.Kind() == SyntaxKind.XmlEmptyElement || xmlSyntax.Kind() == SyntaxKind.XmlElementStartTag);
StructuredTriviaSyntax structuredTrivia = GetEnclosingDocumentationComment(xmlSyntax);
SyntaxTrivia containingTrivia = structuredTrivia.ParentTrivia;
SyntaxToken associatedToken = (SyntaxToken)containingTrivia.Token;
CSharpSyntaxNode curr = (CSharpSyntaxNode)associatedToken.Parent;
while (curr != null)
{
MemberDeclarationSyntax memberSyntax = curr as MemberDeclarationSyntax;
if (memberSyntax != null)
{
// CONSIDER: require that the xml syntax precede the start of the member span?
return memberSyntax;
}
curr = curr.Parent;
}
return null;
}
/// <summary>
/// Walk up from an XML syntax node (attribute or tag) to the enclosing documentation comment trivia.
/// </summary>
private static DocumentationCommentTriviaSyntax GetEnclosingDocumentationComment(CSharpSyntaxNode xmlSyntax)
{
CSharpSyntaxNode curr = xmlSyntax;
for (; !SyntaxFacts.IsDocumentationCommentTrivia(curr.Kind()); curr = curr.Parent)
{
}
Debug.Assert(curr != null);
return (DocumentationCommentTriviaSyntax)curr;
}
#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.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class BinderFactory
{
private sealed class BinderFactoryVisitor : CSharpSyntaxVisitor<Binder>
{
private int _position;
private CSharpSyntaxNode _memberDeclarationOpt;
private Symbol _memberOpt;
private readonly BinderFactory _factory;
internal BinderFactoryVisitor(BinderFactory factory)
{
_factory = factory;
}
internal void Initialize(int position, CSharpSyntaxNode memberDeclarationOpt, Symbol memberOpt)
{
Debug.Assert((memberDeclarationOpt == null) == (memberOpt == null));
_position = position;
_memberDeclarationOpt = memberDeclarationOpt;
_memberOpt = memberOpt;
}
private CSharpCompilation compilation
{
get
{
return _factory._compilation;
}
}
private SyntaxTree syntaxTree
{
get
{
return _factory._syntaxTree;
}
}
private BuckStopsHereBinder buckStopsHereBinder
{
get
{
return _factory._buckStopsHereBinder;
}
}
private ConcurrentCache<BinderCacheKey, Binder> binderCache
{
get
{
return _factory._binderCache;
}
}
private bool InScript
{
get
{
return _factory.InScript;
}
}
public override Binder DefaultVisit(SyntaxNode parent)
{
return VisitCore(parent.Parent);
}
// node, for which we are trying to find a binder is not supposed to be null
// so we do not need to handle null in the Visit
public override Binder Visit(SyntaxNode node)
{
return VisitCore(node);
}
//PERF: nonvirtual implementation of Visit
private Binder VisitCore(SyntaxNode node)
{
return ((CSharpSyntaxNode)node).Accept(this);
}
public override Binder VisitGlobalStatement(GlobalStatementSyntax node)
{
if (SyntaxFacts.IsSimpleProgramTopLevelStatement(node))
{
var compilationUnit = (CompilationUnitSyntax)node.Parent;
if (compilationUnit != syntaxTree.GetRoot())
{
throw new ArgumentOutOfRangeException(nameof(node), "node not part of tree");
}
var key = CreateBinderCacheKey(compilationUnit, NodeUsage.MethodBody);
Binder result;
if (!binderCache.TryGetValue(key, out result))
{
SynthesizedSimpleProgramEntryPointSymbol simpleProgram = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(compilation, (CompilationUnitSyntax)node.Parent, fallbackToMainEntryPoint: false);
ExecutableCodeBinder bodyBinder = simpleProgram.GetBodyBinder(_factory._ignoreAccessibility);
result = bodyBinder.GetBinder(compilationUnit);
binderCache.TryAdd(key, result);
}
return result;
}
return base.VisitGlobalStatement(node);
}
// This is used mainly by the method body binder. During construction of the method symbol,
// the contexts are built "by hand" rather than by this builder (see
// MethodMemberBuilder.EnsureDeclarationBound).
public override Binder VisitMethodDeclaration(MethodDeclarationSyntax methodDecl)
{
if (!LookupPosition.IsInMethodDeclaration(_position, methodDecl))
{
return VisitCore(methodDecl.Parent);
}
NodeUsage usage;
if (LookupPosition.IsInBody(_position, methodDecl))
{
usage = NodeUsage.MethodBody;
}
else if (LookupPosition.IsInMethodTypeParameterScope(_position, methodDecl))
{
usage = NodeUsage.MethodTypeParameters;
}
else
{
// Normal - is when method itself is not involved (will use outer binder)
// that would be if position is within the return type or method name
usage = NodeUsage.Normal;
}
var key = CreateBinderCacheKey(methodDecl, usage);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
var parentType = methodDecl.Parent as TypeDeclarationSyntax;
if (parentType != null)
{
resultBinder = VisitTypeDeclarationCore(parentType, NodeUsage.NamedTypeBodyOrTypeParameters);
}
else
{
resultBinder = VisitCore(methodDecl.Parent);
}
SourceMemberMethodSymbol method = null;
if (usage != NodeUsage.Normal && methodDecl.TypeParameterList != null)
{
method = GetMethodSymbol(methodDecl, resultBinder);
resultBinder = new WithMethodTypeParametersBinder(method, resultBinder);
}
if (usage == NodeUsage.MethodBody)
{
method = method ?? GetMethodSymbol(methodDecl, resultBinder);
resultBinder = new InMethodBinder(method, resultBinder);
}
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(methodDecl.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
public override Binder VisitConstructorDeclaration(ConstructorDeclarationSyntax parent)
{
// If the position isn't in the scope of the method, then proceed to the parent syntax node.
if (!LookupPosition.IsInMethodDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
bool inBodyOrInitializer = LookupPosition.IsInConstructorParameterScope(_position, parent);
var extraInfo = inBodyOrInitializer ? NodeUsage.ConstructorBodyOrInitializer : NodeUsage.Normal; // extra info for the cache.
var key = CreateBinderCacheKey(parent, extraInfo);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
resultBinder = VisitCore(parent.Parent);
// NOTE: Don't get the method symbol unless we're sure we need it.
if (inBodyOrInitializer)
{
var method = GetMethodSymbol(parent, resultBinder);
if ((object)method != null)
{
// Ctors cannot be generic
//TODO: the error should be given in a different place, but should we ignore or consider the type args?
Debug.Assert(method.Arity == 0, "Generic Ctor, What to do?");
resultBinder = new InMethodBinder(method, resultBinder);
}
}
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(parent.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
public override Binder VisitDestructorDeclaration(DestructorDeclarationSyntax parent)
{
// If the position isn't in the scope of the method, then proceed to the parent syntax node.
if (!LookupPosition.IsInMethodDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
var key = CreateBinderCacheKey(parent, usage: NodeUsage.Normal);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
// Destructors have neither parameters nor type parameters, so there's nothing special to do here.
resultBinder = VisitCore(parent.Parent);
SourceMemberMethodSymbol method = GetMethodSymbol(parent, resultBinder);
resultBinder = new InMethodBinder(method, resultBinder);
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(parent.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
public override Binder VisitAccessorDeclaration(AccessorDeclarationSyntax parent)
{
// If the position isn't in the scope of the method, then proceed to the parent syntax node.
if (!LookupPosition.IsInMethodDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
bool inBody = LookupPosition.IsInBody(_position, parent);
var extraInfo = inBody ? NodeUsage.AccessorBody : NodeUsage.Normal; // extra info for the cache.
var key = CreateBinderCacheKey(parent, extraInfo);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
resultBinder = VisitCore(parent.Parent);
if (inBody)
{
var propertyOrEventDecl = parent.Parent.Parent;
MethodSymbol accessor = null;
switch (propertyOrEventDecl.Kind())
{
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
{
var propertySymbol = GetPropertySymbol((BasePropertyDeclarationSyntax)propertyOrEventDecl, resultBinder);
if ((object)propertySymbol != null)
{
accessor = (parent.Kind() == SyntaxKind.GetAccessorDeclaration) ? propertySymbol.GetMethod : propertySymbol.SetMethod;
}
break;
}
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
{
// NOTE: it's an error for field-like events to have accessors,
// but we want to bind them anyway for error tolerance reasons.
var eventSymbol = GetEventSymbol((EventDeclarationSyntax)propertyOrEventDecl, resultBinder);
if ((object)eventSymbol != null)
{
accessor = (parent.Kind() == SyntaxKind.AddAccessorDeclaration) ? eventSymbol.AddMethod : eventSymbol.RemoveMethod;
}
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(propertyOrEventDecl.Kind());
}
if ((object)accessor != null)
{
resultBinder = new InMethodBinder(accessor, resultBinder);
}
}
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
private Binder VisitOperatorOrConversionDeclaration(BaseMethodDeclarationSyntax parent)
{
// If the position isn't in the scope of the method, then proceed to the parent syntax node.
if (!LookupPosition.IsInMethodDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
bool inBody = LookupPosition.IsInBody(_position, parent);
var extraInfo = inBody ? NodeUsage.OperatorBody : NodeUsage.Normal; // extra info for the cache.
var key = CreateBinderCacheKey(parent, extraInfo);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
resultBinder = VisitCore(parent.Parent);
MethodSymbol method = GetMethodSymbol(parent, resultBinder);
if ((object)method != null && inBody)
{
resultBinder = new InMethodBinder(method, resultBinder);
}
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(parent.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
public override Binder VisitOperatorDeclaration(OperatorDeclarationSyntax parent)
{
return VisitOperatorOrConversionDeclaration(parent);
}
public override Binder VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax parent)
{
return VisitOperatorOrConversionDeclaration(parent);
}
public override Binder VisitFieldDeclaration(FieldDeclarationSyntax parent)
{
return VisitCore(parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers);
}
public override Binder VisitEventDeclaration(EventDeclarationSyntax parent)
{
return VisitCore(parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers);
}
public override Binder VisitEventFieldDeclaration(EventFieldDeclarationSyntax parent)
{
return VisitCore(parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers);
}
public override Binder VisitPropertyDeclaration(PropertyDeclarationSyntax parent)
{
if (!LookupPosition.IsInBody(_position, parent))
{
return VisitCore(parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers);
}
return VisitPropertyOrIndexerExpressionBody(parent);
}
public override Binder VisitIndexerDeclaration(IndexerDeclarationSyntax parent)
{
if (!LookupPosition.IsInBody(_position, parent))
{
return VisitCore(parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers);
}
return VisitPropertyOrIndexerExpressionBody(parent);
}
private Binder VisitPropertyOrIndexerExpressionBody(BasePropertyDeclarationSyntax parent)
{
var key = CreateBinderCacheKey(parent, NodeUsage.AccessorBody);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
resultBinder = VisitCore(parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers);
var propertySymbol = GetPropertySymbol(parent, resultBinder);
var accessor = propertySymbol.GetMethod;
if ((object)accessor != null)
{
resultBinder = new InMethodBinder(accessor, resultBinder);
}
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
private NamedTypeSymbol GetContainerType(Binder binder, CSharpSyntaxNode node)
{
Symbol containingSymbol = binder.ContainingMemberOrLambda;
var container = containingSymbol as NamedTypeSymbol;
if ((object)container == null)
{
Debug.Assert(containingSymbol is NamespaceSymbol);
if (node.Parent.Kind() == SyntaxKind.CompilationUnit && syntaxTree.Options.Kind != SourceCodeKind.Regular)
{
container = compilation.ScriptClass;
}
else
{
container = ((NamespaceSymbol)containingSymbol).ImplicitType;
}
}
return container;
}
/// <summary>
/// Get the name of the method so that it can be looked up in the containing type.
/// </summary>
/// <param name="baseMethodDeclarationSyntax">Non-null declaration syntax.</param>
/// <param name="outerBinder">Binder for the scope around the method (may be null for operators, constructors, and destructors).</param>
private static string GetMethodName(BaseMethodDeclarationSyntax baseMethodDeclarationSyntax, Binder outerBinder)
{
switch (baseMethodDeclarationSyntax.Kind())
{
case SyntaxKind.ConstructorDeclaration:
return (baseMethodDeclarationSyntax.Modifiers.Any(SyntaxKind.StaticKeyword) ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName);
case SyntaxKind.DestructorDeclaration:
return WellKnownMemberNames.DestructorName;
case SyntaxKind.OperatorDeclaration:
var operatorDeclaration = (OperatorDeclarationSyntax)baseMethodDeclarationSyntax;
return ExplicitInterfaceHelpers.GetMemberName(outerBinder, operatorDeclaration.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(operatorDeclaration));
case SyntaxKind.ConversionOperatorDeclaration:
var conversionDeclaration = (ConversionOperatorDeclarationSyntax)baseMethodDeclarationSyntax;
return ExplicitInterfaceHelpers.GetMemberName(outerBinder, conversionDeclaration.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(conversionDeclaration));
case SyntaxKind.MethodDeclaration:
MethodDeclarationSyntax methodDeclSyntax = (MethodDeclarationSyntax)baseMethodDeclarationSyntax;
return ExplicitInterfaceHelpers.GetMemberName(outerBinder, methodDeclSyntax.ExplicitInterfaceSpecifier, methodDeclSyntax.Identifier.ValueText);
default:
throw ExceptionUtilities.UnexpectedValue(baseMethodDeclarationSyntax.Kind());
}
}
/// <summary>
/// Get the name of the property, indexer, or event so that it can be looked up in the containing type.
/// </summary>
/// <param name="basePropertyDeclarationSyntax">Non-null declaration syntax.</param>
/// <param name="outerBinder">Non-null binder for the scope around the member.</param>
private static string GetPropertyOrEventName(BasePropertyDeclarationSyntax basePropertyDeclarationSyntax, Binder outerBinder)
{
ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = basePropertyDeclarationSyntax.ExplicitInterfaceSpecifier;
switch (basePropertyDeclarationSyntax.Kind())
{
case SyntaxKind.PropertyDeclaration:
var propertyDecl = (PropertyDeclarationSyntax)basePropertyDeclarationSyntax;
return ExplicitInterfaceHelpers.GetMemberName(outerBinder, explicitInterfaceSpecifierSyntax, propertyDecl.Identifier.ValueText);
case SyntaxKind.IndexerDeclaration:
return ExplicitInterfaceHelpers.GetMemberName(outerBinder, explicitInterfaceSpecifierSyntax, WellKnownMemberNames.Indexer);
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
var eventDecl = (EventDeclarationSyntax)basePropertyDeclarationSyntax;
return ExplicitInterfaceHelpers.GetMemberName(outerBinder, explicitInterfaceSpecifierSyntax, eventDecl.Identifier.ValueText);
default:
throw ExceptionUtilities.UnexpectedValue(basePropertyDeclarationSyntax.Kind());
}
}
// Get the correct methods symbol within container that corresponds to the given method syntax.
private SourceMemberMethodSymbol GetMethodSymbol(BaseMethodDeclarationSyntax baseMethodDeclarationSyntax, Binder outerBinder)
{
if (baseMethodDeclarationSyntax == _memberDeclarationOpt)
{
return (SourceMemberMethodSymbol)_memberOpt;
}
NamedTypeSymbol container = GetContainerType(outerBinder, baseMethodDeclarationSyntax);
if ((object)container == null)
{
return null;
}
string methodName = GetMethodName(baseMethodDeclarationSyntax, outerBinder);
return (SourceMemberMethodSymbol)GetMemberSymbol(methodName, baseMethodDeclarationSyntax.FullSpan, container, SymbolKind.Method);
}
private SourcePropertySymbol GetPropertySymbol(BasePropertyDeclarationSyntax basePropertyDeclarationSyntax, Binder outerBinder)
{
Debug.Assert(basePropertyDeclarationSyntax.Kind() == SyntaxKind.PropertyDeclaration || basePropertyDeclarationSyntax.Kind() == SyntaxKind.IndexerDeclaration);
if (basePropertyDeclarationSyntax == _memberDeclarationOpt)
{
return (SourcePropertySymbol)_memberOpt;
}
NamedTypeSymbol container = GetContainerType(outerBinder, basePropertyDeclarationSyntax);
if ((object)container == null)
{
return null;
}
string propertyName = GetPropertyOrEventName(basePropertyDeclarationSyntax, outerBinder);
return (SourcePropertySymbol)GetMemberSymbol(propertyName, basePropertyDeclarationSyntax.Span, container, SymbolKind.Property);
}
private SourceEventSymbol GetEventSymbol(EventDeclarationSyntax eventDeclarationSyntax, Binder outerBinder)
{
if (eventDeclarationSyntax == _memberDeclarationOpt)
{
return (SourceEventSymbol)_memberOpt;
}
NamedTypeSymbol container = GetContainerType(outerBinder, eventDeclarationSyntax);
if ((object)container == null)
{
return null;
}
string eventName = GetPropertyOrEventName(eventDeclarationSyntax, outerBinder);
return (SourceEventSymbol)GetMemberSymbol(eventName, eventDeclarationSyntax.Span, container, SymbolKind.Event);
}
private Symbol GetMemberSymbol(string memberName, TextSpan memberSpan, NamedTypeSymbol container, SymbolKind kind)
{
// return container.GetMembers(methodSyntax.Identifier.ValueText).OfType<SourceMethodSymbol>().Single(m => m.Locations.Any(l => l.SourceTree == tree && methodSyntax.Span.Contains(l.SourceSpan)));
foreach (Symbol sym in container.GetMembers(memberName))
{
if (sym.Kind != kind)
{
continue;
}
if (sym.Kind == SymbolKind.Method)
{
if (InSpan(sym.Locations[0], this.syntaxTree, memberSpan))
{
return sym;
}
// If this is a partial method, the method represents the defining part,
// not the implementation (method.Locations includes both parts). If the
// span is in fact in the implementation, return that method instead.
var implementation = ((MethodSymbol)sym).PartialImplementationPart;
if ((object)implementation != null)
{
if (InSpan(implementation.Locations[0], this.syntaxTree, memberSpan))
{
return implementation;
}
}
}
else if (InSpan(sym.Locations, this.syntaxTree, memberSpan))
{
return sym;
}
}
return null;
}
/// <summary>
/// Returns true if the location is within the syntax tree and span.
/// </summary>
private static bool InSpan(Location location, SyntaxTree syntaxTree, TextSpan span)
{
Debug.Assert(syntaxTree != null);
return (location.SourceTree == syntaxTree) && span.Contains(location.SourceSpan);
}
/// <summary>
/// Returns true if one of the locations is within the syntax tree and span.
/// </summary>
private static bool InSpan(ImmutableArray<Location> locations, SyntaxTree syntaxTree, TextSpan span)
{
Debug.Assert(syntaxTree != null);
foreach (var loc in locations)
{
if (InSpan(loc, syntaxTree, span))
{
return true;
}
}
return false;
}
public override Binder VisitDelegateDeclaration(DelegateDeclarationSyntax parent)
{
if (!LookupPosition.IsInDelegateDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
var key = CreateBinderCacheKey(parent, usage: NodeUsage.Normal);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
Binder outer = VisitCore(parent.Parent); // a binder for the body of the enclosing type or namespace
var container = ((NamespaceOrTypeSymbol)outer.ContainingMemberOrLambda).GetSourceTypeMember(parent);
// NOTE: Members of the delegate type are in scope in the entire delegate declaration syntax.
// NOTE: Hence we can assume that we are in body of the delegate type and explicitly insert the InContainerBinder in the binder chain.
resultBinder = new InContainerBinder(container, outer);
if (parent.TypeParameterList != null)
{
resultBinder = new WithClassTypeParametersBinder(container, resultBinder);
}
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(parent.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
public override Binder VisitEnumDeclaration(EnumDeclarationSyntax parent)
{
// This method has nothing to contribute unless the position is actually inside the enum (i.e. not in the declaration part)
bool inBody = LookupPosition.IsBetweenTokens(_position, parent.OpenBraceToken, parent.CloseBraceToken) ||
LookupPosition.IsInAttributeSpecification(_position, parent.AttributeLists);
if (!inBody)
{
return VisitCore(parent.Parent);
}
var key = CreateBinderCacheKey(parent, usage: NodeUsage.Normal);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
Binder outer = VisitCore(parent.Parent); // a binder for the body of the type enclosing this type
var container = ((NamespaceOrTypeSymbol)outer.ContainingMemberOrLambda).GetSourceTypeMember(parent.Identifier.ValueText, 0, SyntaxKind.EnumDeclaration, parent);
resultBinder = new InContainerBinder(container, outer);
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(parent.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
// PERF: do not override VisitTypeDeclaration,
// because C# will not call it and will call least derived one instead
// resulting in unnecessary virtual dispatch
private Binder VisitTypeDeclarationCore(TypeDeclarationSyntax parent)
{
if (!LookupPosition.IsInTypeDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
NodeUsage extraInfo = NodeUsage.Normal;
// we are visiting type declarations fairly frequently
// and position is more likely to be in the body, so lets check for "inBody" first.
if (parent.OpenBraceToken != default &&
parent.CloseBraceToken != default &&
(LookupPosition.IsBetweenTokens(_position, parent.OpenBraceToken, parent.CloseBraceToken) ||
LookupPosition.IsInAttributeSpecification(_position, parent.AttributeLists)))
{
extraInfo = NodeUsage.NamedTypeBodyOrTypeParameters;
}
else if (LookupPosition.IsInTypeParameterList(_position, parent))
{
extraInfo = NodeUsage.NamedTypeBodyOrTypeParameters;
}
else if (LookupPosition.IsBetweenTokens(_position, parent.Keyword, parent.OpenBraceToken))
{
extraInfo = NodeUsage.NamedTypeBaseListOrParameterList;
}
return VisitTypeDeclarationCore(parent, extraInfo);
}
internal Binder VisitTypeDeclarationCore(TypeDeclarationSyntax parent, NodeUsage extraInfo)
{
var key = CreateBinderCacheKey(parent, extraInfo);
Binder resultBinder;
if (!binderCache.TryGetValue(key, out resultBinder))
{
// if node is in the optional type parameter list, then members and type parameters are in scope
// (needed when binding attributes applied to type parameters).
// if node is in the base clause, type parameters are in scope.
// if node is in the body, then members and type parameters are in scope.
// a binder for the body of the type enclosing this type
resultBinder = VisitCore(parent.Parent);
if (extraInfo != NodeUsage.Normal)
{
var typeSymbol = ((NamespaceOrTypeSymbol)resultBinder.ContainingMemberOrLambda).GetSourceTypeMember(parent);
if (extraInfo == NodeUsage.NamedTypeBaseListOrParameterList)
{
// even though there could be no type parameter, we need this binder
// for its "IsAccessible"
resultBinder = new WithClassTypeParametersBinder(typeSymbol, resultBinder);
}
else
{
resultBinder = new InContainerBinder(typeSymbol, resultBinder);
if (parent.TypeParameterList != null)
{
resultBinder = new WithClassTypeParametersBinder(typeSymbol, resultBinder);
}
}
}
resultBinder = resultBinder.WithUnsafeRegionIfNecessary(parent.Modifiers);
binderCache.TryAdd(key, resultBinder);
}
return resultBinder;
}
public override Binder VisitClassDeclaration(ClassDeclarationSyntax node)
{
return VisitTypeDeclarationCore(node);
}
public override Binder VisitStructDeclaration(StructDeclarationSyntax node)
{
return VisitTypeDeclarationCore(node);
}
public override Binder VisitInterfaceDeclaration(InterfaceDeclarationSyntax node)
{
return VisitTypeDeclarationCore(node);
}
public override Binder VisitRecordDeclaration(RecordDeclarationSyntax node)
=> VisitTypeDeclarationCore(node);
public sealed override Binder VisitNamespaceDeclaration(NamespaceDeclarationSyntax parent)
{
if (!LookupPosition.IsInNamespaceDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
// test for position equality in case the open brace token is missing:
// namespace X class C { }
bool inBody = LookupPosition.IsBetweenTokens(_position, parent.OpenBraceToken, parent.CloseBraceToken);
bool inUsing = IsInUsing(parent);
return VisitNamespaceDeclaration(parent, _position, inBody, inUsing);
}
public override Binder VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax parent)
{
if (!LookupPosition.IsInNamespaceDeclaration(_position, parent))
{
return VisitCore(parent.Parent);
}
// Anywhere after the `;` is in the 'body' of this namespace.
bool inBody = _position >= parent.SemicolonToken.EndPosition;
bool inUsing = IsInUsing(parent);
return VisitNamespaceDeclaration(parent, _position, inBody, inUsing);
}
internal Binder VisitNamespaceDeclaration(BaseNamespaceDeclarationSyntax parent, int position, bool inBody, bool inUsing)
{
Debug.Assert(!inUsing || inBody, "inUsing => inBody");
var extraInfo = inUsing ? NodeUsage.NamespaceUsings : (inBody ? NodeUsage.NamespaceBody : NodeUsage.Normal); // extra info for the cache.
var key = CreateBinderCacheKey(parent, extraInfo);
Binder result;
if (!binderCache.TryGetValue(key, out result))
{
Binder outer;
var container = parent.Parent;
if (InScript && container.Kind() == SyntaxKind.CompilationUnit)
{
// Although namespaces are not allowed in script code we still bind them so that we don't report useless errors.
// A namespace in script code is not bound within the scope of a Script class,
// but still within scope of compilation unit extern aliases and usings.
outer = VisitCompilationUnit((CompilationUnitSyntax)container, inUsing: false, inScript: false);
}
else
{
outer = _factory.GetBinder(parent.Parent, position);
}
if (!inBody)
{
// not between the curlies
result = outer;
}
else
{
// if between the curlies, members are in scope
result = MakeNamespaceBinder(parent, parent.Name, outer, inUsing);
}
binderCache.TryAdd(key, result);
}
return result;
}
private static Binder MakeNamespaceBinder(CSharpSyntaxNode node, NameSyntax name, Binder outer, bool inUsing)
{
if (name is QualifiedNameSyntax dotted)
{
outer = MakeNamespaceBinder(dotted.Left, dotted.Left, outer, inUsing: false);
name = dotted.Right;
Debug.Assert(name is not QualifiedNameSyntax);
}
NamespaceOrTypeSymbol container;
if (outer is InContainerBinder inContainerBinder)
{
container = inContainerBinder.Container;
}
else
{
Debug.Assert(outer is SimpleProgramUnitBinder);
container = outer.Compilation.GlobalNamespace;
}
NamespaceSymbol ns = ((NamespaceSymbol)container).GetNestedNamespace(name);
if ((object)ns == null) return outer;
if (node is BaseNamespaceDeclarationSyntax namespaceDecl)
{
outer = AddInImportsBinders((SourceNamespaceSymbol)outer.Compilation.SourceModule.GetModuleNamespace(ns), namespaceDecl, outer, inUsing);
}
else
{
Debug.Assert(!inUsing);
}
return new InContainerBinder(ns, outer);
}
public override Binder VisitCompilationUnit(CompilationUnitSyntax parent)
{
return VisitCompilationUnit(
parent,
inUsing: IsInUsing(parent),
inScript: InScript);
}
internal Binder VisitCompilationUnit(CompilationUnitSyntax compilationUnit, bool inUsing, bool inScript)
{
if (compilationUnit != syntaxTree.GetRoot())
{
throw new ArgumentOutOfRangeException(nameof(compilationUnit), "node not part of tree");
}
var extraInfo = inUsing
? (inScript ? NodeUsage.CompilationUnitScriptUsings : NodeUsage.CompilationUnitUsings)
: (inScript ? NodeUsage.CompilationUnitScript : NodeUsage.Normal); // extra info for the cache.
var key = CreateBinderCacheKey(compilationUnit, extraInfo);
Binder result;
if (!binderCache.TryGetValue(key, out result))
{
result = this.buckStopsHereBinder;
if (inScript)
{
Debug.Assert((object)compilation.ScriptClass != null);
//
// Binder chain in script/interactive code:
//
// + global imports
// + current and previous submission imports (except using aliases)
// + global namespace
// + host object members
// + previous submissions and corresponding using aliases
// + script class members and using aliases
//
bool isSubmissionTree = compilation.IsSubmissionSyntaxTree(compilationUnit.SyntaxTree);
var scriptClass = compilation.ScriptClass;
bool isSubmissionClass = scriptClass.IsSubmissionClass;
if (!inUsing)
{
result = WithUsingNamespacesAndTypesBinder.Create(compilation.GlobalImports, result, withImportChainEntry: true);
if (isSubmissionClass)
{
// NB: Only the non-alias imports are
// ever consumed. Aliases are actually checked in InSubmissionClassBinder (below).
// Note: #loaded trees don't consume previous submission imports.
result = WithUsingNamespacesAndTypesBinder.Create((SourceNamespaceSymbol)compilation.SourceModule.GlobalNamespace, compilationUnit, result,
withPreviousSubmissionImports: compilation.PreviousSubmission != null && isSubmissionTree,
withImportChainEntry: true);
}
}
result = new InContainerBinder(compilation.GlobalNamespace, result);
if (compilation.HostObjectType != null)
{
result = new HostObjectModelBinder(result);
}
if (isSubmissionClass)
{
result = new InSubmissionClassBinder(scriptClass, result, compilationUnit, inUsing);
}
else
{
result = AddInImportsBinders((SourceNamespaceSymbol)compilation.SourceModule.GlobalNamespace, compilationUnit, result, inUsing);
result = new InContainerBinder(scriptClass, result);
}
}
else
{
//
// Binder chain in regular code:
//
// + compilation unit imported namespaces and types
// + compilation unit extern and using aliases
// + global namespace
//
var globalNamespace = compilation.GlobalNamespace;
result = AddInImportsBinders((SourceNamespaceSymbol)compilation.SourceModule.GlobalNamespace, compilationUnit, result, inUsing);
result = new InContainerBinder(globalNamespace, result);
if (!inUsing &&
SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(compilation, compilationUnit, fallbackToMainEntryPoint: true) is SynthesizedSimpleProgramEntryPointSymbol simpleProgram)
{
ExecutableCodeBinder bodyBinder = simpleProgram.GetBodyBinder(_factory._ignoreAccessibility);
result = new SimpleProgramUnitBinder(result, (SimpleProgramBinder)bodyBinder.GetBinder(simpleProgram.SyntaxNode));
}
}
binderCache.TryAdd(key, result);
}
return result;
}
private static Binder AddInImportsBinders(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next, bool inUsing)
{
Debug.Assert(declarationSyntax.Kind() is SyntaxKind.CompilationUnit or SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration);
if (inUsing)
{
// Extern aliases are in scope
return WithExternAliasesBinder.Create(declaringSymbol, declarationSyntax, next);
}
else
{
// All imports are in scope
return WithExternAndUsingAliasesBinder.Create(declaringSymbol, declarationSyntax, WithUsingNamespacesAndTypesBinder.Create(declaringSymbol, declarationSyntax, next));
}
}
internal static BinderCacheKey CreateBinderCacheKey(CSharpSyntaxNode node, NodeUsage usage)
{
Debug.Assert(BitArithmeticUtilities.CountBits((uint)usage) <= 1, "Not a flags enum.");
return new BinderCacheKey(node, usage);
}
/// <summary>
/// Returns true if containingNode has a child that contains the specified position
/// and has kind UsingDirective.
/// </summary>
/// <remarks>
/// Usings can't see other usings, so this is extra info when looking at a namespace
/// or compilation unit scope.
/// </remarks>
private bool IsInUsing(CSharpSyntaxNode containingNode)
{
TextSpan containingSpan = containingNode.Span;
SyntaxToken token;
if (containingNode.Kind() != SyntaxKind.CompilationUnit && _position == containingSpan.End)
{
// This occurs at EOF
token = containingNode.GetLastToken();
Debug.Assert(token == this.syntaxTree.GetRoot().GetLastToken());
}
else if (_position < containingSpan.Start || _position > containingSpan.End) //NB: > not >=
{
return false;
}
else
{
token = containingNode.FindToken(_position);
}
var node = token.Parent;
while (node != null && node != containingNode)
{
// ACASEY: the restriction that we're only interested in children
// of containingNode (vs descendants) seems to be required for cases like
// GetSemanticInfoTests.BindAliasQualifier, which binds an alias name
// within a using directive.
if (node.IsKind(SyntaxKind.UsingDirective) && node.Parent == containingNode)
{
return true;
}
node = node.Parent;
}
return false;
}
public override Binder VisitDocumentationCommentTrivia(DocumentationCommentTriviaSyntax parent)
{
// Need to step across the structured trivia boundary explicitly - can't just follow Parent references.
return VisitCore(parent.ParentTrivia.Token.Parent);
}
/// <remarks>
/// Used to detect whether we are in a cref parameter type.
/// </remarks>
public override Binder VisitCrefParameter(CrefParameterSyntax parent)
{
XmlCrefAttributeSyntax containingAttribute = parent.FirstAncestorOrSelf<XmlCrefAttributeSyntax>(ascendOutOfTrivia: false);
return VisitXmlCrefAttributeInternal(containingAttribute, NodeUsage.CrefParameterOrReturnType);
}
/// <remarks>
/// Used to detect whether we are in a cref return type.
/// </remarks>
public override Binder VisitConversionOperatorMemberCref(ConversionOperatorMemberCrefSyntax parent)
{
if (parent.Type.Span.Contains(_position))
{
XmlCrefAttributeSyntax containingAttribute = parent.FirstAncestorOrSelf<XmlCrefAttributeSyntax>(ascendOutOfTrivia: false);
return VisitXmlCrefAttributeInternal(containingAttribute, NodeUsage.CrefParameterOrReturnType);
}
return base.VisitConversionOperatorMemberCref(parent);
}
public override Binder VisitXmlCrefAttribute(XmlCrefAttributeSyntax parent)
{
if (!LookupPosition.IsInXmlAttributeValue(_position, parent))
{
return VisitCore(parent.Parent);
}
var extraInfo = NodeUsage.Normal; // extra info for the cache.
return VisitXmlCrefAttributeInternal(parent, extraInfo);
}
private Binder VisitXmlCrefAttributeInternal(XmlCrefAttributeSyntax parent, NodeUsage extraInfo)
{
Debug.Assert(extraInfo == NodeUsage.Normal || extraInfo == NodeUsage.CrefParameterOrReturnType,
"Unexpected extraInfo " + extraInfo);
var key = CreateBinderCacheKey(parent, extraInfo);
Binder result;
if (!binderCache.TryGetValue(key, out result))
{
CrefSyntax crefSyntax = parent.Cref;
MemberDeclarationSyntax memberSyntax = GetAssociatedMemberForXmlSyntax(parent);
bool inParameterOrReturnType = extraInfo == NodeUsage.CrefParameterOrReturnType;
result = (object)memberSyntax == null
? MakeCrefBinderInternal(crefSyntax, VisitCore(parent.Parent), inParameterOrReturnType)
: MakeCrefBinder(crefSyntax, memberSyntax, _factory, inParameterOrReturnType);
binderCache.TryAdd(key, result);
}
return result;
}
public override Binder VisitXmlNameAttribute(XmlNameAttributeSyntax parent)
{
if (!LookupPosition.IsInXmlAttributeValue(_position, parent))
{
return VisitCore(parent.Parent);
}
XmlNameAttributeElementKind elementKind = parent.GetElementKind();
NodeUsage extraInfo;
switch (elementKind)
{
case XmlNameAttributeElementKind.Parameter:
case XmlNameAttributeElementKind.ParameterReference:
extraInfo = NodeUsage.DocumentationCommentParameter;
break;
case XmlNameAttributeElementKind.TypeParameter:
extraInfo = NodeUsage.DocumentationCommentTypeParameter;
break;
case XmlNameAttributeElementKind.TypeParameterReference:
extraInfo = NodeUsage.DocumentationCommentTypeParameterReference;
break;
default:
throw ExceptionUtilities.UnexpectedValue(elementKind);
}
// Cleverness: rather than using this node as the key, we're going to use the
// enclosing doc comment, because all name attributes with the same element
// kind, in the same doc comment can share the same binder.
var key = CreateBinderCacheKey(GetEnclosingDocumentationComment(parent), extraInfo);
Binder result;
if (!binderCache.TryGetValue(key, out result))
{
result = this.buckStopsHereBinder;
Binder outerBinder = VisitCore(GetEnclosingDocumentationComment(parent));
if ((object)outerBinder != null)
{
// The rest of the doc comment is going to report something for containing symbol -
// that shouldn't change just because we're in a name attribute.
result = result.WithContainingMemberOrLambda(outerBinder.ContainingMemberOrLambda);
}
MemberDeclarationSyntax memberSyntax = GetAssociatedMemberForXmlSyntax(parent);
if ((object)memberSyntax != null)
{
switch (elementKind)
{
case XmlNameAttributeElementKind.Parameter:
case XmlNameAttributeElementKind.ParameterReference:
result = GetParameterNameAttributeValueBinder(memberSyntax, result);
break;
case XmlNameAttributeElementKind.TypeParameter:
result = GetTypeParameterNameAttributeValueBinder(memberSyntax, includeContainingSymbols: false, nextBinder: result);
break;
case XmlNameAttributeElementKind.TypeParameterReference:
result = GetTypeParameterNameAttributeValueBinder(memberSyntax, includeContainingSymbols: true, nextBinder: result);
break;
}
}
binderCache.TryAdd(key, result);
}
return result;
}
/// <summary>
/// We're in a <param> or <paramref> element, so we want a binder that can see
/// the parameters of the associated member and nothing else.
/// </summary>
private Binder GetParameterNameAttributeValueBinder(MemberDeclarationSyntax memberSyntax, Binder nextBinder)
{
if (memberSyntax is BaseMethodDeclarationSyntax { ParameterList: { ParameterCount: > 0 } } baseMethodDeclSyntax)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
MethodSymbol method = GetMethodSymbol(baseMethodDeclSyntax, outerBinder);
return new WithParametersBinder(method.Parameters, nextBinder);
}
if (memberSyntax is RecordDeclarationSyntax { ParameterList: { ParameterCount: > 0 } })
{
Binder outerBinder = VisitCore(memberSyntax);
SourceNamedTypeSymbol recordType = ((NamespaceOrTypeSymbol)outerBinder.ContainingMemberOrLambda).GetSourceTypeMember((TypeDeclarationSyntax)memberSyntax);
var primaryConstructor = recordType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().SingleOrDefault();
if (primaryConstructor.SyntaxRef.SyntaxTree == memberSyntax.SyntaxTree &&
primaryConstructor.GetSyntax() == memberSyntax)
{
return new WithParametersBinder(primaryConstructor.Parameters, nextBinder);
}
}
// As in Dev11, we do not allow <param name="value"> on events.
SyntaxKind memberKind = memberSyntax.Kind();
if (memberKind == SyntaxKind.PropertyDeclaration || memberKind == SyntaxKind.IndexerDeclaration)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
BasePropertyDeclarationSyntax propertyDeclSyntax = (BasePropertyDeclarationSyntax)memberSyntax;
PropertySymbol property = GetPropertySymbol(propertyDeclSyntax, outerBinder);
ImmutableArray<ParameterSymbol> parameters = property.Parameters;
// BREAK: Dev11 also allows "value" for readonly properties, but that doesn't
// make sense and we don't have a symbol.
if ((object)property.SetMethod != null)
{
Debug.Assert(property.SetMethod.ParameterCount > 0);
parameters = parameters.Add(property.SetMethod.Parameters.Last());
}
if (parameters.Any())
{
return new WithParametersBinder(parameters, nextBinder);
}
}
else if (memberKind == SyntaxKind.DelegateDeclaration)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
SourceNamedTypeSymbol delegateType = ((NamespaceOrTypeSymbol)outerBinder.ContainingMemberOrLambda).GetSourceTypeMember((DelegateDeclarationSyntax)memberSyntax);
Debug.Assert((object)delegateType != null);
MethodSymbol invokeMethod = delegateType.DelegateInvokeMethod;
Debug.Assert((object)invokeMethod != null);
ImmutableArray<ParameterSymbol> parameters = invokeMethod.Parameters;
if (parameters.Any())
{
return new WithParametersBinder(parameters, nextBinder);
}
}
return nextBinder;
}
/// <summary>
/// We're in a <typeparam> or <typeparamref> element, so we want a binder that can see
/// the type parameters of the associated member and nothing else.
/// </summary>
private Binder GetTypeParameterNameAttributeValueBinder(MemberDeclarationSyntax memberSyntax, bool includeContainingSymbols, Binder nextBinder)
{
if (includeContainingSymbols)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
for (NamedTypeSymbol curr = outerBinder.ContainingType; (object)curr != null; curr = curr.ContainingType)
{
if (curr.Arity > 0)
{
nextBinder = new WithClassTypeParametersBinder(curr, nextBinder);
}
}
}
// NOTE: don't care about enums, since they don't have type parameters.
TypeDeclarationSyntax typeDeclSyntax = memberSyntax as TypeDeclarationSyntax;
if ((object)typeDeclSyntax != null && typeDeclSyntax.Arity > 0)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
SourceNamedTypeSymbol typeSymbol = ((NamespaceOrTypeSymbol)outerBinder.ContainingMemberOrLambda).GetSourceTypeMember(typeDeclSyntax);
// NOTE: don't include anything else in the binder chain.
return new WithClassTypeParametersBinder(typeSymbol, nextBinder);
}
if (memberSyntax.Kind() == SyntaxKind.MethodDeclaration)
{
MethodDeclarationSyntax methodDeclSyntax = (MethodDeclarationSyntax)memberSyntax;
if (methodDeclSyntax.Arity > 0)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
MethodSymbol method = GetMethodSymbol(methodDeclSyntax, outerBinder);
return new WithMethodTypeParametersBinder(method, nextBinder);
}
}
else if (memberSyntax.Kind() == SyntaxKind.DelegateDeclaration)
{
Binder outerBinder = VisitCore(memberSyntax.Parent);
SourceNamedTypeSymbol delegateType = ((NamespaceOrTypeSymbol)outerBinder.ContainingMemberOrLambda).GetSourceTypeMember((DelegateDeclarationSyntax)memberSyntax);
ImmutableArray<TypeParameterSymbol> typeParameters = delegateType.TypeParameters;
if (typeParameters.Any())
{
return new WithClassTypeParametersBinder(delegateType, nextBinder);
}
}
return nextBinder;
}
}
#region In outer type - BinderFactory
/// <summary>
/// Given a CrefSyntax and an associated member declaration syntax node,
/// construct an appropriate binder for binding the cref.
/// </summary>
/// <param name="crefSyntax">Cref that will be bound.</param>
/// <param name="memberSyntax">The member to which the documentation comment (logically) containing
/// the cref syntax applies.</param>
/// <param name="factory">Corresponding binder factory.</param>
/// <param name="inParameterOrReturnType">True to get a special binder for cref parameter and return types.</param>
/// <remarks>
/// The CrefSyntax does not actually have to be within the documentation comment on the member - it
/// could be included from another file.
/// </remarks>
internal static Binder MakeCrefBinder(CrefSyntax crefSyntax, MemberDeclarationSyntax memberSyntax, BinderFactory factory, bool inParameterOrReturnType = false)
{
Debug.Assert(crefSyntax != null);
Debug.Assert(memberSyntax != null);
Binder binder = memberSyntax is BaseTypeDeclarationSyntax typeDeclSyntax
? getBinder(typeDeclSyntax)
: factory.GetBinder(memberSyntax);
return MakeCrefBinderInternal(crefSyntax, binder, inParameterOrReturnType);
Binder getBinder(BaseTypeDeclarationSyntax baseTypeDeclaration)
{
if (baseTypeDeclaration is RecordDeclarationSyntax { SemicolonToken: { RawKind: (int)SyntaxKind.SemicolonToken } } recordDeclaration)
{
return factory.GetInRecordBodyBinder(recordDeclaration);
}
return factory.GetBinder(baseTypeDeclaration, baseTypeDeclaration.OpenBraceToken.SpanStart);
}
}
/// <summary>
/// Internal version of MakeCrefBinder that allows the caller to explicitly set the underlying binder.
/// </summary>
private static Binder MakeCrefBinderInternal(CrefSyntax crefSyntax, Binder binder, bool inParameterOrReturnType)
{
// After much deliberation, we eventually decided to suppress lookup of inherited members within
// crefs, in order to match dev11's behavior (Changeset #829014). Unfortunately, it turns out
// that dev11 does not suppress these members when performing lookup within parameter and return
// types, within crefs (DevDiv #586815, #598371).
// NOTE: always allow pointer types.
BinderFlags flags = BinderFlags.Cref | BinderFlags.SuppressConstraintChecks | BinderFlags.UnsafeRegion;
if (inParameterOrReturnType)
{
flags |= BinderFlags.CrefParameterOrReturnType;
}
binder = binder.WithAdditionalFlags(flags);
binder = new WithCrefTypeParametersBinder(crefSyntax, binder);
return binder;
}
internal static MemberDeclarationSyntax GetAssociatedMemberForXmlSyntax(CSharpSyntaxNode xmlSyntax)
{
Debug.Assert(xmlSyntax is XmlAttributeSyntax || xmlSyntax.Kind() == SyntaxKind.XmlEmptyElement || xmlSyntax.Kind() == SyntaxKind.XmlElementStartTag);
StructuredTriviaSyntax structuredTrivia = GetEnclosingDocumentationComment(xmlSyntax);
SyntaxTrivia containingTrivia = structuredTrivia.ParentTrivia;
SyntaxToken associatedToken = (SyntaxToken)containingTrivia.Token;
CSharpSyntaxNode curr = (CSharpSyntaxNode)associatedToken.Parent;
while (curr != null)
{
MemberDeclarationSyntax memberSyntax = curr as MemberDeclarationSyntax;
if (memberSyntax != null)
{
// CONSIDER: require that the xml syntax precede the start of the member span?
return memberSyntax;
}
curr = curr.Parent;
}
return null;
}
/// <summary>
/// Walk up from an XML syntax node (attribute or tag) to the enclosing documentation comment trivia.
/// </summary>
private static DocumentationCommentTriviaSyntax GetEnclosingDocumentationComment(CSharpSyntaxNode xmlSyntax)
{
CSharpSyntaxNode curr = xmlSyntax;
for (; !SyntaxFacts.IsDocumentationCommentTrivia(curr.Kind()); curr = curr.Parent)
{
}
Debug.Assert(curr != null);
return (DocumentationCommentTriviaSyntax)curr;
}
#endregion
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Scripting/Core/ScriptOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Scripting
{
using static ParameterValidationHelpers;
/// <summary>
/// Options for creating and running scripts.
/// </summary>
public sealed class ScriptOptions
{
public static ScriptOptions Default { get; } = new ScriptOptions(
filePath: string.Empty,
references: GetDefaultMetadataReferences(),
namespaces: ImmutableArray<string>.Empty,
metadataResolver: ScriptMetadataResolver.Default,
sourceResolver: SourceFileResolver.Default,
emitDebugInformation: false,
fileEncoding: null,
OptimizationLevel.Debug,
checkOverflow: false,
allowUnsafe: true,
warningLevel: 4,
parseOptions: null);
private static ImmutableArray<MetadataReference> GetDefaultMetadataReferences()
{
if (GacFileResolver.IsAvailable)
{
return ImmutableArray<MetadataReference>.Empty;
}
// These references are resolved lazily. Keep in sync with list in core csi.rsp.
var files = new[]
{
"System.Collections",
"System.Collections.Concurrent",
"System.Console",
"System.Diagnostics.Debug",
"System.Diagnostics.Process",
"System.Diagnostics.StackTrace",
"System.Globalization",
"System.IO",
"System.IO.FileSystem",
"System.IO.FileSystem.Primitives",
"System.Reflection",
"System.Reflection.Extensions",
"System.Reflection.Primitives",
"System.Runtime",
"System.Runtime.Extensions",
"System.Runtime.InteropServices",
"System.Text.Encoding",
"System.Text.Encoding.CodePages",
"System.Text.Encoding.Extensions",
"System.Text.RegularExpressions",
"System.Threading",
"System.Threading.Tasks",
"System.Threading.Tasks.Parallel",
"System.Threading.Thread",
"System.ValueTuple",
};
return ImmutableArray.CreateRange(files.Select(CreateUnresolvedReference));
}
/// <summary>
/// An array of <see cref="MetadataReference"/>s to be added to the script.
/// </summary>
/// <remarks>
/// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>).
/// Unresolved references are resolved when the script is about to be executed
/// (<see cref="Script.RunAsync(object, CancellationToken)"/>.
/// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>.
/// </remarks>
public ImmutableArray<MetadataReference> MetadataReferences { get; private set; }
/// <summary>
/// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives.
/// </summary>
public MetadataReferenceResolver MetadataResolver { get; private set; }
/// <summary>
/// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive.
/// </summary>
public SourceReferenceResolver SourceResolver { get; private set; }
/// <summary>
/// The namespaces, static classes and aliases imported by the script.
/// </summary>
public ImmutableArray<string> Imports { get; private set; }
/// <summary>
/// Specifies whether debugging symbols should be emitted.
/// </summary>
public bool EmitDebugInformation { get; private set; } = false;
/// <summary>
/// Specifies the encoding to be used when debugging scripts loaded from a file, or saved to a file for debugging purposes.
/// If it's null, the compiler will attempt to detect the necessary encoding for debugging
/// </summary>
public Encoding FileEncoding { get; private set; }
/// <summary>
/// The path to the script source if it originated from a file, empty otherwise.
/// </summary>
public string FilePath { get; private set; }
/// <summary>
/// Specifies whether or not optimizations should be performed on the output IL.
/// </summary>
public OptimizationLevel OptimizationLevel { get; private set; }
/// <summary>
/// Whether bounds checking on integer arithmetic is enforced by default or not.
/// </summary>
public bool CheckOverflow { get; private set; }
/// <summary>
/// Allow unsafe regions (i.e. unsafe modifiers on members and unsafe blocks).
/// </summary>
public bool AllowUnsafe { get; private set; }
/// <summary>
/// Global warning level (from 0 to 4).
/// </summary>
public int WarningLevel { get; private set; }
internal ParseOptions ParseOptions { get; private set; }
internal ScriptOptions(
string filePath,
ImmutableArray<MetadataReference> references,
ImmutableArray<string> namespaces,
MetadataReferenceResolver metadataResolver,
SourceReferenceResolver sourceResolver,
bool emitDebugInformation,
Encoding fileEncoding,
OptimizationLevel optimizationLevel,
bool checkOverflow,
bool allowUnsafe,
int warningLevel,
ParseOptions parseOptions)
{
Debug.Assert(filePath != null);
Debug.Assert(!references.IsDefault);
Debug.Assert(!namespaces.IsDefault);
Debug.Assert(metadataResolver != null);
Debug.Assert(sourceResolver != null);
FilePath = filePath;
MetadataReferences = references;
Imports = namespaces;
MetadataResolver = metadataResolver;
SourceResolver = sourceResolver;
EmitDebugInformation = emitDebugInformation;
FileEncoding = fileEncoding;
OptimizationLevel = optimizationLevel;
CheckOverflow = checkOverflow;
AllowUnsafe = allowUnsafe;
WarningLevel = warningLevel;
ParseOptions = parseOptions;
}
private ScriptOptions(ScriptOptions other)
: this(filePath: other.FilePath,
references: other.MetadataReferences,
namespaces: other.Imports,
metadataResolver: other.MetadataResolver,
sourceResolver: other.SourceResolver,
emitDebugInformation: other.EmitDebugInformation,
fileEncoding: other.FileEncoding,
optimizationLevel: other.OptimizationLevel,
checkOverflow: other.CheckOverflow,
allowUnsafe: other.AllowUnsafe,
warningLevel: other.WarningLevel,
parseOptions: other.ParseOptions)
{
}
// a reference to an assembly should by default be equivalent to #r, which applies recursive global alias:
private static readonly MetadataReferenceProperties s_assemblyReferenceProperties =
MetadataReferenceProperties.Assembly.WithRecursiveAliases(true);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="FilePath"/> changed.
/// </summary>
public ScriptOptions WithFilePath(string filePath) =>
(FilePath == filePath) ? this : new ScriptOptions(this) { FilePath = filePath ?? "" };
private static MetadataReference CreateUnresolvedReference(string reference) =>
new UnresolvedMetadataReference(reference, s_assemblyReferenceProperties);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
private ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) =>
MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ToImmutableArrayChecked(references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params MetadataReference[] references) =>
WithReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ConcatChecked(MetadataReferences, references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params MetadataReference[] references) =>
AddReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions WithReferences(IEnumerable<Assembly> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions WithReferences(params Assembly[] references) =>
WithReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions AddReferences(IEnumerable<Assembly> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly));
private static MetadataReference CreateReferenceFromAssembly(Assembly assembly)
{
return MetadataReference.CreateFromAssemblyInternal(assembly, s_assemblyReferenceProperties);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions AddReferences(params Assembly[] references) =>
AddReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<string> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params string[] references) =>
WithReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<string> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params string[] references) =>
AddReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>.
/// </summary>
public ScriptOptions WithMetadataResolver(MetadataReferenceResolver resolver) =>
MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>.
/// </summary>
public ScriptOptions WithSourceResolver(SourceReferenceResolver resolver) =>
SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
private ScriptOptions WithImports(ImmutableArray<string> imports) =>
Imports.Equals(imports) ? this : new ScriptOptions(this) { Imports = CheckImmutableArray(imports, nameof(imports)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(IEnumerable<string> imports) =>
WithImports(ToImmutableArrayChecked(imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(params string[] imports) =>
WithImports((IEnumerable<string>)imports);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(IEnumerable<string> imports) =>
WithImports(ConcatChecked(Imports, imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(params string[] imports) =>
AddImports((IEnumerable<string>)imports);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with debugging information enabled.
/// </summary>
public ScriptOptions WithEmitDebugInformation(bool emitDebugInformation) =>
emitDebugInformation == EmitDebugInformation ? this : new ScriptOptions(this) { EmitDebugInformation = emitDebugInformation };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="FileEncoding"/>.
/// </summary>
public ScriptOptions WithFileEncoding(Encoding encoding) =>
encoding == FileEncoding ? this : new ScriptOptions(this) { FileEncoding = encoding };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with the specified <see cref="OptimizationLevel"/>.
/// </summary>
/// <returns></returns>
public ScriptOptions WithOptimizationLevel(OptimizationLevel optimizationLevel) =>
optimizationLevel == OptimizationLevel ? this : new ScriptOptions(this) { OptimizationLevel = optimizationLevel };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with unsafe code regions allowed.
/// </summary>
public ScriptOptions WithAllowUnsafe(bool allowUnsafe) =>
allowUnsafe == AllowUnsafe ? this : new ScriptOptions(this) { AllowUnsafe = allowUnsafe };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with bounds checking on integer arithmetic enforced.
/// </summary>
public ScriptOptions WithCheckOverflow(bool checkOverflow) =>
checkOverflow == CheckOverflow ? this : new ScriptOptions(this) { CheckOverflow = checkOverflow };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with the specific <see cref="WarningLevel"/>.
/// </summary>
public ScriptOptions WithWarningLevel(int warningLevel) =>
warningLevel == WarningLevel ? this : new ScriptOptions(this) { WarningLevel = warningLevel };
internal ScriptOptions WithParseOptions(ParseOptions parseOptions) =>
parseOptions == ParseOptions ? this : new ScriptOptions(this) { ParseOptions = parseOptions };
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Scripting
{
using static ParameterValidationHelpers;
/// <summary>
/// Options for creating and running scripts.
/// </summary>
public sealed class ScriptOptions
{
public static ScriptOptions Default { get; } = new ScriptOptions(
filePath: string.Empty,
references: GetDefaultMetadataReferences(),
namespaces: ImmutableArray<string>.Empty,
metadataResolver: ScriptMetadataResolver.Default,
sourceResolver: SourceFileResolver.Default,
emitDebugInformation: false,
fileEncoding: null,
OptimizationLevel.Debug,
checkOverflow: false,
allowUnsafe: true,
warningLevel: 4,
parseOptions: null);
private static ImmutableArray<MetadataReference> GetDefaultMetadataReferences()
{
if (GacFileResolver.IsAvailable)
{
return ImmutableArray<MetadataReference>.Empty;
}
// These references are resolved lazily. Keep in sync with list in core csi.rsp.
var files = new[]
{
"System.Collections",
"System.Collections.Concurrent",
"System.Console",
"System.Diagnostics.Debug",
"System.Diagnostics.Process",
"System.Diagnostics.StackTrace",
"System.Globalization",
"System.IO",
"System.IO.FileSystem",
"System.IO.FileSystem.Primitives",
"System.Reflection",
"System.Reflection.Extensions",
"System.Reflection.Primitives",
"System.Runtime",
"System.Runtime.Extensions",
"System.Runtime.InteropServices",
"System.Text.Encoding",
"System.Text.Encoding.CodePages",
"System.Text.Encoding.Extensions",
"System.Text.RegularExpressions",
"System.Threading",
"System.Threading.Tasks",
"System.Threading.Tasks.Parallel",
"System.Threading.Thread",
"System.ValueTuple",
};
return ImmutableArray.CreateRange(files.Select(CreateUnresolvedReference));
}
/// <summary>
/// An array of <see cref="MetadataReference"/>s to be added to the script.
/// </summary>
/// <remarks>
/// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>).
/// Unresolved references are resolved when the script is about to be executed
/// (<see cref="Script.RunAsync(object, CancellationToken)"/>.
/// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>.
/// </remarks>
public ImmutableArray<MetadataReference> MetadataReferences { get; private set; }
/// <summary>
/// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives.
/// </summary>
public MetadataReferenceResolver MetadataResolver { get; private set; }
/// <summary>
/// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive.
/// </summary>
public SourceReferenceResolver SourceResolver { get; private set; }
/// <summary>
/// The namespaces, static classes and aliases imported by the script.
/// </summary>
public ImmutableArray<string> Imports { get; private set; }
/// <summary>
/// Specifies whether debugging symbols should be emitted.
/// </summary>
public bool EmitDebugInformation { get; private set; } = false;
/// <summary>
/// Specifies the encoding to be used when debugging scripts loaded from a file, or saved to a file for debugging purposes.
/// If it's null, the compiler will attempt to detect the necessary encoding for debugging
/// </summary>
public Encoding FileEncoding { get; private set; }
/// <summary>
/// The path to the script source if it originated from a file, empty otherwise.
/// </summary>
public string FilePath { get; private set; }
/// <summary>
/// Specifies whether or not optimizations should be performed on the output IL.
/// </summary>
public OptimizationLevel OptimizationLevel { get; private set; }
/// <summary>
/// Whether bounds checking on integer arithmetic is enforced by default or not.
/// </summary>
public bool CheckOverflow { get; private set; }
/// <summary>
/// Allow unsafe regions (i.e. unsafe modifiers on members and unsafe blocks).
/// </summary>
public bool AllowUnsafe { get; private set; }
/// <summary>
/// Global warning level (from 0 to 4).
/// </summary>
public int WarningLevel { get; private set; }
internal ParseOptions ParseOptions { get; private set; }
internal ScriptOptions(
string filePath,
ImmutableArray<MetadataReference> references,
ImmutableArray<string> namespaces,
MetadataReferenceResolver metadataResolver,
SourceReferenceResolver sourceResolver,
bool emitDebugInformation,
Encoding fileEncoding,
OptimizationLevel optimizationLevel,
bool checkOverflow,
bool allowUnsafe,
int warningLevel,
ParseOptions parseOptions)
{
Debug.Assert(filePath != null);
Debug.Assert(!references.IsDefault);
Debug.Assert(!namespaces.IsDefault);
Debug.Assert(metadataResolver != null);
Debug.Assert(sourceResolver != null);
FilePath = filePath;
MetadataReferences = references;
Imports = namespaces;
MetadataResolver = metadataResolver;
SourceResolver = sourceResolver;
EmitDebugInformation = emitDebugInformation;
FileEncoding = fileEncoding;
OptimizationLevel = optimizationLevel;
CheckOverflow = checkOverflow;
AllowUnsafe = allowUnsafe;
WarningLevel = warningLevel;
ParseOptions = parseOptions;
}
private ScriptOptions(ScriptOptions other)
: this(filePath: other.FilePath,
references: other.MetadataReferences,
namespaces: other.Imports,
metadataResolver: other.MetadataResolver,
sourceResolver: other.SourceResolver,
emitDebugInformation: other.EmitDebugInformation,
fileEncoding: other.FileEncoding,
optimizationLevel: other.OptimizationLevel,
checkOverflow: other.CheckOverflow,
allowUnsafe: other.AllowUnsafe,
warningLevel: other.WarningLevel,
parseOptions: other.ParseOptions)
{
}
// a reference to an assembly should by default be equivalent to #r, which applies recursive global alias:
private static readonly MetadataReferenceProperties s_assemblyReferenceProperties =
MetadataReferenceProperties.Assembly.WithRecursiveAliases(true);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="FilePath"/> changed.
/// </summary>
public ScriptOptions WithFilePath(string filePath) =>
(FilePath == filePath) ? this : new ScriptOptions(this) { FilePath = filePath ?? "" };
private static MetadataReference CreateUnresolvedReference(string reference) =>
new UnresolvedMetadataReference(reference, s_assemblyReferenceProperties);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
private ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) =>
MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ToImmutableArrayChecked(references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params MetadataReference[] references) =>
WithReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ConcatChecked(MetadataReferences, references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params MetadataReference[] references) =>
AddReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions WithReferences(IEnumerable<Assembly> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions WithReferences(params Assembly[] references) =>
WithReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions AddReferences(IEnumerable<Assembly> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly));
private static MetadataReference CreateReferenceFromAssembly(Assembly assembly)
{
return MetadataReference.CreateFromAssemblyInternal(assembly, s_assemblyReferenceProperties);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions AddReferences(params Assembly[] references) =>
AddReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<string> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params string[] references) =>
WithReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<string> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params string[] references) =>
AddReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>.
/// </summary>
public ScriptOptions WithMetadataResolver(MetadataReferenceResolver resolver) =>
MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>.
/// </summary>
public ScriptOptions WithSourceResolver(SourceReferenceResolver resolver) =>
SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
private ScriptOptions WithImports(ImmutableArray<string> imports) =>
Imports.Equals(imports) ? this : new ScriptOptions(this) { Imports = CheckImmutableArray(imports, nameof(imports)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(IEnumerable<string> imports) =>
WithImports(ToImmutableArrayChecked(imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(params string[] imports) =>
WithImports((IEnumerable<string>)imports);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(IEnumerable<string> imports) =>
WithImports(ConcatChecked(Imports, imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(params string[] imports) =>
AddImports((IEnumerable<string>)imports);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with debugging information enabled.
/// </summary>
public ScriptOptions WithEmitDebugInformation(bool emitDebugInformation) =>
emitDebugInformation == EmitDebugInformation ? this : new ScriptOptions(this) { EmitDebugInformation = emitDebugInformation };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="FileEncoding"/>.
/// </summary>
public ScriptOptions WithFileEncoding(Encoding encoding) =>
encoding == FileEncoding ? this : new ScriptOptions(this) { FileEncoding = encoding };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with the specified <see cref="OptimizationLevel"/>.
/// </summary>
/// <returns></returns>
public ScriptOptions WithOptimizationLevel(OptimizationLevel optimizationLevel) =>
optimizationLevel == OptimizationLevel ? this : new ScriptOptions(this) { OptimizationLevel = optimizationLevel };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with unsafe code regions allowed.
/// </summary>
public ScriptOptions WithAllowUnsafe(bool allowUnsafe) =>
allowUnsafe == AllowUnsafe ? this : new ScriptOptions(this) { AllowUnsafe = allowUnsafe };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with bounds checking on integer arithmetic enforced.
/// </summary>
public ScriptOptions WithCheckOverflow(bool checkOverflow) =>
checkOverflow == CheckOverflow ? this : new ScriptOptions(this) { CheckOverflow = checkOverflow };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with the specific <see cref="WarningLevel"/>.
/// </summary>
public ScriptOptions WithWarningLevel(int warningLevel) =>
warningLevel == WarningLevel ? this : new ScriptOptions(this) { WarningLevel = warningLevel };
internal ScriptOptions WithParseOptions(ParseOptions parseOptions) =>
parseOptions == ParseOptions ? this : new ScriptOptions(this) { ParseOptions = parseOptions };
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/CSharp/Portable/Symbols/Source/SourceLocalSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a local variable in a method body.
/// </summary>
internal class SourceLocalSymbol : LocalSymbol
{
private readonly Binder _scopeBinder;
/// <summary>
/// Might not be a method symbol.
/// </summary>
private readonly Symbol _containingSymbol;
private readonly SyntaxToken _identifierToken;
private readonly ImmutableArray<Location> _locations;
private readonly RefKind _refKind;
private readonly TypeSyntax _typeSyntax;
private readonly LocalDeclarationKind _declarationKind;
private TypeWithAnnotations.Boxed _type;
/// <summary>
/// Scope to which the local can "escape" via aliasing/ref assignment.
/// Not readonly because we can only know escape values after binding the initializer.
/// </summary>
protected uint _refEscapeScope;
/// <summary>
/// Scope to which the local's values can "escape" via ordinary assignments.
/// Not readonly because we can only know escape values after binding the initializer.
/// </summary>
protected uint _valEscapeScope;
private SourceLocalSymbol(
Symbol containingSymbol,
Binder scopeBinder,
bool allowRefKind,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
LocalDeclarationKind declarationKind)
{
Debug.Assert(identifierToken.Kind() != SyntaxKind.None);
Debug.Assert(declarationKind != LocalDeclarationKind.None);
Debug.Assert(scopeBinder != null);
this._scopeBinder = scopeBinder;
this._containingSymbol = containingSymbol;
this._identifierToken = identifierToken;
this._typeSyntax = allowRefKind ? typeSyntax?.SkipRef(out this._refKind) : typeSyntax;
this._declarationKind = declarationKind;
// create this eagerly as it will always be needed for the EnsureSingleDefinition
_locations = ImmutableArray.Create<Location>(identifierToken.GetLocation());
_refEscapeScope = this._refKind == RefKind.None ?
scopeBinder.LocalScopeDepth :
Binder.ExternalScope; // default to returnable, unless there is initializer
// we do not know the type yet.
// assume this is returnable in case we never get to know our type.
_valEscapeScope = Binder.ExternalScope;
}
/// <summary>
/// Binder that owns the scope for the local, the one that returns it in its <see cref="Binder.Locals"/> array.
/// </summary>
internal Binder ScopeBinder
{
get { return _scopeBinder; }
}
internal override SyntaxNode ScopeDesignatorOpt
{
get { return _scopeBinder.ScopeDesignator; }
}
internal override uint RefEscapeScope => _refEscapeScope;
internal override uint ValEscapeScope => _valEscapeScope;
/// <summary>
/// Binder that should be used to bind type syntax for the local.
/// </summary>
internal Binder TypeSyntaxBinder
{
get { return _scopeBinder; } // Scope binder should be good enough for this.
}
// When the variable's type has not yet been inferred,
// don't let the debugger force inference.
internal override string GetDebuggerDisplay()
{
return _type != null
? base.GetDebuggerDisplay()
: $"{this.Kind} <var> ${this.Name}";
}
public static SourceLocalSymbol MakeForeachLocal(
MethodSymbol containingMethod,
ForEachLoopBinder binder,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
ExpressionSyntax collection)
{
return new ForEachLocalSymbol(containingMethod, binder, typeSyntax, identifierToken, collection, LocalDeclarationKind.ForEachIterationVariable);
}
/// <summary>
/// Make a local variable symbol for an element of a deconstruction,
/// which can be inferred (if necessary) by binding the enclosing statement.
/// </summary>
/// <param name="containingSymbol"></param>
/// <param name="scopeBinder">
/// Binder that owns the scope for the local, the one that returns it in its <see cref="Binder.Locals"/> array.
/// </param>
/// <param name="nodeBinder">
/// Enclosing binder for the location where the local is declared.
/// It should be used to bind something at that location.
/// </param>
/// <param name="closestTypeSyntax"></param>
/// <param name="identifierToken"></param>
/// <param name="kind"></param>
/// <param name="deconstruction"></param>
/// <returns></returns>
public static SourceLocalSymbol MakeDeconstructionLocal(
Symbol containingSymbol,
Binder scopeBinder,
Binder nodeBinder,
TypeSyntax closestTypeSyntax,
SyntaxToken identifierToken,
LocalDeclarationKind kind,
SyntaxNode deconstruction)
{
Debug.Assert(closestTypeSyntax != null);
Debug.Assert(nodeBinder != null);
Debug.Assert(closestTypeSyntax.Kind() != SyntaxKind.RefType);
return closestTypeSyntax.IsVar
? new DeconstructionLocalSymbol(containingSymbol, scopeBinder, nodeBinder, closestTypeSyntax, identifierToken, kind, deconstruction)
: new SourceLocalSymbol(containingSymbol, scopeBinder, false, closestTypeSyntax, identifierToken, kind);
}
/// <summary>
/// Make a local variable symbol whose type can be inferred (if necessary) by binding and enclosing construct.
/// </summary>
internal static LocalSymbol MakeLocalSymbolWithEnclosingContext(
Symbol containingSymbol,
Binder scopeBinder,
Binder nodeBinder,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
LocalDeclarationKind kind,
SyntaxNode nodeToBind,
SyntaxNode forbiddenZone)
{
Debug.Assert(
nodeToBind.Kind() == SyntaxKind.CasePatternSwitchLabel ||
nodeToBind.Kind() == SyntaxKind.ThisConstructorInitializer ||
nodeToBind.Kind() == SyntaxKind.BaseConstructorInitializer ||
nodeToBind.Kind() == SyntaxKind.PrimaryConstructorBaseType || // initializer for a record constructor
nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm ||
nodeToBind.Kind() == SyntaxKind.ArgumentList && (nodeToBind.Parent is ConstructorInitializerSyntax || nodeToBind.Parent is PrimaryConstructorBaseTypeSyntax) ||
nodeToBind.Kind() == SyntaxKind.GotoCaseStatement || // for error recovery
nodeToBind.Kind() == SyntaxKind.VariableDeclarator &&
new[] { SyntaxKind.LocalDeclarationStatement, SyntaxKind.ForStatement, SyntaxKind.UsingStatement, SyntaxKind.FixedStatement }.
Contains(nodeToBind.Ancestors().OfType<StatementSyntax>().First().Kind()) ||
nodeToBind is ExpressionSyntax);
Debug.Assert(!(nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm) || nodeBinder is SwitchExpressionArmBinder);
return typeSyntax?.IsVar != false && kind != LocalDeclarationKind.DeclarationExpressionVariable
? new LocalSymbolWithEnclosingContext(containingSymbol, scopeBinder, nodeBinder, typeSyntax, identifierToken, kind, nodeToBind, forbiddenZone)
: new SourceLocalSymbol(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, kind);
}
/// <summary>
/// Make a local variable symbol which can be inferred (if necessary) by binding its initializing expression.
/// </summary>
/// <param name="containingSymbol"></param>
/// <param name="scopeBinder">
/// Binder that owns the scope for the local, the one that returns it in its <see cref="Binder.Locals"/> array.
/// </param>
/// <param name="allowRefKind"></param>
/// <param name="typeSyntax"></param>
/// <param name="identifierToken"></param>
/// <param name="declarationKind"></param>
/// <param name="initializer"></param>
/// <param name="initializerBinderOpt">
/// Binder that should be used to bind initializer, if different from the <paramref name="scopeBinder"/>.
/// </param>
/// <returns></returns>
public static SourceLocalSymbol MakeLocal(
Symbol containingSymbol,
Binder scopeBinder,
bool allowRefKind,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
LocalDeclarationKind declarationKind,
EqualsValueClauseSyntax initializer = null,
Binder initializerBinderOpt = null)
{
Debug.Assert(declarationKind != LocalDeclarationKind.ForEachIterationVariable);
return (initializer != null)
? new LocalWithInitializer(containingSymbol, scopeBinder, typeSyntax, identifierToken, initializer, initializerBinderOpt ?? scopeBinder, declarationKind)
: new SourceLocalSymbol(containingSymbol, scopeBinder, allowRefKind, typeSyntax, identifierToken, declarationKind);
}
internal override bool IsImportedFromMetadata
{
get { return false; }
}
internal override LocalDeclarationKind DeclarationKind
{
get { return _declarationKind; }
}
internal override SynthesizedLocalKind SynthesizedKind
{
get { return SynthesizedLocalKind.UserDefined; }
}
internal override LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax)
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsPinned
{
get
{
// even when dealing with "fixed" locals it is the underlying managed reference that gets pinned
// the pointer variable itself is not pinned.
return false;
}
}
internal virtual void SetRefEscape(uint value)
{
_refEscapeScope = value;
}
internal virtual void SetValEscape(uint value)
{
_valEscapeScope = value;
}
public override Symbol ContainingSymbol
{
get { return _containingSymbol; }
}
/// <summary>
/// Gets the name of the local variable.
/// </summary>
public override string Name
{
get
{
return _identifierToken.ValueText;
}
}
// Get the identifier token that defined this local symbol. This is useful for robustly
// checking if a local symbol actually matches a particular definition, even in the presence
// of duplicates.
internal override SyntaxToken IdentifierToken
{
get
{
return _identifierToken;
}
}
#if DEBUG
// We use this to detect infinite recursion in type inference.
private int concurrentTypeResolutions = 0;
#endif
public override TypeWithAnnotations TypeWithAnnotations
{
get
{
if (_type == null)
{
#if DEBUG
concurrentTypeResolutions++;
Debug.Assert(concurrentTypeResolutions < 50);
#endif
TypeWithAnnotations localType = GetTypeSymbol();
SetTypeWithAnnotations(localType);
}
return _type.Value;
}
}
public bool IsVar
{
get
{
if (_typeSyntax == null)
{
// in "e is {} x" there is no syntax corresponding to the type.
return true;
}
if (_typeSyntax.IsVar)
{
bool isVar;
TypeWithAnnotations declType = this.TypeSyntaxBinder.BindTypeOrVarKeyword(_typeSyntax, BindingDiagnosticBag.Discarded, out isVar);
return isVar;
}
return false;
}
}
private TypeWithAnnotations GetTypeSymbol()
{
//
// Note that we drop the diagnostics on the floor! That is because this code is invoked mainly in
// IDE scenarios where we are attempting to use the types of a variable before we have processed
// the code which causes the variable's type to be inferred. In batch compilation, on the
// other hand, local variables have their type inferred, if necessary, in the course of binding
// the statements of a method from top to bottom, and an inferred type is given to a variable
// before the variable's type is used by the compiler.
//
var diagnostics = BindingDiagnosticBag.Discarded;
Binder typeBinder = this.TypeSyntaxBinder;
bool isVar;
TypeWithAnnotations declType;
if (_typeSyntax == null) // In recursive patterns the type may be omitted.
{
isVar = true;
declType = default;
}
else
{
declType = typeBinder.BindTypeOrVarKeyword(_typeSyntax.SkipRef(out _), diagnostics, out isVar);
}
if (isVar)
{
var inferredType = InferTypeOfVarVariable(diagnostics);
// If we got a valid result that was not void then use the inferred type
// else create an error type.
if (inferredType.HasType &&
!inferredType.IsVoidType())
{
declType = inferredType;
}
else
{
declType = TypeWithAnnotations.Create(typeBinder.CreateErrorType("var"));
}
}
Debug.Assert(declType.HasType);
return declType;
}
protected virtual TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics)
{
// TODO: this method must be overridden for pattern variables to bind the
// expression or statement that is the nearest enclosing to the pattern variable's
// declaration. That will cause the type of the pattern variable to be set as a side-effect.
return _type?.Value ?? default;
}
internal void SetTypeWithAnnotations(TypeWithAnnotations newType)
{
Debug.Assert(newType.Type is object);
TypeWithAnnotations? originalType = _type?.Value;
// In the event that we race to set the type of a local, we should
// always deduce the same type, or deduce that the type is an error.
Debug.Assert((object)originalType?.DefaultType == null ||
originalType.Value.DefaultType.IsErrorType() && newType.Type.IsErrorType() ||
originalType.Value.TypeSymbolEquals(newType, TypeCompareKind.ConsiderEverything));
if ((object)_type == null)
{
Interlocked.CompareExchange(ref _type, new TypeWithAnnotations.Boxed(newType), null);
}
}
/// <summary>
/// Gets the locations where the local symbol was originally defined in source.
/// There should not be local symbols from metadata, and there should be only one local variable declared.
/// TODO: check if there are multiple same name local variables - error symbol or local symbol?
/// </summary>
public override ImmutableArray<Location> Locations
{
get
{
return _locations;
}
}
internal sealed override SyntaxNode GetDeclaratorSyntax()
{
return _identifierToken.Parent;
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
SyntaxNode node = _identifierToken.Parent;
#if DEBUG
switch (_declarationKind)
{
case LocalDeclarationKind.RegularVariable:
Debug.Assert(node is VariableDeclaratorSyntax);
break;
case LocalDeclarationKind.Constant:
case LocalDeclarationKind.FixedVariable:
case LocalDeclarationKind.UsingVariable:
Debug.Assert(node is VariableDeclaratorSyntax);
break;
case LocalDeclarationKind.ForEachIterationVariable:
Debug.Assert(node is ForEachStatementSyntax || node is SingleVariableDesignationSyntax);
break;
case LocalDeclarationKind.CatchVariable:
Debug.Assert(node is CatchDeclarationSyntax);
break;
case LocalDeclarationKind.OutVariable:
case LocalDeclarationKind.DeclarationExpressionVariable:
case LocalDeclarationKind.DeconstructionVariable:
case LocalDeclarationKind.PatternVariable:
Debug.Assert(node is SingleVariableDesignationSyntax);
break;
default:
throw ExceptionUtilities.UnexpectedValue(_declarationKind);
}
#endif
return ImmutableArray.Create(node.GetReference());
}
}
internal override bool IsCompilerGenerated
{
get { return false; }
}
internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics)
{
return null;
}
internal override ImmutableBindingDiagnostic<AssemblySymbol> GetConstantValueDiagnostics(BoundExpression boundInitValue)
{
return ImmutableBindingDiagnostic<AssemblySymbol>.Empty;
}
public override RefKind RefKind
{
get { return _refKind; }
}
public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
if (obj == (object)this)
{
return true;
}
// If we're comparing against a symbol that was wrapped and updated for nullable,
// delegate to its handling of equality, rather than our own.
if (obj is UpdatedContainingSymbolAndNullableAnnotationLocal updated)
{
return updated.Equals(this, compareKind);
}
return obj is SourceLocalSymbol symbol
&& symbol._identifierToken.Equals(_identifierToken)
&& symbol._containingSymbol.Equals(_containingSymbol, compareKind);
}
public sealed override int GetHashCode()
{
return Hash.Combine(_identifierToken.GetHashCode(), _containingSymbol.GetHashCode());
}
/// <summary>
/// Symbol for a local whose type can be inferred by binding its initializer.
/// </summary>
private sealed class LocalWithInitializer : SourceLocalSymbol
{
private readonly EqualsValueClauseSyntax _initializer;
private readonly Binder _initializerBinder;
/// <summary>
/// Store the constant value and the corresponding diagnostics together
/// to avoid having the former set by one thread and the latter set by
/// another.
/// </summary>
private EvaluatedConstant _constantTuple;
public LocalWithInitializer(
Symbol containingSymbol,
Binder scopeBinder,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
EqualsValueClauseSyntax initializer,
Binder initializerBinder,
LocalDeclarationKind declarationKind) :
base(containingSymbol, scopeBinder, true, typeSyntax, identifierToken, declarationKind)
{
Debug.Assert(declarationKind != LocalDeclarationKind.ForEachIterationVariable);
Debug.Assert(initializer != null);
_initializer = initializer;
_initializerBinder = initializerBinder;
// default to the current scope in case we need to handle self-referential error cases.
_refEscapeScope = _scopeBinder.LocalScopeDepth;
_valEscapeScope = _scopeBinder.LocalScopeDepth;
}
protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics)
{
BoundExpression initializerOpt = this._initializerBinder.BindInferredVariableInitializer(diagnostics, RefKind, _initializer, _initializer);
return TypeWithAnnotations.Create(initializerOpt?.Type);
}
internal override SyntaxNode ForbiddenZone => _initializer;
/// <summary>
/// Determine the constant value of this local and the corresponding diagnostics.
/// Set both to constantTuple in a single operation for thread safety.
/// </summary>
/// <param name="inProgress">Null for the initial call, non-null if we are in the process of evaluating a constant.</param>
/// <param name="boundInitValue">If we already have the bound node for the initial value, pass it in to avoid recomputing it.</param>
private void MakeConstantTuple(LocalSymbol inProgress, BoundExpression boundInitValue)
{
if (this.IsConst && _constantTuple == null)
{
var value = Microsoft.CodeAnalysis.ConstantValue.Bad;
Location initValueNodeLocation = _initializer.Value.Location;
var diagnostics = BindingDiagnosticBag.GetInstance();
Debug.Assert(inProgress != this);
var type = this.Type;
if (boundInitValue == null)
{
var inProgressBinder = new LocalInProgressBinder(this, this._initializerBinder);
boundInitValue = inProgressBinder.BindVariableOrAutoPropInitializerValue(_initializer, this.RefKind, type, diagnostics);
}
value = ConstantValueUtils.GetAndValidateConstantValue(boundInitValue, this, type, initValueNodeLocation, diagnostics);
Interlocked.CompareExchange(ref _constantTuple, new EvaluatedConstant(value, diagnostics.ToReadOnlyAndFree()), null);
}
}
internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics = null)
{
if (this.IsConst && inProgress == this)
{
if (diagnostics != null)
{
diagnostics.Add(ErrorCode.ERR_CircConstValue, node.GetLocation(), this);
}
return Microsoft.CodeAnalysis.ConstantValue.Bad;
}
MakeConstantTuple(inProgress, boundInitValue: null);
return _constantTuple == null ? null : _constantTuple.Value;
}
internal override ImmutableBindingDiagnostic<AssemblySymbol> GetConstantValueDiagnostics(BoundExpression boundInitValue)
{
Debug.Assert(boundInitValue != null);
MakeConstantTuple(inProgress: null, boundInitValue: boundInitValue);
return _constantTuple == null ? ImmutableBindingDiagnostic<AssemblySymbol>.Empty : _constantTuple.Diagnostics;
}
internal override void SetRefEscape(uint value)
{
Debug.Assert(value <= _refEscapeScope);
_refEscapeScope = value;
}
internal override void SetValEscape(uint value)
{
Debug.Assert(value <= _valEscapeScope);
_valEscapeScope = value;
}
}
/// <summary>
/// Symbol for a foreach iteration variable that can be inferred by binding the
/// collection element type of the foreach.
/// </summary>
private sealed class ForEachLocalSymbol : SourceLocalSymbol
{
private readonly ExpressionSyntax _collection;
public ForEachLocalSymbol(
Symbol containingSymbol,
ForEachLoopBinder scopeBinder,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
ExpressionSyntax collection,
LocalDeclarationKind declarationKind) :
base(containingSymbol, scopeBinder, allowRefKind: true, typeSyntax, identifierToken, declarationKind)
{
Debug.Assert(declarationKind == LocalDeclarationKind.ForEachIterationVariable);
_collection = collection;
}
/// <summary>
/// We initialize the base's ScopeBinder with a ForEachLoopBinder, so it is safe
/// to cast it to that type here.
/// </summary>
private ForEachLoopBinder ForEachLoopBinder => (ForEachLoopBinder)ScopeBinder;
protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics)
{
return ForEachLoopBinder.InferCollectionElementType(diagnostics, _collection);
}
/// <summary>
/// There is no forbidden zone for a foreach loop, because the iteration
/// variable is not in scope in the collection expression.
/// </summary>
internal override SyntaxNode ForbiddenZone => null;
}
/// <summary>
/// Symbol for a deconstruction local that might require type inference.
/// For instance, local <c>x</c> in <c>var (x, y) = ...</c> or <c>(var x, int y) = ...</c>.
/// </summary>
private class DeconstructionLocalSymbol : SourceLocalSymbol
{
private readonly SyntaxNode _deconstruction;
private readonly Binder _nodeBinder;
public DeconstructionLocalSymbol(
Symbol containingSymbol,
Binder scopeBinder,
Binder nodeBinder,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
LocalDeclarationKind declarationKind,
SyntaxNode deconstruction)
: base(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, declarationKind)
{
_deconstruction = deconstruction;
_nodeBinder = nodeBinder;
}
protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics)
{
// Try binding enclosing deconstruction-declaration (the top-level VariableDeclaration), this should force the inference.
switch (_deconstruction.Kind())
{
case SyntaxKind.SimpleAssignmentExpression:
var assignment = (AssignmentExpressionSyntax)_deconstruction;
Debug.Assert(assignment.IsDeconstruction());
DeclarationExpressionSyntax declaration = null;
ExpressionSyntax expression = null;
_nodeBinder.BindDeconstruction(assignment, assignment.Left, assignment.Right, diagnostics, ref declaration, ref expression);
break;
case SyntaxKind.ForEachVariableStatement:
Debug.Assert(this.ScopeBinder.GetBinder((ForEachVariableStatementSyntax)_deconstruction) == _nodeBinder);
_nodeBinder.BindForEachDeconstruction(diagnostics, _nodeBinder);
break;
default:
return TypeWithAnnotations.Create(_nodeBinder.CreateErrorType());
}
return _type.Value;
}
internal override SyntaxNode ForbiddenZone
{
get
{
switch (_deconstruction.Kind())
{
case SyntaxKind.SimpleAssignmentExpression:
return _deconstruction;
case SyntaxKind.ForEachVariableStatement:
// There is no forbidden zone for a foreach statement, because the
// variables are not in scope in the expression.
return null;
default:
return null;
}
}
}
}
private class LocalSymbolWithEnclosingContext : SourceLocalSymbol
{
private readonly SyntaxNode _forbiddenZone;
private readonly Binder _nodeBinder;
private readonly SyntaxNode _nodeToBind;
public LocalSymbolWithEnclosingContext(
Symbol containingSymbol,
Binder scopeBinder,
Binder nodeBinder,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
LocalDeclarationKind declarationKind,
SyntaxNode nodeToBind,
SyntaxNode forbiddenZone)
: base(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, declarationKind)
{
Debug.Assert(
nodeToBind.Kind() == SyntaxKind.CasePatternSwitchLabel ||
nodeToBind.Kind() == SyntaxKind.ThisConstructorInitializer ||
nodeToBind.Kind() == SyntaxKind.BaseConstructorInitializer ||
nodeToBind.Kind() == SyntaxKind.PrimaryConstructorBaseType || // initializer for a record constructor
nodeToBind.Kind() == SyntaxKind.ArgumentList && (nodeToBind.Parent is ConstructorInitializerSyntax || nodeToBind.Parent is PrimaryConstructorBaseTypeSyntax) ||
nodeToBind.Kind() == SyntaxKind.VariableDeclarator ||
nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm ||
nodeToBind.Kind() == SyntaxKind.GotoCaseStatement ||
nodeToBind is ExpressionSyntax);
Debug.Assert(!(nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm) || nodeBinder is SwitchExpressionArmBinder);
this._nodeBinder = nodeBinder;
this._nodeToBind = nodeToBind;
this._forbiddenZone = forbiddenZone;
}
internal override SyntaxNode ForbiddenZone => _forbiddenZone;
// This type is currently used for out variables and pattern variables.
// Pattern variables do not have a forbidden zone, so we only need to produce
// the diagnostic for out variables here.
internal override ErrorCode ForbiddenDiagnostic => ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList;
protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics)
{
switch (_nodeToBind.Kind())
{
case SyntaxKind.ThisConstructorInitializer:
case SyntaxKind.BaseConstructorInitializer:
var initializer = (ConstructorInitializerSyntax)_nodeToBind;
_nodeBinder.BindConstructorInitializer(initializer, diagnostics);
break;
case SyntaxKind.PrimaryConstructorBaseType:
_nodeBinder.BindConstructorInitializer((PrimaryConstructorBaseTypeSyntax)_nodeToBind, diagnostics);
break;
case SyntaxKind.ArgumentList:
switch (_nodeToBind.Parent)
{
case ConstructorInitializerSyntax ctorInitializer:
_nodeBinder.BindConstructorInitializer(ctorInitializer, diagnostics);
break;
case PrimaryConstructorBaseTypeSyntax ctorInitializer:
_nodeBinder.BindConstructorInitializer(ctorInitializer, diagnostics);
break;
default:
throw ExceptionUtilities.UnexpectedValue(_nodeToBind.Parent);
}
break;
case SyntaxKind.CasePatternSwitchLabel:
_nodeBinder.BindPatternSwitchLabelForInference((CasePatternSwitchLabelSyntax)_nodeToBind, diagnostics);
break;
case SyntaxKind.VariableDeclarator:
// This occurs, for example, in
// int x, y[out var Z, 1 is int I];
// for (int x, y[out var Z, 1 is int I]; ;) {}
_nodeBinder.BindDeclaratorArguments((VariableDeclaratorSyntax)_nodeToBind, diagnostics);
break;
case SyntaxKind.SwitchExpressionArm:
var arm = (SwitchExpressionArmSyntax)_nodeToBind;
var armBinder = (SwitchExpressionArmBinder)_nodeBinder;
armBinder.BindSwitchExpressionArm(arm, diagnostics);
break;
case SyntaxKind.GotoCaseStatement:
_nodeBinder.BindStatement((GotoStatementSyntax)_nodeToBind, diagnostics);
break;
default:
_nodeBinder.BindExpression((ExpressionSyntax)_nodeToBind, diagnostics);
break;
}
if (this._type == null)
{
Debug.Assert(this.DeclarationKind == LocalDeclarationKind.DeclarationExpressionVariable);
SetTypeWithAnnotations(TypeWithAnnotations.Create(_nodeBinder.CreateErrorType("var")));
}
return _type.Value;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a local variable in a method body.
/// </summary>
internal class SourceLocalSymbol : LocalSymbol
{
private readonly Binder _scopeBinder;
/// <summary>
/// Might not be a method symbol.
/// </summary>
private readonly Symbol _containingSymbol;
private readonly SyntaxToken _identifierToken;
private readonly ImmutableArray<Location> _locations;
private readonly RefKind _refKind;
private readonly TypeSyntax _typeSyntax;
private readonly LocalDeclarationKind _declarationKind;
private TypeWithAnnotations.Boxed _type;
/// <summary>
/// Scope to which the local can "escape" via aliasing/ref assignment.
/// Not readonly because we can only know escape values after binding the initializer.
/// </summary>
protected uint _refEscapeScope;
/// <summary>
/// Scope to which the local's values can "escape" via ordinary assignments.
/// Not readonly because we can only know escape values after binding the initializer.
/// </summary>
protected uint _valEscapeScope;
private SourceLocalSymbol(
Symbol containingSymbol,
Binder scopeBinder,
bool allowRefKind,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
LocalDeclarationKind declarationKind)
{
Debug.Assert(identifierToken.Kind() != SyntaxKind.None);
Debug.Assert(declarationKind != LocalDeclarationKind.None);
Debug.Assert(scopeBinder != null);
this._scopeBinder = scopeBinder;
this._containingSymbol = containingSymbol;
this._identifierToken = identifierToken;
this._typeSyntax = allowRefKind ? typeSyntax?.SkipRef(out this._refKind) : typeSyntax;
this._declarationKind = declarationKind;
// create this eagerly as it will always be needed for the EnsureSingleDefinition
_locations = ImmutableArray.Create<Location>(identifierToken.GetLocation());
_refEscapeScope = this._refKind == RefKind.None ?
scopeBinder.LocalScopeDepth :
Binder.ExternalScope; // default to returnable, unless there is initializer
// we do not know the type yet.
// assume this is returnable in case we never get to know our type.
_valEscapeScope = Binder.ExternalScope;
}
/// <summary>
/// Binder that owns the scope for the local, the one that returns it in its <see cref="Binder.Locals"/> array.
/// </summary>
internal Binder ScopeBinder
{
get { return _scopeBinder; }
}
internal override SyntaxNode ScopeDesignatorOpt
{
get { return _scopeBinder.ScopeDesignator; }
}
internal override uint RefEscapeScope => _refEscapeScope;
internal override uint ValEscapeScope => _valEscapeScope;
/// <summary>
/// Binder that should be used to bind type syntax for the local.
/// </summary>
internal Binder TypeSyntaxBinder
{
get { return _scopeBinder; } // Scope binder should be good enough for this.
}
// When the variable's type has not yet been inferred,
// don't let the debugger force inference.
internal override string GetDebuggerDisplay()
{
return _type != null
? base.GetDebuggerDisplay()
: $"{this.Kind} <var> ${this.Name}";
}
public static SourceLocalSymbol MakeForeachLocal(
MethodSymbol containingMethod,
ForEachLoopBinder binder,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
ExpressionSyntax collection)
{
return new ForEachLocalSymbol(containingMethod, binder, typeSyntax, identifierToken, collection, LocalDeclarationKind.ForEachIterationVariable);
}
/// <summary>
/// Make a local variable symbol for an element of a deconstruction,
/// which can be inferred (if necessary) by binding the enclosing statement.
/// </summary>
/// <param name="containingSymbol"></param>
/// <param name="scopeBinder">
/// Binder that owns the scope for the local, the one that returns it in its <see cref="Binder.Locals"/> array.
/// </param>
/// <param name="nodeBinder">
/// Enclosing binder for the location where the local is declared.
/// It should be used to bind something at that location.
/// </param>
/// <param name="closestTypeSyntax"></param>
/// <param name="identifierToken"></param>
/// <param name="kind"></param>
/// <param name="deconstruction"></param>
/// <returns></returns>
public static SourceLocalSymbol MakeDeconstructionLocal(
Symbol containingSymbol,
Binder scopeBinder,
Binder nodeBinder,
TypeSyntax closestTypeSyntax,
SyntaxToken identifierToken,
LocalDeclarationKind kind,
SyntaxNode deconstruction)
{
Debug.Assert(closestTypeSyntax != null);
Debug.Assert(nodeBinder != null);
Debug.Assert(closestTypeSyntax.Kind() != SyntaxKind.RefType);
return closestTypeSyntax.IsVar
? new DeconstructionLocalSymbol(containingSymbol, scopeBinder, nodeBinder, closestTypeSyntax, identifierToken, kind, deconstruction)
: new SourceLocalSymbol(containingSymbol, scopeBinder, false, closestTypeSyntax, identifierToken, kind);
}
/// <summary>
/// Make a local variable symbol whose type can be inferred (if necessary) by binding and enclosing construct.
/// </summary>
internal static LocalSymbol MakeLocalSymbolWithEnclosingContext(
Symbol containingSymbol,
Binder scopeBinder,
Binder nodeBinder,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
LocalDeclarationKind kind,
SyntaxNode nodeToBind,
SyntaxNode forbiddenZone)
{
Debug.Assert(
nodeToBind.Kind() == SyntaxKind.CasePatternSwitchLabel ||
nodeToBind.Kind() == SyntaxKind.ThisConstructorInitializer ||
nodeToBind.Kind() == SyntaxKind.BaseConstructorInitializer ||
nodeToBind.Kind() == SyntaxKind.PrimaryConstructorBaseType || // initializer for a record constructor
nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm ||
nodeToBind.Kind() == SyntaxKind.ArgumentList && (nodeToBind.Parent is ConstructorInitializerSyntax || nodeToBind.Parent is PrimaryConstructorBaseTypeSyntax) ||
nodeToBind.Kind() == SyntaxKind.GotoCaseStatement || // for error recovery
nodeToBind.Kind() == SyntaxKind.VariableDeclarator &&
new[] { SyntaxKind.LocalDeclarationStatement, SyntaxKind.ForStatement, SyntaxKind.UsingStatement, SyntaxKind.FixedStatement }.
Contains(nodeToBind.Ancestors().OfType<StatementSyntax>().First().Kind()) ||
nodeToBind is ExpressionSyntax);
Debug.Assert(!(nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm) || nodeBinder is SwitchExpressionArmBinder);
return typeSyntax?.IsVar != false && kind != LocalDeclarationKind.DeclarationExpressionVariable
? new LocalSymbolWithEnclosingContext(containingSymbol, scopeBinder, nodeBinder, typeSyntax, identifierToken, kind, nodeToBind, forbiddenZone)
: new SourceLocalSymbol(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, kind);
}
/// <summary>
/// Make a local variable symbol which can be inferred (if necessary) by binding its initializing expression.
/// </summary>
/// <param name="containingSymbol"></param>
/// <param name="scopeBinder">
/// Binder that owns the scope for the local, the one that returns it in its <see cref="Binder.Locals"/> array.
/// </param>
/// <param name="allowRefKind"></param>
/// <param name="typeSyntax"></param>
/// <param name="identifierToken"></param>
/// <param name="declarationKind"></param>
/// <param name="initializer"></param>
/// <param name="initializerBinderOpt">
/// Binder that should be used to bind initializer, if different from the <paramref name="scopeBinder"/>.
/// </param>
/// <returns></returns>
public static SourceLocalSymbol MakeLocal(
Symbol containingSymbol,
Binder scopeBinder,
bool allowRefKind,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
LocalDeclarationKind declarationKind,
EqualsValueClauseSyntax initializer = null,
Binder initializerBinderOpt = null)
{
Debug.Assert(declarationKind != LocalDeclarationKind.ForEachIterationVariable);
return (initializer != null)
? new LocalWithInitializer(containingSymbol, scopeBinder, typeSyntax, identifierToken, initializer, initializerBinderOpt ?? scopeBinder, declarationKind)
: new SourceLocalSymbol(containingSymbol, scopeBinder, allowRefKind, typeSyntax, identifierToken, declarationKind);
}
internal override bool IsImportedFromMetadata
{
get { return false; }
}
internal override LocalDeclarationKind DeclarationKind
{
get { return _declarationKind; }
}
internal override SynthesizedLocalKind SynthesizedKind
{
get { return SynthesizedLocalKind.UserDefined; }
}
internal override LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax)
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsPinned
{
get
{
// even when dealing with "fixed" locals it is the underlying managed reference that gets pinned
// the pointer variable itself is not pinned.
return false;
}
}
internal virtual void SetRefEscape(uint value)
{
_refEscapeScope = value;
}
internal virtual void SetValEscape(uint value)
{
_valEscapeScope = value;
}
public override Symbol ContainingSymbol
{
get { return _containingSymbol; }
}
/// <summary>
/// Gets the name of the local variable.
/// </summary>
public override string Name
{
get
{
return _identifierToken.ValueText;
}
}
// Get the identifier token that defined this local symbol. This is useful for robustly
// checking if a local symbol actually matches a particular definition, even in the presence
// of duplicates.
internal override SyntaxToken IdentifierToken
{
get
{
return _identifierToken;
}
}
#if DEBUG
// We use this to detect infinite recursion in type inference.
private int concurrentTypeResolutions = 0;
#endif
public override TypeWithAnnotations TypeWithAnnotations
{
get
{
if (_type == null)
{
#if DEBUG
concurrentTypeResolutions++;
Debug.Assert(concurrentTypeResolutions < 50);
#endif
TypeWithAnnotations localType = GetTypeSymbol();
SetTypeWithAnnotations(localType);
}
return _type.Value;
}
}
public bool IsVar
{
get
{
if (_typeSyntax == null)
{
// in "e is {} x" there is no syntax corresponding to the type.
return true;
}
if (_typeSyntax.IsVar)
{
bool isVar;
TypeWithAnnotations declType = this.TypeSyntaxBinder.BindTypeOrVarKeyword(_typeSyntax, BindingDiagnosticBag.Discarded, out isVar);
return isVar;
}
return false;
}
}
private TypeWithAnnotations GetTypeSymbol()
{
//
// Note that we drop the diagnostics on the floor! That is because this code is invoked mainly in
// IDE scenarios where we are attempting to use the types of a variable before we have processed
// the code which causes the variable's type to be inferred. In batch compilation, on the
// other hand, local variables have their type inferred, if necessary, in the course of binding
// the statements of a method from top to bottom, and an inferred type is given to a variable
// before the variable's type is used by the compiler.
//
var diagnostics = BindingDiagnosticBag.Discarded;
Binder typeBinder = this.TypeSyntaxBinder;
bool isVar;
TypeWithAnnotations declType;
if (_typeSyntax == null) // In recursive patterns the type may be omitted.
{
isVar = true;
declType = default;
}
else
{
declType = typeBinder.BindTypeOrVarKeyword(_typeSyntax.SkipRef(out _), diagnostics, out isVar);
}
if (isVar)
{
var inferredType = InferTypeOfVarVariable(diagnostics);
// If we got a valid result that was not void then use the inferred type
// else create an error type.
if (inferredType.HasType &&
!inferredType.IsVoidType())
{
declType = inferredType;
}
else
{
declType = TypeWithAnnotations.Create(typeBinder.CreateErrorType("var"));
}
}
Debug.Assert(declType.HasType);
return declType;
}
protected virtual TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics)
{
// TODO: this method must be overridden for pattern variables to bind the
// expression or statement that is the nearest enclosing to the pattern variable's
// declaration. That will cause the type of the pattern variable to be set as a side-effect.
return _type?.Value ?? default;
}
internal void SetTypeWithAnnotations(TypeWithAnnotations newType)
{
Debug.Assert(newType.Type is object);
TypeWithAnnotations? originalType = _type?.Value;
// In the event that we race to set the type of a local, we should
// always deduce the same type, or deduce that the type is an error.
Debug.Assert((object)originalType?.DefaultType == null ||
originalType.Value.DefaultType.IsErrorType() && newType.Type.IsErrorType() ||
originalType.Value.TypeSymbolEquals(newType, TypeCompareKind.ConsiderEverything));
if ((object)_type == null)
{
Interlocked.CompareExchange(ref _type, new TypeWithAnnotations.Boxed(newType), null);
}
}
/// <summary>
/// Gets the locations where the local symbol was originally defined in source.
/// There should not be local symbols from metadata, and there should be only one local variable declared.
/// TODO: check if there are multiple same name local variables - error symbol or local symbol?
/// </summary>
public override ImmutableArray<Location> Locations
{
get
{
return _locations;
}
}
internal sealed override SyntaxNode GetDeclaratorSyntax()
{
return _identifierToken.Parent;
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
SyntaxNode node = _identifierToken.Parent;
#if DEBUG
switch (_declarationKind)
{
case LocalDeclarationKind.RegularVariable:
Debug.Assert(node is VariableDeclaratorSyntax);
break;
case LocalDeclarationKind.Constant:
case LocalDeclarationKind.FixedVariable:
case LocalDeclarationKind.UsingVariable:
Debug.Assert(node is VariableDeclaratorSyntax);
break;
case LocalDeclarationKind.ForEachIterationVariable:
Debug.Assert(node is ForEachStatementSyntax || node is SingleVariableDesignationSyntax);
break;
case LocalDeclarationKind.CatchVariable:
Debug.Assert(node is CatchDeclarationSyntax);
break;
case LocalDeclarationKind.OutVariable:
case LocalDeclarationKind.DeclarationExpressionVariable:
case LocalDeclarationKind.DeconstructionVariable:
case LocalDeclarationKind.PatternVariable:
Debug.Assert(node is SingleVariableDesignationSyntax);
break;
default:
throw ExceptionUtilities.UnexpectedValue(_declarationKind);
}
#endif
return ImmutableArray.Create(node.GetReference());
}
}
internal override bool IsCompilerGenerated
{
get { return false; }
}
internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics)
{
return null;
}
internal override ImmutableBindingDiagnostic<AssemblySymbol> GetConstantValueDiagnostics(BoundExpression boundInitValue)
{
return ImmutableBindingDiagnostic<AssemblySymbol>.Empty;
}
public override RefKind RefKind
{
get { return _refKind; }
}
public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
if (obj == (object)this)
{
return true;
}
// If we're comparing against a symbol that was wrapped and updated for nullable,
// delegate to its handling of equality, rather than our own.
if (obj is UpdatedContainingSymbolAndNullableAnnotationLocal updated)
{
return updated.Equals(this, compareKind);
}
return obj is SourceLocalSymbol symbol
&& symbol._identifierToken.Equals(_identifierToken)
&& symbol._containingSymbol.Equals(_containingSymbol, compareKind);
}
public sealed override int GetHashCode()
{
return Hash.Combine(_identifierToken.GetHashCode(), _containingSymbol.GetHashCode());
}
/// <summary>
/// Symbol for a local whose type can be inferred by binding its initializer.
/// </summary>
private sealed class LocalWithInitializer : SourceLocalSymbol
{
private readonly EqualsValueClauseSyntax _initializer;
private readonly Binder _initializerBinder;
/// <summary>
/// Store the constant value and the corresponding diagnostics together
/// to avoid having the former set by one thread and the latter set by
/// another.
/// </summary>
private EvaluatedConstant _constantTuple;
public LocalWithInitializer(
Symbol containingSymbol,
Binder scopeBinder,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
EqualsValueClauseSyntax initializer,
Binder initializerBinder,
LocalDeclarationKind declarationKind) :
base(containingSymbol, scopeBinder, true, typeSyntax, identifierToken, declarationKind)
{
Debug.Assert(declarationKind != LocalDeclarationKind.ForEachIterationVariable);
Debug.Assert(initializer != null);
_initializer = initializer;
_initializerBinder = initializerBinder;
// default to the current scope in case we need to handle self-referential error cases.
_refEscapeScope = _scopeBinder.LocalScopeDepth;
_valEscapeScope = _scopeBinder.LocalScopeDepth;
}
protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics)
{
BoundExpression initializerOpt = this._initializerBinder.BindInferredVariableInitializer(diagnostics, RefKind, _initializer, _initializer);
return TypeWithAnnotations.Create(initializerOpt?.Type);
}
internal override SyntaxNode ForbiddenZone => _initializer;
/// <summary>
/// Determine the constant value of this local and the corresponding diagnostics.
/// Set both to constantTuple in a single operation for thread safety.
/// </summary>
/// <param name="inProgress">Null for the initial call, non-null if we are in the process of evaluating a constant.</param>
/// <param name="boundInitValue">If we already have the bound node for the initial value, pass it in to avoid recomputing it.</param>
private void MakeConstantTuple(LocalSymbol inProgress, BoundExpression boundInitValue)
{
if (this.IsConst && _constantTuple == null)
{
var value = Microsoft.CodeAnalysis.ConstantValue.Bad;
Location initValueNodeLocation = _initializer.Value.Location;
var diagnostics = BindingDiagnosticBag.GetInstance();
Debug.Assert(inProgress != this);
var type = this.Type;
if (boundInitValue == null)
{
var inProgressBinder = new LocalInProgressBinder(this, this._initializerBinder);
boundInitValue = inProgressBinder.BindVariableOrAutoPropInitializerValue(_initializer, this.RefKind, type, diagnostics);
}
value = ConstantValueUtils.GetAndValidateConstantValue(boundInitValue, this, type, initValueNodeLocation, diagnostics);
Interlocked.CompareExchange(ref _constantTuple, new EvaluatedConstant(value, diagnostics.ToReadOnlyAndFree()), null);
}
}
internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics = null)
{
if (this.IsConst && inProgress == this)
{
if (diagnostics != null)
{
diagnostics.Add(ErrorCode.ERR_CircConstValue, node.GetLocation(), this);
}
return Microsoft.CodeAnalysis.ConstantValue.Bad;
}
MakeConstantTuple(inProgress, boundInitValue: null);
return _constantTuple == null ? null : _constantTuple.Value;
}
internal override ImmutableBindingDiagnostic<AssemblySymbol> GetConstantValueDiagnostics(BoundExpression boundInitValue)
{
Debug.Assert(boundInitValue != null);
MakeConstantTuple(inProgress: null, boundInitValue: boundInitValue);
return _constantTuple == null ? ImmutableBindingDiagnostic<AssemblySymbol>.Empty : _constantTuple.Diagnostics;
}
internal override void SetRefEscape(uint value)
{
Debug.Assert(value <= _refEscapeScope);
_refEscapeScope = value;
}
internal override void SetValEscape(uint value)
{
Debug.Assert(value <= _valEscapeScope);
_valEscapeScope = value;
}
}
/// <summary>
/// Symbol for a foreach iteration variable that can be inferred by binding the
/// collection element type of the foreach.
/// </summary>
private sealed class ForEachLocalSymbol : SourceLocalSymbol
{
private readonly ExpressionSyntax _collection;
public ForEachLocalSymbol(
Symbol containingSymbol,
ForEachLoopBinder scopeBinder,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
ExpressionSyntax collection,
LocalDeclarationKind declarationKind) :
base(containingSymbol, scopeBinder, allowRefKind: true, typeSyntax, identifierToken, declarationKind)
{
Debug.Assert(declarationKind == LocalDeclarationKind.ForEachIterationVariable);
_collection = collection;
}
/// <summary>
/// We initialize the base's ScopeBinder with a ForEachLoopBinder, so it is safe
/// to cast it to that type here.
/// </summary>
private ForEachLoopBinder ForEachLoopBinder => (ForEachLoopBinder)ScopeBinder;
protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics)
{
return ForEachLoopBinder.InferCollectionElementType(diagnostics, _collection);
}
/// <summary>
/// There is no forbidden zone for a foreach loop, because the iteration
/// variable is not in scope in the collection expression.
/// </summary>
internal override SyntaxNode ForbiddenZone => null;
}
/// <summary>
/// Symbol for a deconstruction local that might require type inference.
/// For instance, local <c>x</c> in <c>var (x, y) = ...</c> or <c>(var x, int y) = ...</c>.
/// </summary>
private class DeconstructionLocalSymbol : SourceLocalSymbol
{
private readonly SyntaxNode _deconstruction;
private readonly Binder _nodeBinder;
public DeconstructionLocalSymbol(
Symbol containingSymbol,
Binder scopeBinder,
Binder nodeBinder,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
LocalDeclarationKind declarationKind,
SyntaxNode deconstruction)
: base(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, declarationKind)
{
_deconstruction = deconstruction;
_nodeBinder = nodeBinder;
}
protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics)
{
// Try binding enclosing deconstruction-declaration (the top-level VariableDeclaration), this should force the inference.
switch (_deconstruction.Kind())
{
case SyntaxKind.SimpleAssignmentExpression:
var assignment = (AssignmentExpressionSyntax)_deconstruction;
Debug.Assert(assignment.IsDeconstruction());
DeclarationExpressionSyntax declaration = null;
ExpressionSyntax expression = null;
_nodeBinder.BindDeconstruction(assignment, assignment.Left, assignment.Right, diagnostics, ref declaration, ref expression);
break;
case SyntaxKind.ForEachVariableStatement:
Debug.Assert(this.ScopeBinder.GetBinder((ForEachVariableStatementSyntax)_deconstruction) == _nodeBinder);
_nodeBinder.BindForEachDeconstruction(diagnostics, _nodeBinder);
break;
default:
return TypeWithAnnotations.Create(_nodeBinder.CreateErrorType());
}
return _type.Value;
}
internal override SyntaxNode ForbiddenZone
{
get
{
switch (_deconstruction.Kind())
{
case SyntaxKind.SimpleAssignmentExpression:
return _deconstruction;
case SyntaxKind.ForEachVariableStatement:
// There is no forbidden zone for a foreach statement, because the
// variables are not in scope in the expression.
return null;
default:
return null;
}
}
}
}
private class LocalSymbolWithEnclosingContext : SourceLocalSymbol
{
private readonly SyntaxNode _forbiddenZone;
private readonly Binder _nodeBinder;
private readonly SyntaxNode _nodeToBind;
public LocalSymbolWithEnclosingContext(
Symbol containingSymbol,
Binder scopeBinder,
Binder nodeBinder,
TypeSyntax typeSyntax,
SyntaxToken identifierToken,
LocalDeclarationKind declarationKind,
SyntaxNode nodeToBind,
SyntaxNode forbiddenZone)
: base(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, declarationKind)
{
Debug.Assert(
nodeToBind.Kind() == SyntaxKind.CasePatternSwitchLabel ||
nodeToBind.Kind() == SyntaxKind.ThisConstructorInitializer ||
nodeToBind.Kind() == SyntaxKind.BaseConstructorInitializer ||
nodeToBind.Kind() == SyntaxKind.PrimaryConstructorBaseType || // initializer for a record constructor
nodeToBind.Kind() == SyntaxKind.ArgumentList && (nodeToBind.Parent is ConstructorInitializerSyntax || nodeToBind.Parent is PrimaryConstructorBaseTypeSyntax) ||
nodeToBind.Kind() == SyntaxKind.VariableDeclarator ||
nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm ||
nodeToBind.Kind() == SyntaxKind.GotoCaseStatement ||
nodeToBind is ExpressionSyntax);
Debug.Assert(!(nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm) || nodeBinder is SwitchExpressionArmBinder);
this._nodeBinder = nodeBinder;
this._nodeToBind = nodeToBind;
this._forbiddenZone = forbiddenZone;
}
internal override SyntaxNode ForbiddenZone => _forbiddenZone;
// This type is currently used for out variables and pattern variables.
// Pattern variables do not have a forbidden zone, so we only need to produce
// the diagnostic for out variables here.
internal override ErrorCode ForbiddenDiagnostic => ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList;
protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics)
{
switch (_nodeToBind.Kind())
{
case SyntaxKind.ThisConstructorInitializer:
case SyntaxKind.BaseConstructorInitializer:
var initializer = (ConstructorInitializerSyntax)_nodeToBind;
_nodeBinder.BindConstructorInitializer(initializer, diagnostics);
break;
case SyntaxKind.PrimaryConstructorBaseType:
_nodeBinder.BindConstructorInitializer((PrimaryConstructorBaseTypeSyntax)_nodeToBind, diagnostics);
break;
case SyntaxKind.ArgumentList:
switch (_nodeToBind.Parent)
{
case ConstructorInitializerSyntax ctorInitializer:
_nodeBinder.BindConstructorInitializer(ctorInitializer, diagnostics);
break;
case PrimaryConstructorBaseTypeSyntax ctorInitializer:
_nodeBinder.BindConstructorInitializer(ctorInitializer, diagnostics);
break;
default:
throw ExceptionUtilities.UnexpectedValue(_nodeToBind.Parent);
}
break;
case SyntaxKind.CasePatternSwitchLabel:
_nodeBinder.BindPatternSwitchLabelForInference((CasePatternSwitchLabelSyntax)_nodeToBind, diagnostics);
break;
case SyntaxKind.VariableDeclarator:
// This occurs, for example, in
// int x, y[out var Z, 1 is int I];
// for (int x, y[out var Z, 1 is int I]; ;) {}
_nodeBinder.BindDeclaratorArguments((VariableDeclaratorSyntax)_nodeToBind, diagnostics);
break;
case SyntaxKind.SwitchExpressionArm:
var arm = (SwitchExpressionArmSyntax)_nodeToBind;
var armBinder = (SwitchExpressionArmBinder)_nodeBinder;
armBinder.BindSwitchExpressionArm(arm, diagnostics);
break;
case SyntaxKind.GotoCaseStatement:
_nodeBinder.BindStatement((GotoStatementSyntax)_nodeToBind, diagnostics);
break;
default:
_nodeBinder.BindExpression((ExpressionSyntax)_nodeToBind, diagnostics);
break;
}
if (this._type == null)
{
Debug.Assert(this.DeclarationKind == LocalDeclarationKind.DeclarationExpressionVariable);
SetTypeWithAnnotations(TypeWithAnnotations.Create(_nodeBinder.CreateErrorType("var")));
}
return _type.Value;
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/Core/Portable/DiaSymReader/Metadata/SymWriterMetadataAdapter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Diagnostics;
namespace Microsoft.DiaSymReader
{
/// <summary>
/// Minimal implementation of IMetadataImport that implements APIs used by SymReader and SymWriter.
/// </summary>
internal sealed unsafe class SymWriterMetadataAdapter : MetadataAdapterBase
{
private readonly ISymWriterMetadataProvider _metadataProvider;
public SymWriterMetadataAdapter(ISymWriterMetadataProvider metadataProvider)
{
Debug.Assert(metadataProvider != null);
_metadataProvider = metadataProvider;
}
public override int GetTokenFromSig(byte* voidPointerSig, int byteCountSig)
{
// Only used when building constant signature.
// We trick SymWriter into embedding NIL token into the PDB if
// we don't have a real signature token matching the constant type.
return 0x11000000;
}
public override int GetTypeDefProps(
int typeDef,
[Out] char* qualifiedName,
int qualifiedNameBufferLength,
[Out] int* qualifiedNameLength,
[Out] TypeAttributes* attributes,
[Out] int* baseType)
{
Debug.Assert(baseType == null);
if (!_metadataProvider.TryGetTypeDefinitionInfo(typeDef, out var namespaceName, out var typeName, out var attrib))
{
return HResult.E_INVALIDARG;
}
if (qualifiedNameLength != null || qualifiedName != null)
{
InteropUtilities.CopyQualifiedTypeName(
qualifiedName,
qualifiedNameBufferLength,
qualifiedNameLength,
namespaceName,
typeName);
}
if (attributes != null)
{
*attributes = attrib;
}
return HResult.S_OK;
}
public override int GetTypeRefProps(
int typeRef,
[Out] int* resolutionScope, // ModuleRef or AssemblyRef
[Out] char* qualifiedName,
int qualifiedNameBufferLength,
[Out] int* qualifiedNameLength)
=> throw new NotImplementedException();
public override int GetNestedClassProps(int nestedClass, out int enclosingClass)
{
return _metadataProvider.TryGetEnclosingType(nestedClass, out enclosingClass) ? HResult.S_OK : HResult.E_FAIL;
}
// The only purpose of this method is to get type name of the method and declaring type token (opaque for SymWriter), everything else is ignored by the SymWriter.
// "mb" is the token passed to OpenMethod. The token is remembered until the corresponding CloseMethod, which passes it to GetMethodProps.
// It's opaque for SymWriter.
public override int GetMethodProps(
int methodDef,
[Out] int* declaringTypeDef,
[Out] char* name,
int nameBufferLength,
[Out] int* nameLength,
[Out] MethodAttributes* attributes,
[Out] byte** signature,
[Out] int* signatureLength,
[Out] int* relativeVirtualAddress,
[Out] MethodImplAttributes* implAttributes)
{
Debug.Assert(attributes == null);
Debug.Assert(signature == null);
Debug.Assert(signatureLength == null);
Debug.Assert(relativeVirtualAddress == null);
Debug.Assert(implAttributes == null);
if (!_metadataProvider.TryGetMethodInfo(methodDef, out var nameStr, out var declaringTypeToken))
{
return HResult.E_INVALIDARG;
}
if (name != null || nameLength != null)
{
// if the buffer is too small to fit the name, truncate the name.
// -1 to account for a NUL terminator.
int adjustedLength = Math.Min(nameStr.Length, nameBufferLength - 1);
if (nameLength != null)
{
// return the length of the possibly truncated name not including NUL
*nameLength = adjustedLength;
}
if (name != null && nameBufferLength > 0)
{
char* dst = name;
for (int i = 0; i < adjustedLength; i++)
{
*dst = nameStr[i];
dst++;
}
*dst = '\0';
}
}
if (declaringTypeDef != null)
{
*declaringTypeDef = declaringTypeToken;
}
return HResult.S_OK;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Diagnostics;
namespace Microsoft.DiaSymReader
{
/// <summary>
/// Minimal implementation of IMetadataImport that implements APIs used by SymReader and SymWriter.
/// </summary>
internal sealed unsafe class SymWriterMetadataAdapter : MetadataAdapterBase
{
private readonly ISymWriterMetadataProvider _metadataProvider;
public SymWriterMetadataAdapter(ISymWriterMetadataProvider metadataProvider)
{
Debug.Assert(metadataProvider != null);
_metadataProvider = metadataProvider;
}
public override int GetTokenFromSig(byte* voidPointerSig, int byteCountSig)
{
// Only used when building constant signature.
// We trick SymWriter into embedding NIL token into the PDB if
// we don't have a real signature token matching the constant type.
return 0x11000000;
}
public override int GetTypeDefProps(
int typeDef,
[Out] char* qualifiedName,
int qualifiedNameBufferLength,
[Out] int* qualifiedNameLength,
[Out] TypeAttributes* attributes,
[Out] int* baseType)
{
Debug.Assert(baseType == null);
if (!_metadataProvider.TryGetTypeDefinitionInfo(typeDef, out var namespaceName, out var typeName, out var attrib))
{
return HResult.E_INVALIDARG;
}
if (qualifiedNameLength != null || qualifiedName != null)
{
InteropUtilities.CopyQualifiedTypeName(
qualifiedName,
qualifiedNameBufferLength,
qualifiedNameLength,
namespaceName,
typeName);
}
if (attributes != null)
{
*attributes = attrib;
}
return HResult.S_OK;
}
public override int GetTypeRefProps(
int typeRef,
[Out] int* resolutionScope, // ModuleRef or AssemblyRef
[Out] char* qualifiedName,
int qualifiedNameBufferLength,
[Out] int* qualifiedNameLength)
=> throw new NotImplementedException();
public override int GetNestedClassProps(int nestedClass, out int enclosingClass)
{
return _metadataProvider.TryGetEnclosingType(nestedClass, out enclosingClass) ? HResult.S_OK : HResult.E_FAIL;
}
// The only purpose of this method is to get type name of the method and declaring type token (opaque for SymWriter), everything else is ignored by the SymWriter.
// "mb" is the token passed to OpenMethod. The token is remembered until the corresponding CloseMethod, which passes it to GetMethodProps.
// It's opaque for SymWriter.
public override int GetMethodProps(
int methodDef,
[Out] int* declaringTypeDef,
[Out] char* name,
int nameBufferLength,
[Out] int* nameLength,
[Out] MethodAttributes* attributes,
[Out] byte** signature,
[Out] int* signatureLength,
[Out] int* relativeVirtualAddress,
[Out] MethodImplAttributes* implAttributes)
{
Debug.Assert(attributes == null);
Debug.Assert(signature == null);
Debug.Assert(signatureLength == null);
Debug.Assert(relativeVirtualAddress == null);
Debug.Assert(implAttributes == null);
if (!_metadataProvider.TryGetMethodInfo(methodDef, out var nameStr, out var declaringTypeToken))
{
return HResult.E_INVALIDARG;
}
if (name != null || nameLength != null)
{
// if the buffer is too small to fit the name, truncate the name.
// -1 to account for a NUL terminator.
int adjustedLength = Math.Min(nameStr.Length, nameBufferLength - 1);
if (nameLength != null)
{
// return the length of the possibly truncated name not including NUL
*nameLength = adjustedLength;
}
if (name != null && nameBufferLength > 0)
{
char* dst = name;
for (int i = 0; i < adjustedLength; i++)
{
*dst = nameStr[i];
dst++;
}
*dst = '\0';
}
}
if (declaringTypeDef != null)
{
*declaringTypeDef = declaringTypeToken;
}
return HResult.S_OK;
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./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 | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Features/Core/Portable/GenerateConstructorFromMembers/AbstractGenerateConstructorFromMembersCodeRefactoringProvider.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.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers
{
internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider
{
private class State
{
public TextSpan TextSpan { get; private set; }
public IMethodSymbol? MatchingConstructor { get; private set; }
public IMethodSymbol? DelegatedConstructor { get; private set; }
[NotNull]
public INamedTypeSymbol? ContainingType { get; private set; }
public ImmutableArray<ISymbol> SelectedMembers { get; private set; }
public ImmutableArray<IParameterSymbol> Parameters { get; private set; }
public bool IsContainedInUnsafeType { get; private set; }
public static async Task<State?> TryGenerateAsync(
AbstractGenerateConstructorFromMembersCodeRefactoringProvider service,
Document document,
TextSpan textSpan,
INamedTypeSymbol containingType,
ImmutableArray<ISymbol> selectedMembers,
CancellationToken cancellationToken)
{
var state = new State();
if (!await state.TryInitializeAsync(service, document, textSpan, containingType, selectedMembers, cancellationToken).ConfigureAwait(false))
{
return null;
}
return state;
}
private async Task<bool> TryInitializeAsync(
AbstractGenerateConstructorFromMembersCodeRefactoringProvider service,
Document document,
TextSpan textSpan,
INamedTypeSymbol containingType,
ImmutableArray<ISymbol> selectedMembers,
CancellationToken cancellationToken)
{
if (!selectedMembers.All(IsWritableInstanceFieldOrProperty))
{
return false;
}
SelectedMembers = selectedMembers;
ContainingType = containingType;
TextSpan = textSpan;
if (ContainingType == null || ContainingType.TypeKind == TypeKind.Interface)
{
return false;
}
IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(containingType);
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
Parameters = DetermineParameters(selectedMembers, rules);
MatchingConstructor = GetMatchingConstructorBasedOnParameterTypes(ContainingType, Parameters);
// We are going to create a new contructor and pass part of the parameters into DelegatedConstructor,
// so parameters should be compared based on types since we don't want get a type mismatch error after the new constructor is genreated.
DelegatedConstructor = GetDelegatedConstructorBasedOnParameterTypes(ContainingType, Parameters);
return true;
}
private static IMethodSymbol? GetDelegatedConstructorBasedOnParameterTypes(
INamedTypeSymbol containingType,
ImmutableArray<IParameterSymbol> parameters)
{
var q =
from c in containingType.InstanceConstructors
orderby c.Parameters.Length descending
where c.Parameters.Length > 0 && c.Parameters.Length < parameters.Length
where c.Parameters.All(p => p.RefKind == RefKind.None) && !c.Parameters.Any(p => p.IsParams)
let constructorTypes = c.Parameters.Select(p => p.Type)
let symbolTypes = parameters.Take(c.Parameters.Length).Select(p => p.Type)
where constructorTypes.SequenceEqual(symbolTypes, SymbolEqualityComparer.Default)
select c;
return q.FirstOrDefault();
}
private static IMethodSymbol? GetMatchingConstructorBasedOnParameterTypes(INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters)
=> containingType.InstanceConstructors.FirstOrDefault(c => MatchesConstructorBasedOnParameterTypes(c, parameters));
private static bool MatchesConstructorBasedOnParameterTypes(IMethodSymbol constructor, ImmutableArray<IParameterSymbol> parameters)
=> parameters.Select(p => p.Type).SequenceEqual(constructor.Parameters.Select(p => p.Type));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers
{
internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider
{
private class State
{
public TextSpan TextSpan { get; private set; }
public IMethodSymbol? MatchingConstructor { get; private set; }
public IMethodSymbol? DelegatedConstructor { get; private set; }
[NotNull]
public INamedTypeSymbol? ContainingType { get; private set; }
public ImmutableArray<ISymbol> SelectedMembers { get; private set; }
public ImmutableArray<IParameterSymbol> Parameters { get; private set; }
public bool IsContainedInUnsafeType { get; private set; }
public static async Task<State?> TryGenerateAsync(
AbstractGenerateConstructorFromMembersCodeRefactoringProvider service,
Document document,
TextSpan textSpan,
INamedTypeSymbol containingType,
ImmutableArray<ISymbol> selectedMembers,
CancellationToken cancellationToken)
{
var state = new State();
if (!await state.TryInitializeAsync(service, document, textSpan, containingType, selectedMembers, cancellationToken).ConfigureAwait(false))
{
return null;
}
return state;
}
private async Task<bool> TryInitializeAsync(
AbstractGenerateConstructorFromMembersCodeRefactoringProvider service,
Document document,
TextSpan textSpan,
INamedTypeSymbol containingType,
ImmutableArray<ISymbol> selectedMembers,
CancellationToken cancellationToken)
{
if (!selectedMembers.All(IsWritableInstanceFieldOrProperty))
{
return false;
}
SelectedMembers = selectedMembers;
ContainingType = containingType;
TextSpan = textSpan;
if (ContainingType == null || ContainingType.TypeKind == TypeKind.Interface)
{
return false;
}
IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(containingType);
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
Parameters = DetermineParameters(selectedMembers, rules);
MatchingConstructor = GetMatchingConstructorBasedOnParameterTypes(ContainingType, Parameters);
// We are going to create a new contructor and pass part of the parameters into DelegatedConstructor,
// so parameters should be compared based on types since we don't want get a type mismatch error after the new constructor is genreated.
DelegatedConstructor = GetDelegatedConstructorBasedOnParameterTypes(ContainingType, Parameters);
return true;
}
private static IMethodSymbol? GetDelegatedConstructorBasedOnParameterTypes(
INamedTypeSymbol containingType,
ImmutableArray<IParameterSymbol> parameters)
{
var q =
from c in containingType.InstanceConstructors
orderby c.Parameters.Length descending
where c.Parameters.Length > 0 && c.Parameters.Length < parameters.Length
where c.Parameters.All(p => p.RefKind == RefKind.None) && !c.Parameters.Any(p => p.IsParams)
let constructorTypes = c.Parameters.Select(p => p.Type)
let symbolTypes = parameters.Take(c.Parameters.Length).Select(p => p.Type)
where constructorTypes.SequenceEqual(symbolTypes, SymbolEqualityComparer.Default)
select c;
return q.FirstOrDefault();
}
private static IMethodSymbol? GetMatchingConstructorBasedOnParameterTypes(INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters)
=> containingType.InstanceConstructors.FirstOrDefault(c => MatchesConstructorBasedOnParameterTypes(c, parameters));
private static bool MatchesConstructorBasedOnParameterTypes(IMethodSymbol constructor, ImmutableArray<IParameterSymbol> parameters)
=> parameters.Select(p => p.Type).SequenceEqual(constructor.Parameters.Select(p => p.Type));
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.ParsedSyntaxTree.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class CSharpSyntaxTree
{
private class ParsedSyntaxTree : CSharpSyntaxTree
{
private readonly CSharpParseOptions _options;
private readonly string _path;
private readonly CSharpSyntaxNode _root;
private readonly bool _hasCompilationUnitRoot;
private readonly Encoding? _encodingOpt;
private readonly SourceHashAlgorithm _checksumAlgorithm;
private readonly ImmutableDictionary<string, ReportDiagnostic> _diagnosticOptions;
private SourceText? _lazyText;
internal ParsedSyntaxTree(
SourceText? textOpt,
Encoding? encodingOpt,
SourceHashAlgorithm checksumAlgorithm,
string path,
CSharpParseOptions options,
CSharpSyntaxNode root,
Syntax.InternalSyntax.DirectiveStack directives,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
bool cloneRoot)
{
Debug.Assert(root != null);
Debug.Assert(options != null);
Debug.Assert(textOpt == null || textOpt.Encoding == encodingOpt && textOpt.ChecksumAlgorithm == checksumAlgorithm);
_lazyText = textOpt;
_encodingOpt = encodingOpt ?? textOpt?.Encoding;
_checksumAlgorithm = checksumAlgorithm;
_options = options;
_path = path ?? string.Empty;
_root = cloneRoot ? this.CloneNodeAsRoot(root) : root;
_hasCompilationUnitRoot = root.Kind() == SyntaxKind.CompilationUnit;
_diagnosticOptions = diagnosticOptions ?? EmptyDiagnosticOptions;
this.SetDirectiveStack(directives);
}
public override string FilePath
{
get { return _path; }
}
public override SourceText GetText(CancellationToken cancellationToken)
{
if (_lazyText == null)
{
Interlocked.CompareExchange(ref _lazyText, this.GetRoot(cancellationToken).GetText(_encodingOpt, _checksumAlgorithm), null);
}
return _lazyText;
}
public override bool TryGetText([NotNullWhen(true)] out SourceText? text)
{
text = _lazyText;
return text != null;
}
public override Encoding? Encoding
{
get { return _encodingOpt; }
}
public override int Length
{
get { return _root.FullSpan.Length; }
}
public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken)
{
return _root;
}
public override bool TryGetRoot(out CSharpSyntaxNode root)
{
root = _root;
return true;
}
public override bool HasCompilationUnitRoot
{
get
{
return _hasCompilationUnitRoot;
}
}
public override CSharpParseOptions Options
{
get
{
return _options;
}
}
[Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public override ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions => _diagnosticOptions;
public override SyntaxReference GetReference(SyntaxNode node)
{
return new SimpleSyntaxReference(node);
}
public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options)
{
if (ReferenceEquals(_root, root) && ReferenceEquals(_options, options))
{
return this;
}
return new ParsedSyntaxTree(
textOpt: null,
_encodingOpt,
_checksumAlgorithm,
_path,
(CSharpParseOptions)options,
(CSharpSyntaxNode)root,
_directives,
_diagnosticOptions,
cloneRoot: true);
}
public override SyntaxTree WithFilePath(string path)
{
if (_path == path)
{
return this;
}
return new ParsedSyntaxTree(
_lazyText,
_encodingOpt,
_checksumAlgorithm,
path,
_options,
_root,
_directives,
_diagnosticOptions,
cloneRoot: true);
}
[Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public override SyntaxTree WithDiagnosticOptions(ImmutableDictionary<string, ReportDiagnostic> options)
{
if (options is null)
{
options = EmptyDiagnosticOptions;
}
if (ReferenceEquals(_diagnosticOptions, options))
{
return this;
}
return new ParsedSyntaxTree(
_lazyText,
_encodingOpt,
_checksumAlgorithm,
_path,
_options,
_root,
_directives,
options,
cloneRoot: true);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class CSharpSyntaxTree
{
private class ParsedSyntaxTree : CSharpSyntaxTree
{
private readonly CSharpParseOptions _options;
private readonly string _path;
private readonly CSharpSyntaxNode _root;
private readonly bool _hasCompilationUnitRoot;
private readonly Encoding? _encodingOpt;
private readonly SourceHashAlgorithm _checksumAlgorithm;
private readonly ImmutableDictionary<string, ReportDiagnostic> _diagnosticOptions;
private SourceText? _lazyText;
internal ParsedSyntaxTree(
SourceText? textOpt,
Encoding? encodingOpt,
SourceHashAlgorithm checksumAlgorithm,
string path,
CSharpParseOptions options,
CSharpSyntaxNode root,
Syntax.InternalSyntax.DirectiveStack directives,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
bool cloneRoot)
{
Debug.Assert(root != null);
Debug.Assert(options != null);
Debug.Assert(textOpt == null || textOpt.Encoding == encodingOpt && textOpt.ChecksumAlgorithm == checksumAlgorithm);
_lazyText = textOpt;
_encodingOpt = encodingOpt ?? textOpt?.Encoding;
_checksumAlgorithm = checksumAlgorithm;
_options = options;
_path = path ?? string.Empty;
_root = cloneRoot ? this.CloneNodeAsRoot(root) : root;
_hasCompilationUnitRoot = root.Kind() == SyntaxKind.CompilationUnit;
_diagnosticOptions = diagnosticOptions ?? EmptyDiagnosticOptions;
this.SetDirectiveStack(directives);
}
public override string FilePath
{
get { return _path; }
}
public override SourceText GetText(CancellationToken cancellationToken)
{
if (_lazyText == null)
{
Interlocked.CompareExchange(ref _lazyText, this.GetRoot(cancellationToken).GetText(_encodingOpt, _checksumAlgorithm), null);
}
return _lazyText;
}
public override bool TryGetText([NotNullWhen(true)] out SourceText? text)
{
text = _lazyText;
return text != null;
}
public override Encoding? Encoding
{
get { return _encodingOpt; }
}
public override int Length
{
get { return _root.FullSpan.Length; }
}
public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken)
{
return _root;
}
public override bool TryGetRoot(out CSharpSyntaxNode root)
{
root = _root;
return true;
}
public override bool HasCompilationUnitRoot
{
get
{
return _hasCompilationUnitRoot;
}
}
public override CSharpParseOptions Options
{
get
{
return _options;
}
}
[Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public override ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions => _diagnosticOptions;
public override SyntaxReference GetReference(SyntaxNode node)
{
return new SimpleSyntaxReference(node);
}
public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options)
{
if (ReferenceEquals(_root, root) && ReferenceEquals(_options, options))
{
return this;
}
return new ParsedSyntaxTree(
textOpt: null,
_encodingOpt,
_checksumAlgorithm,
_path,
(CSharpParseOptions)options,
(CSharpSyntaxNode)root,
_directives,
_diagnosticOptions,
cloneRoot: true);
}
public override SyntaxTree WithFilePath(string path)
{
if (_path == path)
{
return this;
}
return new ParsedSyntaxTree(
_lazyText,
_encodingOpt,
_checksumAlgorithm,
path,
_options,
_root,
_directives,
_diagnosticOptions,
cloneRoot: true);
}
[Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public override SyntaxTree WithDiagnosticOptions(ImmutableDictionary<string, ReportDiagnostic> options)
{
if (options is null)
{
options = EmptyDiagnosticOptions;
}
if (ReferenceEquals(_diagnosticOptions, options))
{
return this;
}
return new ParsedSyntaxTree(
_lazyText,
_encodingOpt,
_checksumAlgorithm,
_path,
_options,
_root,
_directives,
options,
cloneRoot: true);
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/CSharp/Portable/BoundTree/TupleBinaryOperatorInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal enum TupleBinaryOperatorInfoKind
{
Single,
NullNull,
Multiple
}
/// <summary>
/// A tree of binary operators for tuple comparisons.
///
/// For <c>(a, (b, c)) == (d, (e, f))</c> we'll hold a Multiple with two elements.
/// The first element is a Single (describing the binary operator and conversions that are involved in <c>a == d</c>).
/// The second element is a Multiple containing two Singles (one for the <c>b == e</c> comparison and the other for <c>c == f</c>).
/// </summary>
internal abstract class TupleBinaryOperatorInfo
{
internal abstract TupleBinaryOperatorInfoKind InfoKind { get; }
internal readonly TypeSymbol? LeftConvertedTypeOpt;
internal readonly TypeSymbol? RightConvertedTypeOpt;
#if DEBUG
internal abstract TreeDumperNode DumpCore();
internal string Dump() => TreeDumper.DumpCompact(DumpCore());
#endif
private TupleBinaryOperatorInfo(TypeSymbol? leftConvertedTypeOpt, TypeSymbol? rightConvertedTypeOpt)
{
LeftConvertedTypeOpt = leftConvertedTypeOpt;
RightConvertedTypeOpt = rightConvertedTypeOpt;
}
/// <summary>
/// Holds the information for an element-wise comparison (like <c>a == b</c> as part of <c>(a, ...) == (b, ...)</c>)
/// </summary>
internal class Single : TupleBinaryOperatorInfo
{
internal readonly BinaryOperatorKind Kind;
internal readonly MethodSymbol? MethodSymbolOpt; // User-defined comparison operator, if applicable
internal readonly TypeSymbol? ConstrainedToTypeOpt;
internal readonly Conversion ConversionForBool; // If a conversion to bool exists, then no operator needed. If an operator is needed, this holds the conversion for input to that operator.
internal readonly UnaryOperatorSignature BoolOperator; // Information for op_true or op_false
internal Single(
TypeSymbol? leftConvertedTypeOpt,
TypeSymbol? rightConvertedTypeOpt,
BinaryOperatorKind kind,
MethodSymbol? methodSymbolOpt,
TypeSymbol? constrainedToTypeOpt,
Conversion conversionForBool, UnaryOperatorSignature boolOperator) : base(leftConvertedTypeOpt, rightConvertedTypeOpt)
{
Kind = kind;
MethodSymbolOpt = methodSymbolOpt;
ConstrainedToTypeOpt = constrainedToTypeOpt;
ConversionForBool = conversionForBool;
BoolOperator = boolOperator;
Debug.Assert(Kind.IsUserDefined() == (MethodSymbolOpt is { }));
}
internal override TupleBinaryOperatorInfoKind InfoKind
=> TupleBinaryOperatorInfoKind.Single;
public override string ToString()
=> $"binaryOperatorKind: {Kind}";
#if DEBUG
internal override TreeDumperNode DumpCore()
{
var sub = new List<TreeDumperNode>();
if (MethodSymbolOpt is { })
{
sub.Add(new TreeDumperNode("methodSymbolOpt", MethodSymbolOpt.ToDisplayString(), null));
}
sub.Add(new TreeDumperNode("leftConversion", LeftConvertedTypeOpt?.ToDisplayString(), null));
sub.Add(new TreeDumperNode("rightConversion", RightConvertedTypeOpt?.ToDisplayString(), null));
return new TreeDumperNode("nested", Kind, sub);
}
#endif
}
/// <summary>
/// Holds the information for a tuple comparison, either at the top-level (like <c>(a, b) == ...</c>) or nested (like <c>(..., (a, b)) == (..., ...)</c>).
/// </summary>
internal class Multiple : TupleBinaryOperatorInfo
{
internal readonly ImmutableArray<TupleBinaryOperatorInfo> Operators;
internal static readonly Multiple ErrorInstance =
new Multiple(operators: ImmutableArray<TupleBinaryOperatorInfo>.Empty, leftConvertedTypeOpt: null, rightConvertedTypeOpt: null);
internal Multiple(ImmutableArray<TupleBinaryOperatorInfo> operators, TypeSymbol? leftConvertedTypeOpt, TypeSymbol? rightConvertedTypeOpt)
: base(leftConvertedTypeOpt, rightConvertedTypeOpt)
{
Debug.Assert(leftConvertedTypeOpt is null || leftConvertedTypeOpt.StrippedType().IsTupleType);
Debug.Assert(rightConvertedTypeOpt is null || rightConvertedTypeOpt.StrippedType().IsTupleType);
Debug.Assert(!operators.IsDefault);
Debug.Assert(operators.IsEmpty || operators.Length > 1); // an empty array is used for error cases, otherwise tuples must have cardinality > 1
Operators = operators;
}
internal override TupleBinaryOperatorInfoKind InfoKind
=> TupleBinaryOperatorInfoKind.Multiple;
#if DEBUG
internal override TreeDumperNode DumpCore()
{
var sub = new List<TreeDumperNode>();
sub.Add(new TreeDumperNode($"nestedOperators[{Operators.Length}]", null,
Operators.SelectAsArray(c => c.DumpCore())));
return new TreeDumperNode("nested", null, sub);
}
#endif
}
/// <summary>
/// Represents an element-wise null/null comparison.
/// For instance, <c>(null, ...) == (null, ...)</c>.
/// </summary>
internal class NullNull : TupleBinaryOperatorInfo
{
internal readonly BinaryOperatorKind Kind;
internal NullNull(BinaryOperatorKind kind)
: base(leftConvertedTypeOpt: null, rightConvertedTypeOpt: null)
{
Kind = kind;
}
internal override TupleBinaryOperatorInfoKind InfoKind
=> TupleBinaryOperatorInfoKind.NullNull;
#if DEBUG
internal override TreeDumperNode DumpCore()
{
return new TreeDumperNode("nullnull", value: Kind, children: null);
}
#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.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal enum TupleBinaryOperatorInfoKind
{
Single,
NullNull,
Multiple
}
/// <summary>
/// A tree of binary operators for tuple comparisons.
///
/// For <c>(a, (b, c)) == (d, (e, f))</c> we'll hold a Multiple with two elements.
/// The first element is a Single (describing the binary operator and conversions that are involved in <c>a == d</c>).
/// The second element is a Multiple containing two Singles (one for the <c>b == e</c> comparison and the other for <c>c == f</c>).
/// </summary>
internal abstract class TupleBinaryOperatorInfo
{
internal abstract TupleBinaryOperatorInfoKind InfoKind { get; }
internal readonly TypeSymbol? LeftConvertedTypeOpt;
internal readonly TypeSymbol? RightConvertedTypeOpt;
#if DEBUG
internal abstract TreeDumperNode DumpCore();
internal string Dump() => TreeDumper.DumpCompact(DumpCore());
#endif
private TupleBinaryOperatorInfo(TypeSymbol? leftConvertedTypeOpt, TypeSymbol? rightConvertedTypeOpt)
{
LeftConvertedTypeOpt = leftConvertedTypeOpt;
RightConvertedTypeOpt = rightConvertedTypeOpt;
}
/// <summary>
/// Holds the information for an element-wise comparison (like <c>a == b</c> as part of <c>(a, ...) == (b, ...)</c>)
/// </summary>
internal class Single : TupleBinaryOperatorInfo
{
internal readonly BinaryOperatorKind Kind;
internal readonly MethodSymbol? MethodSymbolOpt; // User-defined comparison operator, if applicable
internal readonly TypeSymbol? ConstrainedToTypeOpt;
internal readonly Conversion ConversionForBool; // If a conversion to bool exists, then no operator needed. If an operator is needed, this holds the conversion for input to that operator.
internal readonly UnaryOperatorSignature BoolOperator; // Information for op_true or op_false
internal Single(
TypeSymbol? leftConvertedTypeOpt,
TypeSymbol? rightConvertedTypeOpt,
BinaryOperatorKind kind,
MethodSymbol? methodSymbolOpt,
TypeSymbol? constrainedToTypeOpt,
Conversion conversionForBool, UnaryOperatorSignature boolOperator) : base(leftConvertedTypeOpt, rightConvertedTypeOpt)
{
Kind = kind;
MethodSymbolOpt = methodSymbolOpt;
ConstrainedToTypeOpt = constrainedToTypeOpt;
ConversionForBool = conversionForBool;
BoolOperator = boolOperator;
Debug.Assert(Kind.IsUserDefined() == (MethodSymbolOpt is { }));
}
internal override TupleBinaryOperatorInfoKind InfoKind
=> TupleBinaryOperatorInfoKind.Single;
public override string ToString()
=> $"binaryOperatorKind: {Kind}";
#if DEBUG
internal override TreeDumperNode DumpCore()
{
var sub = new List<TreeDumperNode>();
if (MethodSymbolOpt is { })
{
sub.Add(new TreeDumperNode("methodSymbolOpt", MethodSymbolOpt.ToDisplayString(), null));
}
sub.Add(new TreeDumperNode("leftConversion", LeftConvertedTypeOpt?.ToDisplayString(), null));
sub.Add(new TreeDumperNode("rightConversion", RightConvertedTypeOpt?.ToDisplayString(), null));
return new TreeDumperNode("nested", Kind, sub);
}
#endif
}
/// <summary>
/// Holds the information for a tuple comparison, either at the top-level (like <c>(a, b) == ...</c>) or nested (like <c>(..., (a, b)) == (..., ...)</c>).
/// </summary>
internal class Multiple : TupleBinaryOperatorInfo
{
internal readonly ImmutableArray<TupleBinaryOperatorInfo> Operators;
internal static readonly Multiple ErrorInstance =
new Multiple(operators: ImmutableArray<TupleBinaryOperatorInfo>.Empty, leftConvertedTypeOpt: null, rightConvertedTypeOpt: null);
internal Multiple(ImmutableArray<TupleBinaryOperatorInfo> operators, TypeSymbol? leftConvertedTypeOpt, TypeSymbol? rightConvertedTypeOpt)
: base(leftConvertedTypeOpt, rightConvertedTypeOpt)
{
Debug.Assert(leftConvertedTypeOpt is null || leftConvertedTypeOpt.StrippedType().IsTupleType);
Debug.Assert(rightConvertedTypeOpt is null || rightConvertedTypeOpt.StrippedType().IsTupleType);
Debug.Assert(!operators.IsDefault);
Debug.Assert(operators.IsEmpty || operators.Length > 1); // an empty array is used for error cases, otherwise tuples must have cardinality > 1
Operators = operators;
}
internal override TupleBinaryOperatorInfoKind InfoKind
=> TupleBinaryOperatorInfoKind.Multiple;
#if DEBUG
internal override TreeDumperNode DumpCore()
{
var sub = new List<TreeDumperNode>();
sub.Add(new TreeDumperNode($"nestedOperators[{Operators.Length}]", null,
Operators.SelectAsArray(c => c.DumpCore())));
return new TreeDumperNode("nested", null, sub);
}
#endif
}
/// <summary>
/// Represents an element-wise null/null comparison.
/// For instance, <c>(null, ...) == (null, ...)</c>.
/// </summary>
internal class NullNull : TupleBinaryOperatorInfo
{
internal readonly BinaryOperatorKind Kind;
internal NullNull(BinaryOperatorKind kind)
: base(leftConvertedTypeOpt: null, rightConvertedTypeOpt: null)
{
Kind = kind;
}
internal override TupleBinaryOperatorInfoKind InfoKind
=> TupleBinaryOperatorInfoKind.NullNull;
#if DEBUG
internal override TreeDumperNode DumpCore()
{
return new TreeDumperNode("nullnull", value: Kind, children: null);
}
#endif
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/EditorFeatures/Core/Shared/Extensions/TelemetryExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Globalization;
using System.Linq;
using Microsoft.CodeAnalysis.CodeFixes;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static class TelemetryExtensions
{
public static Guid GetTelemetryId(this Type type, short scope = 0)
{
type = GetTypeForTelemetry(type);
Contract.ThrowIfNull(type.FullName);
// AssemblyQualifiedName will change across version numbers, FullName won't
// Use a stable hashing algorithm (FNV) that doesn't depend on platform
// or .NET implementation.
var suffix = Roslyn.Utilities.Hash.GetFNVHashCode(type.FullName);
// Suffix is the remaining 8 bytes, and the hash code only makes up 4. Pad
// the remainder with an empty byte array
var suffixBytes = BitConverter.GetBytes(suffix).Concat(new byte[4]).ToArray();
return new Guid(0, scope, 0, suffixBytes);
}
public static Type GetTypeForTelemetry(this Type type)
=> type.IsConstructedGenericType ? type.GetGenericTypeDefinition() : type;
public static short GetScopeIdForTelemetry(this FixAllScope scope)
=> (short)(scope switch
{
FixAllScope.Document => 1,
FixAllScope.Project => 2,
FixAllScope.Solution => 3,
_ => 4,
});
public static string GetTelemetryDiagnosticID(this Diagnostic diagnostic)
{
// we log diagnostic id as it is if it is from us
if (diagnostic.Descriptor.CustomTags.Any(t => t == WellKnownDiagnosticTags.Telemetry))
{
return diagnostic.Id;
}
// if it is from third party, we use hashcode
return diagnostic.GetHashCode().ToString(CultureInfo.InvariantCulture);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Globalization;
using System.Linq;
using Microsoft.CodeAnalysis.CodeFixes;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static class TelemetryExtensions
{
public static Guid GetTelemetryId(this Type type, short scope = 0)
{
type = GetTypeForTelemetry(type);
Contract.ThrowIfNull(type.FullName);
// AssemblyQualifiedName will change across version numbers, FullName won't
// Use a stable hashing algorithm (FNV) that doesn't depend on platform
// or .NET implementation.
var suffix = Roslyn.Utilities.Hash.GetFNVHashCode(type.FullName);
// Suffix is the remaining 8 bytes, and the hash code only makes up 4. Pad
// the remainder with an empty byte array
var suffixBytes = BitConverter.GetBytes(suffix).Concat(new byte[4]).ToArray();
return new Guid(0, scope, 0, suffixBytes);
}
public static Type GetTypeForTelemetry(this Type type)
=> type.IsConstructedGenericType ? type.GetGenericTypeDefinition() : type;
public static short GetScopeIdForTelemetry(this FixAllScope scope)
=> (short)(scope switch
{
FixAllScope.Document => 1,
FixAllScope.Project => 2,
FixAllScope.Solution => 3,
_ => 4,
});
public static string GetTelemetryDiagnosticID(this Diagnostic diagnostic)
{
// we log diagnostic id as it is if it is from us
if (diagnostic.Descriptor.CustomTags.Any(t => t == WellKnownDiagnosticTags.Telemetry))
{
return diagnostic.Id;
}
// if it is from third party, we use hashcode
return diagnostic.GetHashCode().ToString(CultureInfo.InvariantCulture);
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicArgumentProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicArgumentProvider : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicArgumentProvider(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicArgumentProvider))
{
}
public override async Task InitializeAsync()
{
await base.InitializeAsync().ConfigureAwait(true);
VisualStudio.Workspace.SetArgumentCompletionSnippetsOption(true);
}
[WpfFact]
public void SimpleTabTabCompletion()
{
SetUpEditor(@"
Public Class Test
Private f As Object
Public Sub Method()$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("f.ToSt");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString()$$", assertCaretPosition: true);
}
[WpfFact]
public void TabTabCompleteObjectEquals()
{
SetUpEditor(@"
Public Class Test
Public Sub Method()
$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys("Object.Equ");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Object.Equals$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Object.Equals(Nothing$$)", assertCaretPosition: true);
}
[WpfFact]
public void TabTabCompleteNewObject()
{
SetUpEditor(@"
Public Class Test
Public Sub Method()
Dim value = $$
End Sub
End Class
");
VisualStudio.Editor.SendKeys("New Obje");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Dim value = New Object$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Dim value = New Object($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Dim value = New Object()$$", assertCaretPosition: true);
}
[WpfFact]
public void TabTabCompletionWithArguments()
{
SetUpEditor(@"
Imports System
Public Class Test
Private f As Integer
Public Sub Method(provider As IFormatProvider)$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("f.ToSt");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(Nothing$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(Nothing$$, provider)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys("\"format\"");
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$, provider)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\", provider$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Up);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Up);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true);
}
[WpfFact]
public void FullCycle()
{
SetUpEditor(@"
Imports System
Public Class TestClass
Public Sub Method()$$
End Sub
Sub Test()
End Sub
Sub Test(x As Integer)
End Sub
Sub Test(x As Integer, y As Integer)
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("Tes");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Test$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true);
}
[WpfFact]
public void ImplicitArgumentSwitching()
{
SetUpEditor(@"
Imports System
Public Class TestClass
Public Sub Method()$$
End Sub
Sub Test()
End Sub
Sub Test(x As Integer)
End Sub
Sub Test(x As Integer, y As Integer)
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("Tes");
// Trigger the session and type '0' without waiting for the session to finish initializing
VisualStudio.Editor.SendKeys(VirtualKey.Tab, VirtualKey.Tab, '0');
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Up);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
}
[WpfFact]
public void SmartBreakLineWithTabTabCompletion()
{
SetUpEditor(@"
Public Class Test
Private f As Object
Public Sub Method()$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("f.ToSt");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(Shift(VirtualKey.Enter));
VisualStudio.Editor.Verify.TextContains(@"
Public Class Test
Private f As Object
Public Sub Method()
f.ToString()
$$
End Sub
End Class
", assertCaretPosition: true);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicArgumentProvider : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicArgumentProvider(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicArgumentProvider))
{
}
public override async Task InitializeAsync()
{
await base.InitializeAsync().ConfigureAwait(true);
VisualStudio.Workspace.SetArgumentCompletionSnippetsOption(true);
}
[WpfFact]
public void SimpleTabTabCompletion()
{
SetUpEditor(@"
Public Class Test
Private f As Object
Public Sub Method()$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("f.ToSt");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString()$$", assertCaretPosition: true);
}
[WpfFact]
public void TabTabCompleteObjectEquals()
{
SetUpEditor(@"
Public Class Test
Public Sub Method()
$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys("Object.Equ");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Object.Equals$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Object.Equals(Nothing$$)", assertCaretPosition: true);
}
[WpfFact]
public void TabTabCompleteNewObject()
{
SetUpEditor(@"
Public Class Test
Public Sub Method()
Dim value = $$
End Sub
End Class
");
VisualStudio.Editor.SendKeys("New Obje");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Dim value = New Object$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Dim value = New Object($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Dim value = New Object()$$", assertCaretPosition: true);
}
[WpfFact]
public void TabTabCompletionWithArguments()
{
SetUpEditor(@"
Imports System
Public Class Test
Private f As Integer
Public Sub Method(provider As IFormatProvider)$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("f.ToSt");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(Nothing$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(Nothing$$, provider)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys("\"format\"");
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$, provider)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\", provider$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Up);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Up);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true);
}
[WpfFact]
public void FullCycle()
{
SetUpEditor(@"
Imports System
Public Class TestClass
Public Sub Method()$$
End Sub
Sub Test()
End Sub
Sub Test(x As Integer)
End Sub
Sub Test(x As Integer, y As Integer)
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("Tes");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Test$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true);
}
[WpfFact]
public void ImplicitArgumentSwitching()
{
SetUpEditor(@"
Imports System
Public Class TestClass
Public Sub Method()$$
End Sub
Sub Test()
End Sub
Sub Test(x As Integer)
End Sub
Sub Test(x As Integer, y As Integer)
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("Tes");
// Trigger the session and type '0' without waiting for the session to finish initializing
VisualStudio.Editor.SendKeys(VirtualKey.Tab, VirtualKey.Tab, '0');
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Up);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
}
[WpfFact]
public void SmartBreakLineWithTabTabCompletion()
{
SetUpEditor(@"
Public Class Test
Private f As Object
Public Sub Method()$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("f.ToSt");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(Shift(VirtualKey.Enter));
VisualStudio.Editor.Verify.TextContains(@"
Public Class Test
Private f As Object
Public Sub Method()
f.ToString()
$$
End Sub
End Class
", assertCaretPosition: true);
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/EditorFeatures/Core/Implementation/InlineRename/CommandHandlers/AbstractRenameCommandHandler_OpenLineAboveHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal abstract partial class AbstractRenameCommandHandler : IChainedCommandHandler<OpenLineAboveCommandArgs>
{
public CommandState GetCommandState(OpenLineAboveCommandArgs args, Func<CommandState> nextHandler)
=> GetCommandState(nextHandler);
public void ExecuteCommand(OpenLineAboveCommandArgs args, Action nextHandler, CommandExecutionContext context)
{
HandlePossibleTypingCommand(args, nextHandler, (activeSession, span) =>
{
activeSession.Commit();
nextHandler();
});
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal abstract partial class AbstractRenameCommandHandler : IChainedCommandHandler<OpenLineAboveCommandArgs>
{
public CommandState GetCommandState(OpenLineAboveCommandArgs args, Func<CommandState> nextHandler)
=> GetCommandState(nextHandler);
public void ExecuteCommand(OpenLineAboveCommandArgs args, Action nextHandler, CommandExecutionContext context)
{
HandlePossibleTypingCommand(args, nextHandler, (activeSession, span) =>
{
activeSession.Commit();
nextHandler();
});
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/ExpressionEvaluator/CSharp/Test/ResultProvider/DebuggerBrowsableAttributeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Reflection;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class DebuggerBrowsableAttributeTests : CSharpResultProviderTestBase
{
[Fact]
public void Never()
{
var source =
@"using System.Diagnostics;
[DebuggerTypeProxy(typeof(P))]
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object F = 1;
object P { get { return 3; } }
}
class P
{
public P(C c) { }
public object G = 2;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object Q { get { return 4; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("new C()", value);
Verify(evalResult,
EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("G", "2", "object {int}", "new P(new C()).G"),
EvalResult("Raw View", null, "", "new C(), raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
children = GetChildren(children[1]);
Verify(children,
EvalResult("P", "3", "object {int}", "(new C()).P", DkmEvaluationResultFlags.ReadOnly));
}
/// <summary>
/// DebuggerBrowsableAttributes are not inherited.
/// </summary>
[Fact]
public void Never_OverridesAndImplements()
{
var source =
@"using System.Diagnostics;
interface I
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object P1 { get; }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object P2 { get; }
object P3 { get; }
object P4 { get; }
}
abstract class A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal abstract object P5 { get; }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal virtual object P6 { get { return 0; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal abstract object P7 { get; }
internal abstract object P8 { get; }
}
class B : A, I
{
public object P1 { get { return 1; } }
object I.P2 { get { return 2; } }
object I.P3 { get { return 3; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object I.P4 { get { return 4; } }
internal override object P5 { get { return 5; } }
internal override object P6 { get { return 6; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal override object P7 { get { return 7; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal override object P8 { get { return 8; } }
}
class C
{
I o = new B();
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("c", value);
Verify(evalResult,
EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("o", "{B}", "I {B}", "c.o", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite));
children = GetChildren(children[0]);
Verify(children,
EvalResult("I.P2", "2", "object {int}", "c.o.P2", DkmEvaluationResultFlags.ReadOnly),
EvalResult("I.P3", "3", "object {int}", "c.o.P3", DkmEvaluationResultFlags.ReadOnly),
EvalResult("P1", "1", "object {int}", "((B)c.o).P1", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite),
EvalResult("P5", "5", "object {int}", "((B)c.o).P5", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite),
EvalResult("P6", "6", "object {int}", "((B)c.o).P6", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite));
}
[Fact]
public void DuplicateAttributes()
{
var source =
@"using System.Diagnostics;
abstract class A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object P1;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object P2;
internal object P3 => 0;
}
class B : A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
new public object P1 => base.P1;
new public object P2 => 1;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal new object P3 => 2;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None,
valueFlags: DkmClrValueFlags.Synthetic);
var evalResult = FormatResult("this", value);
Verify(evalResult,
EvalResult("this", "{B}", "B", "this", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("P3 (A)", "0", "object {int}", "((A)this).P3", DkmEvaluationResultFlags.ReadOnly));
}
/// <summary>
/// DkmClrDebuggerBrowsableAttributes are obtained from the
/// containing type and associated with the member name. For
/// explicit interface implementations, the name will include
/// namespace and type.
/// </summary>
[Fact]
public void Never_ExplicitNamespaceGeneric()
{
var source =
@"using System.Diagnostics;
namespace N1
{
namespace N2
{
class A<T>
{
internal interface I<U>
{
T P { get; }
U Q { get; }
}
}
}
class B : N2.A<object>.I<int>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object N2.A<object>.I<int>.P { get { return 1; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public int Q { get { return 2; } }
}
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("N1.B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{N1.B}", "N1.B", "o"));
}
[Fact]
public void RootHidden()
{
var source =
@"using System.Diagnostics;
struct S
{
internal S(int[] x, object[] y) : this()
{
this.F = x;
this.Q = y;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal int[] F;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal int P { get { return this.F.Length; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object[] Q { get; private set; }
}
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly B G = new B { H = 4 };
}
class B
{
internal object H;
}";
var assembly = GetAssembly(source);
var typeS = assembly.GetType("S");
var typeA = assembly.GetType("A");
var value = CreateDkmClrValue(
value: typeS.Instantiate(new int[] { 1, 2 }, new object[] { 3, typeA.Instantiate() }),
type: new DkmClrType((TypeImpl)typeS),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{S}", "S", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "int", "o.F[0]"),
EvalResult("[1]", "2", "int", "o.F[1]"),
EvalResult("[0]", "3", "object {int}", "o.Q[0]"),
EvalResult("[1]", "{A}", "object {A}", "o.Q[1]", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[3]),
EvalResult("H", "4", "object {int}", "((A)o.Q[1]).G.H"));
}
[Fact]
public void RootHidden_Exception()
{
var source =
@"using System;
using System.Diagnostics;
class E : Exception
{
}
class F : E
{
object G = 1;
}
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
object P { get { throw new F(); } }
}";
using (new EnsureEnglishUICulture())
{
var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source)));
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = type.Instantiate();
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children[1],
EvalResult("G", "1", "object {int}", null));
Verify(children[7],
EvalResult("Message", "\"Exception of type 'F' was thrown.\"", "string", null,
DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly));
}
}
}
/// <summary>
/// Instance of type where all members are marked
/// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)].
/// </summary>
[WorkItem(934800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/934800")]
[Fact]
public void RootHidden_Empty()
{
var source =
@"using System.Diagnostics;
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F1 = new C();
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F2 = new C();
}
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F3 = new object();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F4 = null;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); // Ideally, not expandable.
var children = GetChildren(evalResult);
Verify(children); // No children.
}
[Fact]
public void DebuggerBrowsable_GenericType()
{
var source =
@"using System.Diagnostics;
class C<T>
{
internal C(T f, T g)
{
this.F = f;
this.G = g;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal readonly T F;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly T G;
}
struct S
{
internal S(object o)
{
this.O = o;
}
internal readonly object O;
}";
var assembly = GetAssembly(source);
var typeS = assembly.GetType("S");
var typeC = assembly.GetType("C`1").MakeGenericType(typeS);
var value = CreateDkmClrValue(
value: typeC.Instantiate(typeS.Instantiate(1), typeS.Instantiate(2)),
type: new DkmClrType((TypeImpl)typeC),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<S>}", "C<S>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("O", "2", "object {int}", "o.G.O", DkmEvaluationResultFlags.ReadOnly));
}
[Fact]
public void RootHidden_ExplicitImplementation()
{
var source =
@"using System.Diagnostics;
interface I<T>
{
T P { get; }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
T Q { get; }
}
class A
{
internal object F;
}
class B : I<A>
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
A I<A>.P { get { return new A() { F = 1 }; } }
A I<A>.Q { get { return new A() { F = 2 }; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "1", "object {int}", "((I<A>)o).P.F"),
EvalResult("I<A>.Q", "{A}", "A", "((I<A>)o).Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[1]),
EvalResult("F", "2", "object {int}", "((I<A>)o).Q.F", DkmEvaluationResultFlags.CanFavorite));
}
[Fact]
public void RootHidden_ProxyType()
{
var source =
@"using System.Diagnostics;
[DebuggerTypeProxy(typeof(P))]
class A
{
internal A(int f)
{
this.F = f;
}
internal int F;
}
class P
{
private readonly A a;
public P(A a)
{
this.a = a;
}
public object Q { get { return this.a.F; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public object R { get { return this.a.F + 1; } }
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object F = new A(1);
internal object G = new A(3);
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Q", "1", "object {int}", "new P(o.F).Q", DkmEvaluationResultFlags.ReadOnly),
EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("G", "{A}", "object {A}", "o.G", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[1]),
EvalResult("F", "1", "int", "((A)o.F).F"));
Verify(GetChildren(children[2]),
EvalResult("Q", "3", "object {int}", "new P(o.G).Q", DkmEvaluationResultFlags.ReadOnly),
EvalResult("Raw View", null, "", "o.G, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
}
[Fact]
public void RootHidden_Recursive()
{
var source =
@"using System.Diagnostics;
class A
{
internal A(object o)
{
this.F = o;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object F;
}
class B
{
internal B(object o)
{
this.F = o;
}
internal object F;
}";
var assembly = GetAssembly(source);
var typeA = assembly.GetType("A");
var typeB = assembly.GetType("B");
var value = CreateDkmClrValue(
value: typeA.Instantiate(typeA.Instantiate(typeA.Instantiate(typeB.Instantiate(4)))),
type: new DkmClrType((TypeImpl)typeA),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "4", "object {int}", "((B)((A)((A)o.F).F).F).F"));
}
[Fact]
public void RootHidden_OnStaticMembers()
{
var source =
@"using System.Diagnostics;
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal static object F = new B();
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal static object P { get { return new C(); } }
internal static object G = 1;
}
class C
{
internal static object Q { get { return 3; } }
internal object H = 2;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("A");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[0]);
Verify(children,
EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[0]);
Verify(children,
EvalResult("G", "1", "object {int}", "B.G"),
EvalResult("H", "2", "object {int}", "((C)B.P).H"),
EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[2]);
Verify(children,
EvalResult("Q", "3", "object {int}", "C.Q", DkmEvaluationResultFlags.ReadOnly));
}
// Dev12 exposes the contents of RootHidden members even
// if the members are private (e.g.: ImmutableArray<T>).
[Fact]
public void RootHidden_OnNonPublicMembers()
{
var source =
@"using System.Diagnostics;
public class C<T>
{
public C(params T[] items)
{
this.items = items;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private T[] items;
}";
var assembly = GetAssembly(source);
var runtime = new DkmClrRuntimeInstance(new Assembly[0]);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(1, 2, 3),
type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "int", "o.items[0]"),
EvalResult("[1]", "2", "int", "o.items[1]"),
EvalResult("[2]", "3", "int", "o.items[2]"));
}
// Dev12 does not merge "Static members" (or "Non-Public
// members") across multiple RootHidden members. In
// other words, there may be multiple "Static members" (or
// "Non-Public members") rows within the same container.
[Fact]
public void RootHidden_WithStaticAndNonPublicMembers()
{
var source =
@"using System.Diagnostics;
public class A
{
public static int PA { get { return 1; } }
internal int FA = 2;
}
public class B
{
internal int PB { get { return 3; } }
public static int FB = 4;
}
public class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public readonly object FA = new A();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public object PB { get { return new B(); } }
public static int PC { get { return 5; } }
internal int FC = 6;
}";
var assembly = GetAssembly(source);
var runtime = new DkmClrRuntimeInstance(new Assembly[0]);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type),
evalFlags: DkmEvaluationResultFlags.None);
var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers);
var evalResult = FormatResult("o", value, inspectionContext: inspectionContext);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult, inspectionContext: inspectionContext);
Verify(children,
EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o.FA, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o.PB, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
Verify(GetChildren(children[0]),
EvalResult("PA", "1", "int", "A.PA", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[1]),
EvalResult("FA", "2", "int", "((A)o.FA).FA"));
Verify(GetChildren(children[2]),
EvalResult("FB", "4", "int", "B.FB"));
Verify(GetChildren(children[3]),
EvalResult("PB", "3", "int", "((B)o.PB).PB", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[4]),
EvalResult("PC", "5", "int", "C.PC", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[5]),
EvalResult("FC", "6", "int", "o.FC"));
}
[Fact]
public void ConstructedGenericType()
{
var source = @"
using System.Diagnostics;
public class C<T>
{
public T X;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Y;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(evalResult),
EvalResult("X", "0", "int", "o.X", DkmEvaluationResultFlags.CanFavorite));
}
[WorkItem(18581, "https://github.com/dotnet/roslyn/issues/18581")]
[Fact]
public void AccessibilityNotTrumpedByAttribute()
{
var source =
@"using System.Diagnostics;
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int[] _someArray = { 10, 20 };
private object SomethingPrivate = 3;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
internal object InternalCollapsed { get { return 1; } }
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
private object PrivateCollapsed { get { return 3; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private int[] PrivateRootHidden { get { return _someArray; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("new C()", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "10", "int", "(new C()).PrivateRootHidden[0]"),
EvalResult("[1]", "20", "int", "(new C()).PrivateRootHidden[1]"),
EvalResult("Non-Public members", null, "", "new C(), hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
var nonPublicChildren = GetChildren(children[2]);
Verify(nonPublicChildren,
EvalResult("InternalCollapsed", "1", "object {int}", "(new C()).InternalCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Internal),
EvalResult("PrivateCollapsed", "3", "object {int}", "(new C()).PrivateCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private),
EvalResult("SomethingPrivate", "3", "object {int}", "(new C()).SomethingPrivate", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Private));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Reflection;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class DebuggerBrowsableAttributeTests : CSharpResultProviderTestBase
{
[Fact]
public void Never()
{
var source =
@"using System.Diagnostics;
[DebuggerTypeProxy(typeof(P))]
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object F = 1;
object P { get { return 3; } }
}
class P
{
public P(C c) { }
public object G = 2;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object Q { get { return 4; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("new C()", value);
Verify(evalResult,
EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("G", "2", "object {int}", "new P(new C()).G"),
EvalResult("Raw View", null, "", "new C(), raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
children = GetChildren(children[1]);
Verify(children,
EvalResult("P", "3", "object {int}", "(new C()).P", DkmEvaluationResultFlags.ReadOnly));
}
/// <summary>
/// DebuggerBrowsableAttributes are not inherited.
/// </summary>
[Fact]
public void Never_OverridesAndImplements()
{
var source =
@"using System.Diagnostics;
interface I
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object P1 { get; }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object P2 { get; }
object P3 { get; }
object P4 { get; }
}
abstract class A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal abstract object P5 { get; }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal virtual object P6 { get { return 0; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal abstract object P7 { get; }
internal abstract object P8 { get; }
}
class B : A, I
{
public object P1 { get { return 1; } }
object I.P2 { get { return 2; } }
object I.P3 { get { return 3; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object I.P4 { get { return 4; } }
internal override object P5 { get { return 5; } }
internal override object P6 { get { return 6; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal override object P7 { get { return 7; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal override object P8 { get { return 8; } }
}
class C
{
I o = new B();
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("c", value);
Verify(evalResult,
EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("o", "{B}", "I {B}", "c.o", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite));
children = GetChildren(children[0]);
Verify(children,
EvalResult("I.P2", "2", "object {int}", "c.o.P2", DkmEvaluationResultFlags.ReadOnly),
EvalResult("I.P3", "3", "object {int}", "c.o.P3", DkmEvaluationResultFlags.ReadOnly),
EvalResult("P1", "1", "object {int}", "((B)c.o).P1", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite),
EvalResult("P5", "5", "object {int}", "((B)c.o).P5", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite),
EvalResult("P6", "6", "object {int}", "((B)c.o).P6", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite));
}
[Fact]
public void DuplicateAttributes()
{
var source =
@"using System.Diagnostics;
abstract class A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object P1;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object P2;
internal object P3 => 0;
}
class B : A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
new public object P1 => base.P1;
new public object P2 => 1;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal new object P3 => 2;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None,
valueFlags: DkmClrValueFlags.Synthetic);
var evalResult = FormatResult("this", value);
Verify(evalResult,
EvalResult("this", "{B}", "B", "this", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("P3 (A)", "0", "object {int}", "((A)this).P3", DkmEvaluationResultFlags.ReadOnly));
}
/// <summary>
/// DkmClrDebuggerBrowsableAttributes are obtained from the
/// containing type and associated with the member name. For
/// explicit interface implementations, the name will include
/// namespace and type.
/// </summary>
[Fact]
public void Never_ExplicitNamespaceGeneric()
{
var source =
@"using System.Diagnostics;
namespace N1
{
namespace N2
{
class A<T>
{
internal interface I<U>
{
T P { get; }
U Q { get; }
}
}
}
class B : N2.A<object>.I<int>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object N2.A<object>.I<int>.P { get { return 1; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public int Q { get { return 2; } }
}
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("N1.B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{N1.B}", "N1.B", "o"));
}
[Fact]
public void RootHidden()
{
var source =
@"using System.Diagnostics;
struct S
{
internal S(int[] x, object[] y) : this()
{
this.F = x;
this.Q = y;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal int[] F;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal int P { get { return this.F.Length; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object[] Q { get; private set; }
}
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly B G = new B { H = 4 };
}
class B
{
internal object H;
}";
var assembly = GetAssembly(source);
var typeS = assembly.GetType("S");
var typeA = assembly.GetType("A");
var value = CreateDkmClrValue(
value: typeS.Instantiate(new int[] { 1, 2 }, new object[] { 3, typeA.Instantiate() }),
type: new DkmClrType((TypeImpl)typeS),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{S}", "S", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "int", "o.F[0]"),
EvalResult("[1]", "2", "int", "o.F[1]"),
EvalResult("[0]", "3", "object {int}", "o.Q[0]"),
EvalResult("[1]", "{A}", "object {A}", "o.Q[1]", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[3]),
EvalResult("H", "4", "object {int}", "((A)o.Q[1]).G.H"));
}
[Fact]
public void RootHidden_Exception()
{
var source =
@"using System;
using System.Diagnostics;
class E : Exception
{
}
class F : E
{
object G = 1;
}
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
object P { get { throw new F(); } }
}";
using (new EnsureEnglishUICulture())
{
var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source)));
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = type.Instantiate();
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children[1],
EvalResult("G", "1", "object {int}", null));
Verify(children[7],
EvalResult("Message", "\"Exception of type 'F' was thrown.\"", "string", null,
DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly));
}
}
}
/// <summary>
/// Instance of type where all members are marked
/// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)].
/// </summary>
[WorkItem(934800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/934800")]
[Fact]
public void RootHidden_Empty()
{
var source =
@"using System.Diagnostics;
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F1 = new C();
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F2 = new C();
}
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F3 = new object();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F4 = null;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); // Ideally, not expandable.
var children = GetChildren(evalResult);
Verify(children); // No children.
}
[Fact]
public void DebuggerBrowsable_GenericType()
{
var source =
@"using System.Diagnostics;
class C<T>
{
internal C(T f, T g)
{
this.F = f;
this.G = g;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal readonly T F;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly T G;
}
struct S
{
internal S(object o)
{
this.O = o;
}
internal readonly object O;
}";
var assembly = GetAssembly(source);
var typeS = assembly.GetType("S");
var typeC = assembly.GetType("C`1").MakeGenericType(typeS);
var value = CreateDkmClrValue(
value: typeC.Instantiate(typeS.Instantiate(1), typeS.Instantiate(2)),
type: new DkmClrType((TypeImpl)typeC),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<S>}", "C<S>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("O", "2", "object {int}", "o.G.O", DkmEvaluationResultFlags.ReadOnly));
}
[Fact]
public void RootHidden_ExplicitImplementation()
{
var source =
@"using System.Diagnostics;
interface I<T>
{
T P { get; }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
T Q { get; }
}
class A
{
internal object F;
}
class B : I<A>
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
A I<A>.P { get { return new A() { F = 1 }; } }
A I<A>.Q { get { return new A() { F = 2 }; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "1", "object {int}", "((I<A>)o).P.F"),
EvalResult("I<A>.Q", "{A}", "A", "((I<A>)o).Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[1]),
EvalResult("F", "2", "object {int}", "((I<A>)o).Q.F", DkmEvaluationResultFlags.CanFavorite));
}
[Fact]
public void RootHidden_ProxyType()
{
var source =
@"using System.Diagnostics;
[DebuggerTypeProxy(typeof(P))]
class A
{
internal A(int f)
{
this.F = f;
}
internal int F;
}
class P
{
private readonly A a;
public P(A a)
{
this.a = a;
}
public object Q { get { return this.a.F; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public object R { get { return this.a.F + 1; } }
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object F = new A(1);
internal object G = new A(3);
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Q", "1", "object {int}", "new P(o.F).Q", DkmEvaluationResultFlags.ReadOnly),
EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("G", "{A}", "object {A}", "o.G", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[1]),
EvalResult("F", "1", "int", "((A)o.F).F"));
Verify(GetChildren(children[2]),
EvalResult("Q", "3", "object {int}", "new P(o.G).Q", DkmEvaluationResultFlags.ReadOnly),
EvalResult("Raw View", null, "", "o.G, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
}
[Fact]
public void RootHidden_Recursive()
{
var source =
@"using System.Diagnostics;
class A
{
internal A(object o)
{
this.F = o;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object F;
}
class B
{
internal B(object o)
{
this.F = o;
}
internal object F;
}";
var assembly = GetAssembly(source);
var typeA = assembly.GetType("A");
var typeB = assembly.GetType("B");
var value = CreateDkmClrValue(
value: typeA.Instantiate(typeA.Instantiate(typeA.Instantiate(typeB.Instantiate(4)))),
type: new DkmClrType((TypeImpl)typeA),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "4", "object {int}", "((B)((A)((A)o.F).F).F).F"));
}
[Fact]
public void RootHidden_OnStaticMembers()
{
var source =
@"using System.Diagnostics;
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal static object F = new B();
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal static object P { get { return new C(); } }
internal static object G = 1;
}
class C
{
internal static object Q { get { return 3; } }
internal object H = 2;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("A");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[0]);
Verify(children,
EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[0]);
Verify(children,
EvalResult("G", "1", "object {int}", "B.G"),
EvalResult("H", "2", "object {int}", "((C)B.P).H"),
EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[2]);
Verify(children,
EvalResult("Q", "3", "object {int}", "C.Q", DkmEvaluationResultFlags.ReadOnly));
}
// Dev12 exposes the contents of RootHidden members even
// if the members are private (e.g.: ImmutableArray<T>).
[Fact]
public void RootHidden_OnNonPublicMembers()
{
var source =
@"using System.Diagnostics;
public class C<T>
{
public C(params T[] items)
{
this.items = items;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private T[] items;
}";
var assembly = GetAssembly(source);
var runtime = new DkmClrRuntimeInstance(new Assembly[0]);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(1, 2, 3),
type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "int", "o.items[0]"),
EvalResult("[1]", "2", "int", "o.items[1]"),
EvalResult("[2]", "3", "int", "o.items[2]"));
}
// Dev12 does not merge "Static members" (or "Non-Public
// members") across multiple RootHidden members. In
// other words, there may be multiple "Static members" (or
// "Non-Public members") rows within the same container.
[Fact]
public void RootHidden_WithStaticAndNonPublicMembers()
{
var source =
@"using System.Diagnostics;
public class A
{
public static int PA { get { return 1; } }
internal int FA = 2;
}
public class B
{
internal int PB { get { return 3; } }
public static int FB = 4;
}
public class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public readonly object FA = new A();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public object PB { get { return new B(); } }
public static int PC { get { return 5; } }
internal int FC = 6;
}";
var assembly = GetAssembly(source);
var runtime = new DkmClrRuntimeInstance(new Assembly[0]);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type),
evalFlags: DkmEvaluationResultFlags.None);
var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers);
var evalResult = FormatResult("o", value, inspectionContext: inspectionContext);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult, inspectionContext: inspectionContext);
Verify(children,
EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o.FA, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o.PB, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
Verify(GetChildren(children[0]),
EvalResult("PA", "1", "int", "A.PA", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[1]),
EvalResult("FA", "2", "int", "((A)o.FA).FA"));
Verify(GetChildren(children[2]),
EvalResult("FB", "4", "int", "B.FB"));
Verify(GetChildren(children[3]),
EvalResult("PB", "3", "int", "((B)o.PB).PB", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[4]),
EvalResult("PC", "5", "int", "C.PC", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[5]),
EvalResult("FC", "6", "int", "o.FC"));
}
[Fact]
public void ConstructedGenericType()
{
var source = @"
using System.Diagnostics;
public class C<T>
{
public T X;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Y;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(evalResult),
EvalResult("X", "0", "int", "o.X", DkmEvaluationResultFlags.CanFavorite));
}
[WorkItem(18581, "https://github.com/dotnet/roslyn/issues/18581")]
[Fact]
public void AccessibilityNotTrumpedByAttribute()
{
var source =
@"using System.Diagnostics;
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int[] _someArray = { 10, 20 };
private object SomethingPrivate = 3;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
internal object InternalCollapsed { get { return 1; } }
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
private object PrivateCollapsed { get { return 3; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private int[] PrivateRootHidden { get { return _someArray; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("new C()", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "10", "int", "(new C()).PrivateRootHidden[0]"),
EvalResult("[1]", "20", "int", "(new C()).PrivateRootHidden[1]"),
EvalResult("Non-Public members", null, "", "new C(), hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
var nonPublicChildren = GetChildren(children[2]);
Verify(nonPublicChildren,
EvalResult("InternalCollapsed", "1", "object {int}", "(new C()).InternalCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Internal),
EvalResult("PrivateCollapsed", "3", "object {int}", "(new C()).PrivateCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private),
EvalResult("SomethingPrivate", "3", "object {int}", "(new C()).SomethingPrivate", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Private));
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/CodeStyle/Core/Analyzers/FormattingAnalyzerHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Diagnostics;
using Microsoft.CodeAnalysis.Text;
#if CODE_STYLE
using Formatter = Microsoft.CodeAnalysis.Formatting.FormatterHelper;
using FormatterState = Microsoft.CodeAnalysis.Formatting.ISyntaxFormattingService;
using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
#else
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Formatting;
using FormatterState = Microsoft.CodeAnalysis.Workspace;
#endif
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal static class FormattingAnalyzerHelper
{
internal static void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context, FormatterState formatterState, DiagnosticDescriptor descriptor, OptionSet options)
{
var tree = context.Tree;
var cancellationToken = context.CancellationToken;
var oldText = tree.GetText(cancellationToken);
var formattingChanges = Formatter.GetFormattedTextChanges(tree.GetRoot(cancellationToken), formatterState, options, cancellationToken);
// formattingChanges could include changes that impact a larger section of the original document than
// necessary. Before reporting diagnostics, process the changes to minimize the span of individual
// diagnostics.
foreach (var formattingChange in formattingChanges)
{
var change = formattingChange;
if (change.NewText.Length > 0 && !change.Span.IsEmpty)
{
// Handle cases where the change is a substring removal from the beginning. In these cases, we want
// the diagnostic span to cover the unwanted leading characters (which should be removed), and
// nothing more.
var offset = change.Span.Length - change.NewText.Length;
if (offset >= 0)
{
if (oldText.GetSubText(new TextSpan(change.Span.Start + offset, change.NewText.Length)).ContentEquals(SourceText.From(change.NewText)))
{
change = new TextChange(new TextSpan(change.Span.Start, offset), "");
}
else
{
// Handle cases where the change is a substring removal from the end. In these cases, we want
// the diagnostic span to cover the unwanted trailing characters (which should be removed), and
// nothing more.
if (oldText.GetSubText(new TextSpan(change.Span.Start, change.NewText.Length)).ContentEquals(SourceText.From(change.NewText)))
{
change = new TextChange(new TextSpan(change.Span.Start + change.NewText.Length, offset), "");
}
}
}
}
if (change.NewText.Length == 0 && change.Span.IsEmpty)
{
// No actual change (allows for the formatter to report a NOP change without triggering a
// diagnostic that can't be fixed).
continue;
}
var location = Location.Create(tree, change.Span);
context.ReportDiagnostic(Diagnostic.Create(
descriptor,
location,
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 Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
#if CODE_STYLE
using Formatter = Microsoft.CodeAnalysis.Formatting.FormatterHelper;
using FormatterState = Microsoft.CodeAnalysis.Formatting.ISyntaxFormattingService;
using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
#else
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Formatting;
using FormatterState = Microsoft.CodeAnalysis.Workspace;
#endif
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal static class FormattingAnalyzerHelper
{
internal static void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context, FormatterState formatterState, DiagnosticDescriptor descriptor, OptionSet options)
{
var tree = context.Tree;
var cancellationToken = context.CancellationToken;
var oldText = tree.GetText(cancellationToken);
var formattingChanges = Formatter.GetFormattedTextChanges(tree.GetRoot(cancellationToken), formatterState, options, cancellationToken);
// formattingChanges could include changes that impact a larger section of the original document than
// necessary. Before reporting diagnostics, process the changes to minimize the span of individual
// diagnostics.
foreach (var formattingChange in formattingChanges)
{
var change = formattingChange;
if (change.NewText.Length > 0 && !change.Span.IsEmpty)
{
// Handle cases where the change is a substring removal from the beginning. In these cases, we want
// the diagnostic span to cover the unwanted leading characters (which should be removed), and
// nothing more.
var offset = change.Span.Length - change.NewText.Length;
if (offset >= 0)
{
if (oldText.GetSubText(new TextSpan(change.Span.Start + offset, change.NewText.Length)).ContentEquals(SourceText.From(change.NewText)))
{
change = new TextChange(new TextSpan(change.Span.Start, offset), "");
}
else
{
// Handle cases where the change is a substring removal from the end. In these cases, we want
// the diagnostic span to cover the unwanted trailing characters (which should be removed), and
// nothing more.
if (oldText.GetSubText(new TextSpan(change.Span.Start, change.NewText.Length)).ContentEquals(SourceText.From(change.NewText)))
{
change = new TextChange(new TextSpan(change.Span.Start + change.NewText.Length, offset), "");
}
}
}
}
if (change.NewText.Length == 0 && change.Span.IsEmpty)
{
// No actual change (allows for the formatter to report a NOP change without triggering a
// diagnostic that can't be fixed).
continue;
}
var location = Location.Create(tree, change.Span);
context.ReportDiagnostic(Diagnostic.Create(
descriptor,
location,
additionalLocations: null,
properties: null));
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/VisualStudioWorkspace_InProc.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.OperationProgress;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Hosting.Diagnostics.Waiters;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class VisualStudioWorkspace_InProc : InProcComponent
{
private static readonly Guid RoslynPackageId = new Guid("6cf2e545-6109-4730-8883-cf43d7aec3e1");
private readonly VisualStudioWorkspace _visualStudioWorkspace;
private VisualStudioWorkspace_InProc()
{
// we need to enable waiting service before we create workspace
GetWaitingService().Enable(true);
_visualStudioWorkspace = GetComponentModelService<VisualStudioWorkspace>();
}
public static VisualStudioWorkspace_InProc Create()
=> new VisualStudioWorkspace_InProc();
public void SetOptionInfer(string projectName, bool value)
=> InvokeOnUIThread(cancellationToken =>
{
var convertedValue = value ? 1 : 0;
var project = GetProject(projectName);
project.Properties.Item("OptionInfer").Value = convertedValue;
});
private EnvDTE.Project GetProject(string nameOrFileName)
=> GetDTE().Solution.Projects.OfType<EnvDTE.Project>().First(p =>
string.Compare(p.FileName, nameOrFileName, StringComparison.OrdinalIgnoreCase) == 0
|| string.Compare(p.Name, nameOrFileName, StringComparison.OrdinalIgnoreCase) == 0);
public bool IsPrettyListingOn(string languageName)
=> _visualStudioWorkspace.Options.GetOption(FeatureOnOffOptions.PrettyListing, languageName);
public void SetPrettyListing(string languageName, bool value)
=> InvokeOnUIThread(cancellationToken =>
{
_visualStudioWorkspace.SetOptions(_visualStudioWorkspace.Options.WithChangedOption(
FeatureOnOffOptions.PrettyListing, languageName, value));
});
public void EnableQuickInfo(bool value)
=> InvokeOnUIThread(cancellationToken =>
{
_visualStudioWorkspace.SetOptions(_visualStudioWorkspace.Options.WithChangedOption(
InternalFeatureOnOffOptions.QuickInfo, value));
});
public void SetPerLanguageOption(string optionName, string feature, string language, object value)
{
var option = GetOption(optionName, feature);
var result = GetValue(value, option);
var optionKey = new OptionKey(option, language);
SetOption(optionKey, result);
}
public void SetOption(string optionName, string feature, object value)
{
var option = GetOption(optionName, feature);
var result = GetValue(value, option);
var optionKey = new OptionKey(option);
SetOption(optionKey, result);
}
private static object GetValue(object value, IOption option)
{
object result;
if (value is string stringValue)
{
result = TypeDescriptor.GetConverter(option.Type).ConvertFromString(stringValue);
}
else
{
result = value;
}
return result;
}
private IOption GetOption(string optionName, string feature)
{
var optionService = _visualStudioWorkspace.Services.GetRequiredService<IOptionService>();
var option = optionService.GetRegisteredOptions().FirstOrDefault(o => o.Feature == feature && o.Name == optionName);
if (option == null)
{
throw new Exception($"Failed to find option with feature name '{feature}' and option name '{optionName}'");
}
return option;
}
private void SetOption(OptionKey optionKey, object? result)
=> _visualStudioWorkspace.SetOptions(_visualStudioWorkspace.Options.WithChangedOption(optionKey, result));
private static TestingOnly_WaitingService GetWaitingService()
=> GetComponentModel().DefaultExportProvider.GetExport<TestingOnly_WaitingService>().Value;
public void WaitForAsyncOperations(TimeSpan timeout, string featuresToWaitFor, bool waitForWorkspaceFirst = true)
{
if (waitForWorkspaceFirst || featuresToWaitFor == FeatureAttribute.Workspace)
{
WaitForProjectSystem(timeout);
}
GetWaitingService().WaitForAsyncOperations(timeout, featuresToWaitFor, waitForWorkspaceFirst);
}
public void WaitForAllAsyncOperations(TimeSpan timeout, params string[] featureNames)
{
if (featureNames.Contains(FeatureAttribute.Workspace))
{
WaitForProjectSystem(timeout);
}
GetWaitingService().WaitForAllAsyncOperations(_visualStudioWorkspace, timeout, featureNames);
}
public void WaitForAllAsyncOperationsOrFail(TimeSpan timeout, params string[] featureNames)
{
try
{
WaitForAllAsyncOperations(timeout, featureNames);
}
catch (Exception e)
{
var listenerProvider = GetComponentModel().DefaultExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>();
var messageBuilder = new StringBuilder("Failed to clean up listeners in a timely manner.");
foreach (var token in ((AsynchronousOperationListenerProvider)listenerProvider).GetTokens())
{
messageBuilder.AppendLine().Append($" {token}");
}
Environment.FailFast("Terminating test process due to unrecoverable timeout.", new TimeoutException(messageBuilder.ToString(), e));
}
}
private static void WaitForProjectSystem(TimeSpan timeout)
{
var operationProgressStatus = InvokeOnUIThread(_ => GetGlobalService<SVsOperationProgress, IVsOperationProgressStatusService>());
var stageStatus = operationProgressStatus.GetStageStatus(CommonOperationProgressStageIds.Intellisense);
stageStatus.WaitForCompletionAsync().Wait(timeout);
}
private static void LoadRoslynPackage()
{
var roslynPackageGuid = RoslynPackageId;
var vsShell = GetGlobalService<SVsShell, IVsShell>();
var hresult = vsShell.LoadPackage(ref roslynPackageGuid, out _);
Marshal.ThrowExceptionForHR(hresult);
}
public void CleanUpWorkspace()
=> InvokeOnUIThread(cancellationToken =>
{
LoadRoslynPackage();
_visualStudioWorkspace.TestHookPartialSolutionsDisabled = true;
});
/// <summary>
/// Reset options that are manipulated by integration tests back to their default values.
/// </summary>
public void ResetOptions()
{
ResetOption(CompletionOptions.EnableArgumentCompletionSnippets);
return;
// Local function
void ResetOption(IOption option)
{
if (option is IPerLanguageOption)
{
SetOption(new OptionKey(option, LanguageNames.CSharp), option.DefaultValue);
SetOption(new OptionKey(option, LanguageNames.VisualBasic), option.DefaultValue);
}
else
{
SetOption(new OptionKey(option), option.DefaultValue);
}
}
}
public void CleanUpWaitingService()
=> InvokeOnUIThread(cancellationToken =>
{
var provider = GetComponentModel().DefaultExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>();
if (provider == null)
{
throw new InvalidOperationException("The test waiting service could not be located.");
}
GetWaitingService().EnableActiveTokenTracking(true);
});
public void SetFeatureOption(string feature, string optionName, string language, string? valueString)
=> InvokeOnUIThread(cancellationToken =>
{
var option = GetOption(optionName, feature);
var value = TypeDescriptor.GetConverter(option.Type).ConvertFromString(valueString);
var optionKey = string.IsNullOrWhiteSpace(language)
? new OptionKey(option)
: new OptionKey(option, language);
SetOption(optionKey, value);
});
public string? GetWorkingFolder()
{
var service = _visualStudioWorkspace.Services.GetRequiredService<IPersistentStorageLocationService>();
return service.TryGetStorageLocation(_visualStudioWorkspace.CurrentSolution);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.OperationProgress;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Hosting.Diagnostics.Waiters;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class VisualStudioWorkspace_InProc : InProcComponent
{
private static readonly Guid RoslynPackageId = new Guid("6cf2e545-6109-4730-8883-cf43d7aec3e1");
private readonly VisualStudioWorkspace _visualStudioWorkspace;
private VisualStudioWorkspace_InProc()
{
// we need to enable waiting service before we create workspace
GetWaitingService().Enable(true);
_visualStudioWorkspace = GetComponentModelService<VisualStudioWorkspace>();
}
public static VisualStudioWorkspace_InProc Create()
=> new VisualStudioWorkspace_InProc();
public void SetOptionInfer(string projectName, bool value)
=> InvokeOnUIThread(cancellationToken =>
{
var convertedValue = value ? 1 : 0;
var project = GetProject(projectName);
project.Properties.Item("OptionInfer").Value = convertedValue;
});
private EnvDTE.Project GetProject(string nameOrFileName)
=> GetDTE().Solution.Projects.OfType<EnvDTE.Project>().First(p =>
string.Compare(p.FileName, nameOrFileName, StringComparison.OrdinalIgnoreCase) == 0
|| string.Compare(p.Name, nameOrFileName, StringComparison.OrdinalIgnoreCase) == 0);
public bool IsPrettyListingOn(string languageName)
=> _visualStudioWorkspace.Options.GetOption(FeatureOnOffOptions.PrettyListing, languageName);
public void SetPrettyListing(string languageName, bool value)
=> InvokeOnUIThread(cancellationToken =>
{
_visualStudioWorkspace.SetOptions(_visualStudioWorkspace.Options.WithChangedOption(
FeatureOnOffOptions.PrettyListing, languageName, value));
});
public void EnableQuickInfo(bool value)
=> InvokeOnUIThread(cancellationToken =>
{
_visualStudioWorkspace.SetOptions(_visualStudioWorkspace.Options.WithChangedOption(
InternalFeatureOnOffOptions.QuickInfo, value));
});
public void SetPerLanguageOption(string optionName, string feature, string language, object value)
{
var option = GetOption(optionName, feature);
var result = GetValue(value, option);
var optionKey = new OptionKey(option, language);
SetOption(optionKey, result);
}
public void SetOption(string optionName, string feature, object value)
{
var option = GetOption(optionName, feature);
var result = GetValue(value, option);
var optionKey = new OptionKey(option);
SetOption(optionKey, result);
}
private static object GetValue(object value, IOption option)
{
object result;
if (value is string stringValue)
{
result = TypeDescriptor.GetConverter(option.Type).ConvertFromString(stringValue);
}
else
{
result = value;
}
return result;
}
private IOption GetOption(string optionName, string feature)
{
var optionService = _visualStudioWorkspace.Services.GetRequiredService<IOptionService>();
var option = optionService.GetRegisteredOptions().FirstOrDefault(o => o.Feature == feature && o.Name == optionName);
if (option == null)
{
throw new Exception($"Failed to find option with feature name '{feature}' and option name '{optionName}'");
}
return option;
}
private void SetOption(OptionKey optionKey, object? result)
=> _visualStudioWorkspace.SetOptions(_visualStudioWorkspace.Options.WithChangedOption(optionKey, result));
private static TestingOnly_WaitingService GetWaitingService()
=> GetComponentModel().DefaultExportProvider.GetExport<TestingOnly_WaitingService>().Value;
public void WaitForAsyncOperations(TimeSpan timeout, string featuresToWaitFor, bool waitForWorkspaceFirst = true)
{
if (waitForWorkspaceFirst || featuresToWaitFor == FeatureAttribute.Workspace)
{
WaitForProjectSystem(timeout);
}
GetWaitingService().WaitForAsyncOperations(timeout, featuresToWaitFor, waitForWorkspaceFirst);
}
public void WaitForAllAsyncOperations(TimeSpan timeout, params string[] featureNames)
{
if (featureNames.Contains(FeatureAttribute.Workspace))
{
WaitForProjectSystem(timeout);
}
GetWaitingService().WaitForAllAsyncOperations(_visualStudioWorkspace, timeout, featureNames);
}
public void WaitForAllAsyncOperationsOrFail(TimeSpan timeout, params string[] featureNames)
{
try
{
WaitForAllAsyncOperations(timeout, featureNames);
}
catch (Exception e)
{
var listenerProvider = GetComponentModel().DefaultExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>();
var messageBuilder = new StringBuilder("Failed to clean up listeners in a timely manner.");
foreach (var token in ((AsynchronousOperationListenerProvider)listenerProvider).GetTokens())
{
messageBuilder.AppendLine().Append($" {token}");
}
Environment.FailFast("Terminating test process due to unrecoverable timeout.", new TimeoutException(messageBuilder.ToString(), e));
}
}
private static void WaitForProjectSystem(TimeSpan timeout)
{
var operationProgressStatus = InvokeOnUIThread(_ => GetGlobalService<SVsOperationProgress, IVsOperationProgressStatusService>());
var stageStatus = operationProgressStatus.GetStageStatus(CommonOperationProgressStageIds.Intellisense);
stageStatus.WaitForCompletionAsync().Wait(timeout);
}
private static void LoadRoslynPackage()
{
var roslynPackageGuid = RoslynPackageId;
var vsShell = GetGlobalService<SVsShell, IVsShell>();
var hresult = vsShell.LoadPackage(ref roslynPackageGuid, out _);
Marshal.ThrowExceptionForHR(hresult);
}
public void CleanUpWorkspace()
=> InvokeOnUIThread(cancellationToken =>
{
LoadRoslynPackage();
_visualStudioWorkspace.TestHookPartialSolutionsDisabled = true;
});
/// <summary>
/// Reset options that are manipulated by integration tests back to their default values.
/// </summary>
public void ResetOptions()
{
ResetOption(CompletionOptions.EnableArgumentCompletionSnippets);
return;
// Local function
void ResetOption(IOption option)
{
if (option is IPerLanguageOption)
{
SetOption(new OptionKey(option, LanguageNames.CSharp), option.DefaultValue);
SetOption(new OptionKey(option, LanguageNames.VisualBasic), option.DefaultValue);
}
else
{
SetOption(new OptionKey(option), option.DefaultValue);
}
}
}
public void CleanUpWaitingService()
=> InvokeOnUIThread(cancellationToken =>
{
var provider = GetComponentModel().DefaultExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>();
if (provider == null)
{
throw new InvalidOperationException("The test waiting service could not be located.");
}
GetWaitingService().EnableActiveTokenTracking(true);
});
public void SetFeatureOption(string feature, string optionName, string language, string? valueString)
=> InvokeOnUIThread(cancellationToken =>
{
var option = GetOption(optionName, feature);
var value = TypeDescriptor.GetConverter(option.Type).ConvertFromString(valueString);
var optionKey = string.IsNullOrWhiteSpace(language)
? new OptionKey(option)
: new OptionKey(option, language);
SetOption(optionKey, value);
});
public string? GetWorkingFolder()
{
var service = _visualStudioWorkspace.Services.GetRequiredService<IPersistentStorageLocationService>();
return service.TryGetStorageLocation(_visualStudioWorkspace.CurrentSolution);
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IMethodReferenceOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Operations;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.IOperation)]
public class IOperationTests_IMethodReferenceOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void MethodReference_NoControlFlow()
{
// Verify method references with different kinds of instance references.
string source = @"
class C
{
public virtual int M1() => 0;
public static int M2() => 0;
void M(C c, System.Func<int> m1, System.Func<int> m2, System.Func<int> m3)
/*<bind>*/{
m1 = this.M1;
m2 = c.M1;
m3 = M2;
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm1 = this.M1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func<System.Int32>) (Syntax: 'm1 = this.M1')
Left:
IParameterReferenceOperation: m1 (OperationKind.ParameterReference, Type: System.Func<System.Int32>) (Syntax: 'm1')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32>, IsImplicit) (Syntax: 'this.M1')
Target:
IMethodReferenceOperation: System.Int32 C.M1() (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'this.M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm2 = c.M1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func<System.Int32>) (Syntax: 'm2 = c.M1')
Left:
IParameterReferenceOperation: m2 (OperationKind.ParameterReference, Type: System.Func<System.Int32>) (Syntax: 'm2')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32>, IsImplicit) (Syntax: 'c.M1')
Target:
IMethodReferenceOperation: System.Int32 C.M1() (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'c.M1')
Instance Receiver:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm3 = M2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func<System.Int32>) (Syntax: 'm3 = M2')
Left:
IParameterReferenceOperation: m3 (OperationKind.ParameterReference, Type: System.Func<System.Int32>) (Syntax: 'm3')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32>, IsImplicit) (Syntax: 'M2')
Target:
IMethodReferenceOperation: System.Int32 C.M2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'M2')
Instance Receiver:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void MethodReference_ControlFlowInReceiver()
{
string source = @"
class C
{
public int M1() => 0;
void M(C c1, C c2, System.Func<int> m)
/*<bind>*/{
m = (c1 ?? c2).M1;
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'm')
Value:
IParameterReferenceOperation: m (OperationKind.ParameterReference, Type: System.Func<System.Int32>) (Syntax: 'm')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm = (c1 ?? c2).M1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func<System.Int32>) (Syntax: 'm = (c1 ?? c2).M1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Func<System.Int32>, IsImplicit) (Syntax: 'm')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32>, IsImplicit) (Syntax: '(c1 ?? c2).M1')
Target:
IMethodReferenceOperation: System.Int32 C.M1() (OperationKind.MethodReference, Type: null) (Syntax: '(c1 ?? c2).M1')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1 ?? c2')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void MethodReference_ControlFlowInReceiver_StaticMethod()
{
string source = @"
class C
{
public static int M1() => 0;
void M(C c1, C c2, System.Func<int> m1, System.Func<int> m2)
/*<bind>*/{
m1 = c1.M1;
m2 = (c1 ?? c2).M1;
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'm1 = c1.M1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func<System.Int32>, IsInvalid) (Syntax: 'm1 = c1.M1')
Left:
IParameterReferenceOperation: m1 (OperationKind.ParameterReference, Type: System.Func<System.Int32>) (Syntax: 'm1')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32>, IsInvalid, IsImplicit) (Syntax: 'c1.M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'c1.M1')
Children(1):
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c1')
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'm2')
Value:
IParameterReferenceOperation: m2 (OperationKind.ParameterReference, Type: System.Func<System.Int32>) (Syntax: 'm2')
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c1')
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c1')
Leaving: {R2}
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c2')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'm2 = (c1 ?? c2).M1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func<System.Int32>, IsInvalid) (Syntax: 'm2 = (c1 ?? c2).M1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Func<System.Int32>, IsImplicit) (Syntax: 'm2')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32>, IsInvalid, IsImplicit) (Syntax: '(c1 ?? c2).M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: '(c1 ?? c2).M1')
Children(1):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c1 ?? c2')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B6]
Statements (0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(7,14): error CS0176: Member 'C.M1()' cannot be accessed with an instance reference; qualify it with a type name instead
// m1 = c1.M1;
Diagnostic(ErrorCode.ERR_ObjectProhibited, "c1.M1").WithArguments("C.M1()").WithLocation(7, 14),
// file.cs(8,14): error CS0176: Member 'C.M1()' cannot be accessed with an instance reference; qualify it with a type name instead
// m2 = (c1 ?? c2).M1;
Diagnostic(ErrorCode.ERR_ObjectProhibited, "(c1 ?? c2).M1").WithArguments("C.M1()").WithLocation(8, 14)
};
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 System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.IOperation)]
public class IOperationTests_IMethodReferenceOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void MethodReference_NoControlFlow()
{
// Verify method references with different kinds of instance references.
string source = @"
class C
{
public virtual int M1() => 0;
public static int M2() => 0;
void M(C c, System.Func<int> m1, System.Func<int> m2, System.Func<int> m3)
/*<bind>*/{
m1 = this.M1;
m2 = c.M1;
m3 = M2;
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm1 = this.M1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func<System.Int32>) (Syntax: 'm1 = this.M1')
Left:
IParameterReferenceOperation: m1 (OperationKind.ParameterReference, Type: System.Func<System.Int32>) (Syntax: 'm1')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32>, IsImplicit) (Syntax: 'this.M1')
Target:
IMethodReferenceOperation: System.Int32 C.M1() (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'this.M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm2 = c.M1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func<System.Int32>) (Syntax: 'm2 = c.M1')
Left:
IParameterReferenceOperation: m2 (OperationKind.ParameterReference, Type: System.Func<System.Int32>) (Syntax: 'm2')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32>, IsImplicit) (Syntax: 'c.M1')
Target:
IMethodReferenceOperation: System.Int32 C.M1() (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'c.M1')
Instance Receiver:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm3 = M2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func<System.Int32>) (Syntax: 'm3 = M2')
Left:
IParameterReferenceOperation: m3 (OperationKind.ParameterReference, Type: System.Func<System.Int32>) (Syntax: 'm3')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32>, IsImplicit) (Syntax: 'M2')
Target:
IMethodReferenceOperation: System.Int32 C.M2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'M2')
Instance Receiver:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void MethodReference_ControlFlowInReceiver()
{
string source = @"
class C
{
public int M1() => 0;
void M(C c1, C c2, System.Func<int> m)
/*<bind>*/{
m = (c1 ?? c2).M1;
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'm')
Value:
IParameterReferenceOperation: m (OperationKind.ParameterReference, Type: System.Func<System.Int32>) (Syntax: 'm')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm = (c1 ?? c2).M1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func<System.Int32>) (Syntax: 'm = (c1 ?? c2).M1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Func<System.Int32>, IsImplicit) (Syntax: 'm')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32>, IsImplicit) (Syntax: '(c1 ?? c2).M1')
Target:
IMethodReferenceOperation: System.Int32 C.M1() (OperationKind.MethodReference, Type: null) (Syntax: '(c1 ?? c2).M1')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1 ?? c2')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void MethodReference_ControlFlowInReceiver_StaticMethod()
{
string source = @"
class C
{
public static int M1() => 0;
void M(C c1, C c2, System.Func<int> m1, System.Func<int> m2)
/*<bind>*/{
m1 = c1.M1;
m2 = (c1 ?? c2).M1;
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'm1 = c1.M1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func<System.Int32>, IsInvalid) (Syntax: 'm1 = c1.M1')
Left:
IParameterReferenceOperation: m1 (OperationKind.ParameterReference, Type: System.Func<System.Int32>) (Syntax: 'm1')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32>, IsInvalid, IsImplicit) (Syntax: 'c1.M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'c1.M1')
Children(1):
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c1')
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'm2')
Value:
IParameterReferenceOperation: m2 (OperationKind.ParameterReference, Type: System.Func<System.Int32>) (Syntax: 'm2')
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c1')
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c1')
Leaving: {R2}
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c2')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'm2 = (c1 ?? c2).M1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func<System.Int32>, IsInvalid) (Syntax: 'm2 = (c1 ?? c2).M1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Func<System.Int32>, IsImplicit) (Syntax: 'm2')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32>, IsInvalid, IsImplicit) (Syntax: '(c1 ?? c2).M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: '(c1 ?? c2).M1')
Children(1):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c1 ?? c2')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B6]
Statements (0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(7,14): error CS0176: Member 'C.M1()' cannot be accessed with an instance reference; qualify it with a type name instead
// m1 = c1.M1;
Diagnostic(ErrorCode.ERR_ObjectProhibited, "c1.M1").WithArguments("C.M1()").WithLocation(7, 14),
// file.cs(8,14): error CS0176: Member 'C.M1()' cannot be accessed with an instance reference; qualify it with a type name instead
// m2 = (c1 ?? c2).M1;
Diagnostic(ErrorCode.ERR_ObjectProhibited, "(c1 ?? c2).M1").WithArguments("C.M1()").WithLocation(8, 14)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/CSharp/Test/Symbol/DocumentationComments/EventDocumentationCommentTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class EventDocumentationCommentTests : CSharpTestBase
{
private readonly CSharpCompilation _compilation;
private readonly NamespaceSymbol _acmeNamespace;
private readonly NamedTypeSymbol _widgetClass;
public EventDocumentationCommentTests()
{
_compilation = CreateCompilation(@"namespace Acme
{
class Widget: IProcess
{
public event System.Action E;
public event System.Action F { add { } remove { } }
}
}
");
_acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMember<NamespaceSymbol>("Acme");
_widgetClass = _acmeNamespace.GetMember<NamedTypeSymbol>("Widget");
}
[Fact]
public void TestFieldLikeEvent()
{
var eventSymbol = _widgetClass.GetMember<EventSymbol>("E");
Assert.Equal("E:Acme.Widget.E", eventSymbol.GetDocumentationCommentId());
Assert.Equal("M:Acme.Widget.add_E(System.Action)", eventSymbol.AddMethod.GetDocumentationCommentId());
Assert.Equal("M:Acme.Widget.remove_E(System.Action)", eventSymbol.RemoveMethod.GetDocumentationCommentId());
}
[Fact]
public void TestCustomEvent()
{
var eventSymbol = _widgetClass.GetMember<EventSymbol>("F");
Assert.Equal("E:Acme.Widget.F", eventSymbol.GetDocumentationCommentId());
Assert.Equal("M:Acme.Widget.add_F(System.Action)", eventSymbol.AddMethod.GetDocumentationCommentId());
Assert.Equal("M:Acme.Widget.remove_F(System.Action)", eventSymbol.RemoveMethod.GetDocumentationCommentId());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class EventDocumentationCommentTests : CSharpTestBase
{
private readonly CSharpCompilation _compilation;
private readonly NamespaceSymbol _acmeNamespace;
private readonly NamedTypeSymbol _widgetClass;
public EventDocumentationCommentTests()
{
_compilation = CreateCompilation(@"namespace Acme
{
class Widget: IProcess
{
public event System.Action E;
public event System.Action F { add { } remove { } }
}
}
");
_acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMember<NamespaceSymbol>("Acme");
_widgetClass = _acmeNamespace.GetMember<NamedTypeSymbol>("Widget");
}
[Fact]
public void TestFieldLikeEvent()
{
var eventSymbol = _widgetClass.GetMember<EventSymbol>("E");
Assert.Equal("E:Acme.Widget.E", eventSymbol.GetDocumentationCommentId());
Assert.Equal("M:Acme.Widget.add_E(System.Action)", eventSymbol.AddMethod.GetDocumentationCommentId());
Assert.Equal("M:Acme.Widget.remove_E(System.Action)", eventSymbol.RemoveMethod.GetDocumentationCommentId());
}
[Fact]
public void TestCustomEvent()
{
var eventSymbol = _widgetClass.GetMember<EventSymbol>("F");
Assert.Equal("E:Acme.Widget.F", eventSymbol.GetDocumentationCommentId());
Assert.Equal("M:Acme.Widget.add_F(System.Action)", eventSymbol.AddMethod.GetDocumentationCommentId());
Assert.Equal("M:Acme.Widget.remove_F(System.Action)", eventSymbol.RemoveMethod.GetDocumentationCommentId());
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/Core/RebuildTest/CompilationOptionsReaderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Rebuild;
using Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.Extensions.Logging;
using Xunit;
using Microsoft.Cci;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.Rebuild.UnitTests
{
public class CompilationOptionsReaderTests : CSharpTestBase
{
private CompilationOptionsReader GetOptionsReader(Compilation compilation)
{
compilation.VerifyDiagnostics();
var peBytes = compilation.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded));
var originalReader = new PEReader(peBytes);
var originalPdbReader = originalReader.GetEmbeddedPdbMetadataReader();
AssertEx.NotNull(originalPdbReader);
var factory = LoggerFactory.Create(configure => { });
var logger = factory.CreateLogger("RoundTripVerification");
return new CompilationOptionsReader(logger, originalPdbReader, originalReader);
}
[Fact]
public void PublicKeyNetModule()
{
var compilation = CreateCompilation(
options: TestOptions.DebugModule,
source: @"
class C { }
");
var reader = GetOptionsReader(compilation);
Assert.Null(reader.GetPublicKey());
}
[Theory]
[CombinatorialData]
public void OutputKind(OutputKind kind)
{
var compilation = CreateCompilation(
options: new CSharpCompilationOptions(outputKind: kind),
source: @"
class Program {
public static void Main() { }
}");
var reader = GetOptionsReader(compilation);
Assert.Equal(kind, reader.GetMetadataCompilationOptions().OptionToEnum<OutputKind>(CompilationOptionNames.OutputKind));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Rebuild;
using Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.Extensions.Logging;
using Xunit;
using Microsoft.Cci;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.Rebuild.UnitTests
{
public class CompilationOptionsReaderTests : CSharpTestBase
{
private CompilationOptionsReader GetOptionsReader(Compilation compilation)
{
compilation.VerifyDiagnostics();
var peBytes = compilation.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded));
var originalReader = new PEReader(peBytes);
var originalPdbReader = originalReader.GetEmbeddedPdbMetadataReader();
AssertEx.NotNull(originalPdbReader);
var factory = LoggerFactory.Create(configure => { });
var logger = factory.CreateLogger("RoundTripVerification");
return new CompilationOptionsReader(logger, originalPdbReader, originalReader);
}
[Fact]
public void PublicKeyNetModule()
{
var compilation = CreateCompilation(
options: TestOptions.DebugModule,
source: @"
class C { }
");
var reader = GetOptionsReader(compilation);
Assert.Null(reader.GetPublicKey());
}
[Theory]
[CombinatorialData]
public void OutputKind(OutputKind kind)
{
var compilation = CreateCompilation(
options: new CSharpCompilationOptions(outputKind: kind),
source: @"
class Program {
public static void Main() { }
}");
var reader = GetOptionsReader(compilation);
Assert.Equal(kind, reader.GetMetadataCompilationOptions().OptionToEnum<OutputKind>(CompilationOptionNames.OutputKind));
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/Test/Core/Diagnostics/CouldHaveMoreSpecificTypeAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
/// <summary>Analyzer used to identify local variables and fields that could be declared with more specific types.</summary>
public class SymbolCouldHaveMoreSpecificTypeAnalyzer : DiagnosticAnalyzer
{
private const string SystemCategory = "System";
public static readonly DiagnosticDescriptor LocalCouldHaveMoreSpecificTypeDescriptor = new DiagnosticDescriptor(
"LocalCouldHaveMoreSpecificType",
"Local Could Have More Specific Type",
"Local variable {0} could be declared with more specific type {1}.",
SystemCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor FieldCouldHaveMoreSpecificTypeDescriptor = new DiagnosticDescriptor(
"FieldCouldHaveMoreSpecificType",
"Field Could Have More Specific Type",
"Field {0} could be declared with more specific type {1}.",
SystemCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(LocalCouldHaveMoreSpecificTypeDescriptor, FieldCouldHaveMoreSpecificTypeDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(
(compilationContext) =>
{
Dictionary<IFieldSymbol, HashSet<INamedTypeSymbol>> fieldsSourceTypes = new Dictionary<IFieldSymbol, HashSet<INamedTypeSymbol>>();
compilationContext.RegisterOperationBlockStartAction(
(operationBlockContext) =>
{
if (operationBlockContext.OwningSymbol is IMethodSymbol containingMethod)
{
Dictionary<ILocalSymbol, HashSet<INamedTypeSymbol>> localsSourceTypes = new Dictionary<ILocalSymbol, HashSet<INamedTypeSymbol>>();
// Track explicit assignments.
operationBlockContext.RegisterOperationAction(
(operationContext) =>
{
if (operationContext.Operation is IAssignmentOperation assignment)
{
AssignTo(assignment.Target, localsSourceTypes, fieldsSourceTypes, assignment.Value);
}
else if (operationContext.Operation is IIncrementOrDecrementOperation increment)
{
SyntaxNode syntax = increment.Syntax;
ITypeSymbol type = increment.Type;
var constantValue = ConstantValue.Create(1);
bool isImplicit = increment.IsImplicit;
var value = new LiteralOperation(increment.SemanticModel, syntax, type, constantValue, isImplicit);
AssignTo(increment.Target, localsSourceTypes, fieldsSourceTypes, value);
}
else
{
throw TestExceptionUtilities.UnexpectedValue(operationContext.Operation);
}
},
OperationKind.SimpleAssignment,
OperationKind.CompoundAssignment,
OperationKind.Increment);
// Track arguments that match out or ref parameters.
operationBlockContext.RegisterOperationAction(
(operationContext) =>
{
IInvocationOperation invocation = (IInvocationOperation)operationContext.Operation;
foreach (IArgumentOperation argument in invocation.Arguments)
{
if (argument.Parameter.RefKind == RefKind.Out || argument.Parameter.RefKind == RefKind.Ref)
{
AssignTo(argument.Value, localsSourceTypes, fieldsSourceTypes, argument.Parameter.Type);
}
}
},
OperationKind.Invocation);
// Track local variable initializations.
operationBlockContext.RegisterOperationAction(
(operationContext) =>
{
IVariableInitializerOperation initializer = (IVariableInitializerOperation)operationContext.Operation;
// If the parent is a single variable declaration, just process that one variable. If it's a multi variable
// declaration, process all variables being assigned
if (initializer.Parent is IVariableDeclaratorOperation singleVariableDeclaration)
{
ILocalSymbol local = singleVariableDeclaration.Symbol;
AssignTo(local, local.Type, localsSourceTypes, initializer.Value);
}
else if (initializer.Parent is IVariableDeclarationOperation multiVariableDeclaration)
{
foreach (ILocalSymbol local in multiVariableDeclaration.GetDeclaredVariables())
{
AssignTo(local, local.Type, localsSourceTypes, initializer.Value);
}
}
},
OperationKind.VariableInitializer);
// Report locals that could have more specific types.
operationBlockContext.RegisterOperationBlockEndAction(
(operationBlockEndContext) =>
{
foreach (ILocalSymbol local in localsSourceTypes.Keys)
{
if (HasMoreSpecificSourceType(local, local.Type, localsSourceTypes, out var mostSpecificSourceType))
{
Report(operationBlockEndContext, local, mostSpecificSourceType, LocalCouldHaveMoreSpecificTypeDescriptor);
}
}
});
}
});
// Track field initializations.
compilationContext.RegisterOperationAction(
(operationContext) =>
{
IFieldInitializerOperation initializer = (IFieldInitializerOperation)operationContext.Operation;
foreach (IFieldSymbol initializedField in initializer.InitializedFields)
{
AssignTo(initializedField, initializedField.Type, fieldsSourceTypes, initializer.Value);
}
},
OperationKind.FieldInitializer);
// Report fields that could have more specific types.
compilationContext.RegisterCompilationEndAction(
(compilationEndContext) =>
{
foreach (IFieldSymbol field in fieldsSourceTypes.Keys)
{
if (HasMoreSpecificSourceType(field, field.Type, fieldsSourceTypes, out var mostSpecificSourceType))
{
Report(compilationEndContext, field, mostSpecificSourceType, FieldCouldHaveMoreSpecificTypeDescriptor);
}
}
});
});
}
private static bool HasMoreSpecificSourceType<SymbolType>(SymbolType symbol, ITypeSymbol symbolType, Dictionary<SymbolType, HashSet<INamedTypeSymbol>> symbolsSourceTypes, out INamedTypeSymbol commonSourceType)
{
if (symbolsSourceTypes.TryGetValue(symbol, out var sourceTypes))
{
commonSourceType = CommonType(sourceTypes);
if (commonSourceType != null && DerivesFrom(commonSourceType, (INamedTypeSymbol)symbolType))
{
return true;
}
}
commonSourceType = null;
return false;
}
private static INamedTypeSymbol CommonType(IEnumerable<INamedTypeSymbol> types)
{
foreach (INamedTypeSymbol type in types)
{
bool success = true;
foreach (INamedTypeSymbol testType in types)
{
if (type != testType)
{
if (!DerivesFrom(testType, type))
{
success = false;
break;
}
}
}
if (success)
{
return type;
}
}
return null;
}
private static bool DerivesFrom(INamedTypeSymbol derivedType, INamedTypeSymbol baseType)
{
if (derivedType.TypeKind == TypeKind.Class || derivedType.TypeKind == TypeKind.Structure)
{
INamedTypeSymbol derivedBaseType = derivedType.BaseType;
return derivedBaseType != null && (derivedBaseType.Equals(baseType) || DerivesFrom(derivedBaseType, baseType));
}
else if (derivedType.TypeKind == TypeKind.Interface)
{
if (derivedType.Interfaces.Contains(baseType))
{
return true;
}
foreach (INamedTypeSymbol baseInterface in derivedType.Interfaces)
{
if (DerivesFrom(baseInterface, baseType))
{
return true;
}
}
return baseType.TypeKind == TypeKind.Class && baseType.SpecialType == SpecialType.System_Object;
}
return false;
}
private static void AssignTo(IOperation target, Dictionary<ILocalSymbol, HashSet<INamedTypeSymbol>> localsSourceTypes, Dictionary<IFieldSymbol, HashSet<INamedTypeSymbol>> fieldsSourceTypes, IOperation sourceValue)
{
AssignTo(target, localsSourceTypes, fieldsSourceTypes, OriginalType(sourceValue));
}
private static void AssignTo(IOperation target, Dictionary<ILocalSymbol, HashSet<INamedTypeSymbol>> localsSourceTypes, Dictionary<IFieldSymbol, HashSet<INamedTypeSymbol>> fieldsSourceTypes, ITypeSymbol sourceType)
{
OperationKind targetKind = target.Kind;
if (targetKind == OperationKind.LocalReference)
{
ILocalSymbol targetLocal = ((ILocalReferenceOperation)target).Local;
AssignTo(targetLocal, targetLocal.Type, localsSourceTypes, sourceType);
}
else if (targetKind == OperationKind.FieldReference)
{
IFieldSymbol targetField = ((IFieldReferenceOperation)target).Field;
AssignTo(targetField, targetField.Type, fieldsSourceTypes, sourceType);
}
}
private static void AssignTo<SymbolType>(SymbolType target, ITypeSymbol targetType, Dictionary<SymbolType, HashSet<INamedTypeSymbol>> sourceTypes, IOperation sourceValue)
{
AssignTo(target, targetType, sourceTypes, OriginalType(sourceValue));
}
private static void AssignTo<SymbolType>(SymbolType target, ITypeSymbol targetType, Dictionary<SymbolType, HashSet<INamedTypeSymbol>> sourceTypes, ITypeSymbol sourceType)
{
if (sourceType != null && targetType != null)
{
TypeKind targetTypeKind = targetType.TypeKind;
TypeKind sourceTypeKind = sourceType.TypeKind;
// Don't suggest using an interface type instead of a class type, or vice versa.
if ((targetTypeKind == sourceTypeKind && (targetTypeKind == TypeKind.Class || targetTypeKind == TypeKind.Interface)) ||
(targetTypeKind == TypeKind.Class && (sourceTypeKind == TypeKind.Structure || sourceTypeKind == TypeKind.Interface) && targetType.SpecialType == SpecialType.System_Object))
{
if (!sourceTypes.TryGetValue(target, out var symbolSourceTypes))
{
symbolSourceTypes = new HashSet<INamedTypeSymbol>();
sourceTypes[target] = symbolSourceTypes;
}
symbolSourceTypes.Add((INamedTypeSymbol)sourceType);
}
}
}
private static ITypeSymbol OriginalType(IOperation value)
{
if (value.Kind == OperationKind.Conversion)
{
IConversionOperation conversion = (IConversionOperation)value;
if (conversion.IsImplicit)
{
return conversion.Operand.Type;
}
}
return value.Type;
}
private void Report(OperationBlockAnalysisContext context, ILocalSymbol local, ITypeSymbol moreSpecificType, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, local.Locations.FirstOrDefault(), local, moreSpecificType));
}
private void Report(CompilationAnalysisContext context, IFieldSymbol field, ITypeSymbol moreSpecificType, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, field.Locations.FirstOrDefault(), field, moreSpecificType));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
/// <summary>Analyzer used to identify local variables and fields that could be declared with more specific types.</summary>
public class SymbolCouldHaveMoreSpecificTypeAnalyzer : DiagnosticAnalyzer
{
private const string SystemCategory = "System";
public static readonly DiagnosticDescriptor LocalCouldHaveMoreSpecificTypeDescriptor = new DiagnosticDescriptor(
"LocalCouldHaveMoreSpecificType",
"Local Could Have More Specific Type",
"Local variable {0} could be declared with more specific type {1}.",
SystemCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor FieldCouldHaveMoreSpecificTypeDescriptor = new DiagnosticDescriptor(
"FieldCouldHaveMoreSpecificType",
"Field Could Have More Specific Type",
"Field {0} could be declared with more specific type {1}.",
SystemCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(LocalCouldHaveMoreSpecificTypeDescriptor, FieldCouldHaveMoreSpecificTypeDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(
(compilationContext) =>
{
Dictionary<IFieldSymbol, HashSet<INamedTypeSymbol>> fieldsSourceTypes = new Dictionary<IFieldSymbol, HashSet<INamedTypeSymbol>>();
compilationContext.RegisterOperationBlockStartAction(
(operationBlockContext) =>
{
if (operationBlockContext.OwningSymbol is IMethodSymbol containingMethod)
{
Dictionary<ILocalSymbol, HashSet<INamedTypeSymbol>> localsSourceTypes = new Dictionary<ILocalSymbol, HashSet<INamedTypeSymbol>>();
// Track explicit assignments.
operationBlockContext.RegisterOperationAction(
(operationContext) =>
{
if (operationContext.Operation is IAssignmentOperation assignment)
{
AssignTo(assignment.Target, localsSourceTypes, fieldsSourceTypes, assignment.Value);
}
else if (operationContext.Operation is IIncrementOrDecrementOperation increment)
{
SyntaxNode syntax = increment.Syntax;
ITypeSymbol type = increment.Type;
var constantValue = ConstantValue.Create(1);
bool isImplicit = increment.IsImplicit;
var value = new LiteralOperation(increment.SemanticModel, syntax, type, constantValue, isImplicit);
AssignTo(increment.Target, localsSourceTypes, fieldsSourceTypes, value);
}
else
{
throw TestExceptionUtilities.UnexpectedValue(operationContext.Operation);
}
},
OperationKind.SimpleAssignment,
OperationKind.CompoundAssignment,
OperationKind.Increment);
// Track arguments that match out or ref parameters.
operationBlockContext.RegisterOperationAction(
(operationContext) =>
{
IInvocationOperation invocation = (IInvocationOperation)operationContext.Operation;
foreach (IArgumentOperation argument in invocation.Arguments)
{
if (argument.Parameter.RefKind == RefKind.Out || argument.Parameter.RefKind == RefKind.Ref)
{
AssignTo(argument.Value, localsSourceTypes, fieldsSourceTypes, argument.Parameter.Type);
}
}
},
OperationKind.Invocation);
// Track local variable initializations.
operationBlockContext.RegisterOperationAction(
(operationContext) =>
{
IVariableInitializerOperation initializer = (IVariableInitializerOperation)operationContext.Operation;
// If the parent is a single variable declaration, just process that one variable. If it's a multi variable
// declaration, process all variables being assigned
if (initializer.Parent is IVariableDeclaratorOperation singleVariableDeclaration)
{
ILocalSymbol local = singleVariableDeclaration.Symbol;
AssignTo(local, local.Type, localsSourceTypes, initializer.Value);
}
else if (initializer.Parent is IVariableDeclarationOperation multiVariableDeclaration)
{
foreach (ILocalSymbol local in multiVariableDeclaration.GetDeclaredVariables())
{
AssignTo(local, local.Type, localsSourceTypes, initializer.Value);
}
}
},
OperationKind.VariableInitializer);
// Report locals that could have more specific types.
operationBlockContext.RegisterOperationBlockEndAction(
(operationBlockEndContext) =>
{
foreach (ILocalSymbol local in localsSourceTypes.Keys)
{
if (HasMoreSpecificSourceType(local, local.Type, localsSourceTypes, out var mostSpecificSourceType))
{
Report(operationBlockEndContext, local, mostSpecificSourceType, LocalCouldHaveMoreSpecificTypeDescriptor);
}
}
});
}
});
// Track field initializations.
compilationContext.RegisterOperationAction(
(operationContext) =>
{
IFieldInitializerOperation initializer = (IFieldInitializerOperation)operationContext.Operation;
foreach (IFieldSymbol initializedField in initializer.InitializedFields)
{
AssignTo(initializedField, initializedField.Type, fieldsSourceTypes, initializer.Value);
}
},
OperationKind.FieldInitializer);
// Report fields that could have more specific types.
compilationContext.RegisterCompilationEndAction(
(compilationEndContext) =>
{
foreach (IFieldSymbol field in fieldsSourceTypes.Keys)
{
if (HasMoreSpecificSourceType(field, field.Type, fieldsSourceTypes, out var mostSpecificSourceType))
{
Report(compilationEndContext, field, mostSpecificSourceType, FieldCouldHaveMoreSpecificTypeDescriptor);
}
}
});
});
}
private static bool HasMoreSpecificSourceType<SymbolType>(SymbolType symbol, ITypeSymbol symbolType, Dictionary<SymbolType, HashSet<INamedTypeSymbol>> symbolsSourceTypes, out INamedTypeSymbol commonSourceType)
{
if (symbolsSourceTypes.TryGetValue(symbol, out var sourceTypes))
{
commonSourceType = CommonType(sourceTypes);
if (commonSourceType != null && DerivesFrom(commonSourceType, (INamedTypeSymbol)symbolType))
{
return true;
}
}
commonSourceType = null;
return false;
}
private static INamedTypeSymbol CommonType(IEnumerable<INamedTypeSymbol> types)
{
foreach (INamedTypeSymbol type in types)
{
bool success = true;
foreach (INamedTypeSymbol testType in types)
{
if (type != testType)
{
if (!DerivesFrom(testType, type))
{
success = false;
break;
}
}
}
if (success)
{
return type;
}
}
return null;
}
private static bool DerivesFrom(INamedTypeSymbol derivedType, INamedTypeSymbol baseType)
{
if (derivedType.TypeKind == TypeKind.Class || derivedType.TypeKind == TypeKind.Structure)
{
INamedTypeSymbol derivedBaseType = derivedType.BaseType;
return derivedBaseType != null && (derivedBaseType.Equals(baseType) || DerivesFrom(derivedBaseType, baseType));
}
else if (derivedType.TypeKind == TypeKind.Interface)
{
if (derivedType.Interfaces.Contains(baseType))
{
return true;
}
foreach (INamedTypeSymbol baseInterface in derivedType.Interfaces)
{
if (DerivesFrom(baseInterface, baseType))
{
return true;
}
}
return baseType.TypeKind == TypeKind.Class && baseType.SpecialType == SpecialType.System_Object;
}
return false;
}
private static void AssignTo(IOperation target, Dictionary<ILocalSymbol, HashSet<INamedTypeSymbol>> localsSourceTypes, Dictionary<IFieldSymbol, HashSet<INamedTypeSymbol>> fieldsSourceTypes, IOperation sourceValue)
{
AssignTo(target, localsSourceTypes, fieldsSourceTypes, OriginalType(sourceValue));
}
private static void AssignTo(IOperation target, Dictionary<ILocalSymbol, HashSet<INamedTypeSymbol>> localsSourceTypes, Dictionary<IFieldSymbol, HashSet<INamedTypeSymbol>> fieldsSourceTypes, ITypeSymbol sourceType)
{
OperationKind targetKind = target.Kind;
if (targetKind == OperationKind.LocalReference)
{
ILocalSymbol targetLocal = ((ILocalReferenceOperation)target).Local;
AssignTo(targetLocal, targetLocal.Type, localsSourceTypes, sourceType);
}
else if (targetKind == OperationKind.FieldReference)
{
IFieldSymbol targetField = ((IFieldReferenceOperation)target).Field;
AssignTo(targetField, targetField.Type, fieldsSourceTypes, sourceType);
}
}
private static void AssignTo<SymbolType>(SymbolType target, ITypeSymbol targetType, Dictionary<SymbolType, HashSet<INamedTypeSymbol>> sourceTypes, IOperation sourceValue)
{
AssignTo(target, targetType, sourceTypes, OriginalType(sourceValue));
}
private static void AssignTo<SymbolType>(SymbolType target, ITypeSymbol targetType, Dictionary<SymbolType, HashSet<INamedTypeSymbol>> sourceTypes, ITypeSymbol sourceType)
{
if (sourceType != null && targetType != null)
{
TypeKind targetTypeKind = targetType.TypeKind;
TypeKind sourceTypeKind = sourceType.TypeKind;
// Don't suggest using an interface type instead of a class type, or vice versa.
if ((targetTypeKind == sourceTypeKind && (targetTypeKind == TypeKind.Class || targetTypeKind == TypeKind.Interface)) ||
(targetTypeKind == TypeKind.Class && (sourceTypeKind == TypeKind.Structure || sourceTypeKind == TypeKind.Interface) && targetType.SpecialType == SpecialType.System_Object))
{
if (!sourceTypes.TryGetValue(target, out var symbolSourceTypes))
{
symbolSourceTypes = new HashSet<INamedTypeSymbol>();
sourceTypes[target] = symbolSourceTypes;
}
symbolSourceTypes.Add((INamedTypeSymbol)sourceType);
}
}
}
private static ITypeSymbol OriginalType(IOperation value)
{
if (value.Kind == OperationKind.Conversion)
{
IConversionOperation conversion = (IConversionOperation)value;
if (conversion.IsImplicit)
{
return conversion.Operand.Type;
}
}
return value.Type;
}
private void Report(OperationBlockAnalysisContext context, ILocalSymbol local, ITypeSymbol moreSpecificType, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, local.Locations.FirstOrDefault(), local, moreSpecificType));
}
private void Report(CompilationAnalysisContext context, IFieldSymbol field, ITypeSymbol moreSpecificType, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, field.Locations.FirstOrDefault(), field, moreSpecificType));
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/VisualStudio/Core/Def/Implementation/PickMembers/PickMembersDialogViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers
{
internal class PickMembersDialogViewModel : AbstractNotifyPropertyChanged
{
private readonly List<MemberSymbolViewModel> _allMembers;
public List<MemberSymbolViewModel> MemberContainers { get; set; }
public List<OptionViewModel> Options { get; set; }
/// <summary>
/// <see langword="true"/> if 'Select All' was chosen. <see langword="false"/> if 'Deselect All' was chosen.
/// </summary>
public bool SelectedAll { get; set; }
internal PickMembersDialogViewModel(
IGlyphService glyphService,
ImmutableArray<ISymbol> members,
ImmutableArray<PickMembersOption> options,
bool selectAll)
{
_allMembers = members.Select(m => new MemberSymbolViewModel(m, glyphService)).ToList();
MemberContainers = _allMembers;
Options = options.Select(o => new OptionViewModel(o)).ToList();
if (selectAll)
{
SelectAll();
}
else
{
DeselectAll();
}
}
internal void Filter(string searchText)
{
searchText = searchText.Trim();
MemberContainers = searchText.Length == 0
? _allMembers
: _allMembers.Where(m => m.SymbolAutomationText.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0).ToList();
NotifyPropertyChanged(nameof(MemberContainers));
}
internal void DeselectAll()
{
SelectedAll = false;
foreach (var memberContainer in MemberContainers)
memberContainer.IsChecked = false;
}
internal void SelectAll()
{
SelectedAll = true;
foreach (var memberContainer in MemberContainers)
memberContainer.IsChecked = true;
}
private int? _selectedIndex;
public int? SelectedIndex
{
get
{
return _selectedIndex;
}
set
{
var newSelectedIndex = value == -1 ? null : value;
if (newSelectedIndex == _selectedIndex)
{
return;
}
_selectedIndex = newSelectedIndex;
NotifyPropertyChanged(nameof(CanMoveUp));
NotifyPropertyChanged(nameof(MoveUpAutomationText));
NotifyPropertyChanged(nameof(CanMoveDown));
NotifyPropertyChanged(nameof(MoveDownAutomationText));
}
}
public string MoveUpAutomationText
{
get
{
if (!CanMoveUp)
{
return string.Empty;
}
return string.Format(ServicesVSResources.Move_0_above_1, MemberContainers[SelectedIndex.Value].SymbolAutomationText, MemberContainers[SelectedIndex.Value - 1].SymbolAutomationText);
}
}
public string MoveDownAutomationText
{
get
{
if (!CanMoveDown)
{
return string.Empty;
}
return string.Format(ServicesVSResources.Move_0_below_1, MemberContainers[SelectedIndex.Value].SymbolAutomationText, MemberContainers[SelectedIndex.Value + 1].SymbolAutomationText);
}
}
[MemberNotNullWhen(true, nameof(SelectedIndex))]
public bool CanMoveUp
{
get
{
if (!SelectedIndex.HasValue)
{
return false;
}
var index = SelectedIndex.Value;
return index > 0;
}
}
[MemberNotNullWhen(true, nameof(SelectedIndex))]
public bool CanMoveDown
{
get
{
if (!SelectedIndex.HasValue)
{
return false;
}
var index = SelectedIndex.Value;
return index < MemberContainers.Count - 1;
}
}
internal void MoveUp()
{
Contract.ThrowIfFalse(CanMoveUp);
var index = SelectedIndex.Value;
Move(MemberContainers, index, delta: -1);
}
internal void MoveDown()
{
Contract.ThrowIfFalse(CanMoveDown);
var index = SelectedIndex.Value;
Move(MemberContainers, index, delta: 1);
}
private void Move(List<MemberSymbolViewModel> list, int index, int delta)
{
var param = list[index];
list.RemoveAt(index);
list.Insert(index + delta, param);
SelectedIndex += delta;
}
internal class MemberSymbolViewModel : SymbolViewModel<ISymbol>
{
public MemberSymbolViewModel(ISymbol symbol, IGlyphService glyphService) : base(symbol, glyphService)
{
}
}
internal class OptionViewModel : AbstractNotifyPropertyChanged
{
public PickMembersOption Option { get; }
public string Title { get; }
public OptionViewModel(PickMembersOption option)
{
Option = option;
Title = option.Title;
IsChecked = option.Value;
}
private bool _isChecked;
public bool IsChecked
{
get => _isChecked;
set
{
Option.Value = value;
SetProperty(ref _isChecked, value);
}
}
public string MemberAutomationText => Option.Title;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers
{
internal class PickMembersDialogViewModel : AbstractNotifyPropertyChanged
{
private readonly List<MemberSymbolViewModel> _allMembers;
public List<MemberSymbolViewModel> MemberContainers { get; set; }
public List<OptionViewModel> Options { get; set; }
/// <summary>
/// <see langword="true"/> if 'Select All' was chosen. <see langword="false"/> if 'Deselect All' was chosen.
/// </summary>
public bool SelectedAll { get; set; }
internal PickMembersDialogViewModel(
IGlyphService glyphService,
ImmutableArray<ISymbol> members,
ImmutableArray<PickMembersOption> options,
bool selectAll)
{
_allMembers = members.Select(m => new MemberSymbolViewModel(m, glyphService)).ToList();
MemberContainers = _allMembers;
Options = options.Select(o => new OptionViewModel(o)).ToList();
if (selectAll)
{
SelectAll();
}
else
{
DeselectAll();
}
}
internal void Filter(string searchText)
{
searchText = searchText.Trim();
MemberContainers = searchText.Length == 0
? _allMembers
: _allMembers.Where(m => m.SymbolAutomationText.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0).ToList();
NotifyPropertyChanged(nameof(MemberContainers));
}
internal void DeselectAll()
{
SelectedAll = false;
foreach (var memberContainer in MemberContainers)
memberContainer.IsChecked = false;
}
internal void SelectAll()
{
SelectedAll = true;
foreach (var memberContainer in MemberContainers)
memberContainer.IsChecked = true;
}
private int? _selectedIndex;
public int? SelectedIndex
{
get
{
return _selectedIndex;
}
set
{
var newSelectedIndex = value == -1 ? null : value;
if (newSelectedIndex == _selectedIndex)
{
return;
}
_selectedIndex = newSelectedIndex;
NotifyPropertyChanged(nameof(CanMoveUp));
NotifyPropertyChanged(nameof(MoveUpAutomationText));
NotifyPropertyChanged(nameof(CanMoveDown));
NotifyPropertyChanged(nameof(MoveDownAutomationText));
}
}
public string MoveUpAutomationText
{
get
{
if (!CanMoveUp)
{
return string.Empty;
}
return string.Format(ServicesVSResources.Move_0_above_1, MemberContainers[SelectedIndex.Value].SymbolAutomationText, MemberContainers[SelectedIndex.Value - 1].SymbolAutomationText);
}
}
public string MoveDownAutomationText
{
get
{
if (!CanMoveDown)
{
return string.Empty;
}
return string.Format(ServicesVSResources.Move_0_below_1, MemberContainers[SelectedIndex.Value].SymbolAutomationText, MemberContainers[SelectedIndex.Value + 1].SymbolAutomationText);
}
}
[MemberNotNullWhen(true, nameof(SelectedIndex))]
public bool CanMoveUp
{
get
{
if (!SelectedIndex.HasValue)
{
return false;
}
var index = SelectedIndex.Value;
return index > 0;
}
}
[MemberNotNullWhen(true, nameof(SelectedIndex))]
public bool CanMoveDown
{
get
{
if (!SelectedIndex.HasValue)
{
return false;
}
var index = SelectedIndex.Value;
return index < MemberContainers.Count - 1;
}
}
internal void MoveUp()
{
Contract.ThrowIfFalse(CanMoveUp);
var index = SelectedIndex.Value;
Move(MemberContainers, index, delta: -1);
}
internal void MoveDown()
{
Contract.ThrowIfFalse(CanMoveDown);
var index = SelectedIndex.Value;
Move(MemberContainers, index, delta: 1);
}
private void Move(List<MemberSymbolViewModel> list, int index, int delta)
{
var param = list[index];
list.RemoveAt(index);
list.Insert(index + delta, param);
SelectedIndex += delta;
}
internal class MemberSymbolViewModel : SymbolViewModel<ISymbol>
{
public MemberSymbolViewModel(ISymbol symbol, IGlyphService glyphService) : base(symbol, glyphService)
{
}
}
internal class OptionViewModel : AbstractNotifyPropertyChanged
{
public PickMembersOption Option { get; }
public string Title { get; }
public OptionViewModel(PickMembersOption option)
{
Option = option;
Title = option.Title;
IsChecked = option.Value;
}
private bool _isChecked;
public bool IsChecked
{
get => _isChecked;
set
{
Option.Value = value;
SetProperty(ref _isChecked, value);
}
}
public string MemberAutomationText => Option.Title;
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Tools/BuildValidator/PEReaderExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text;
namespace BuildValidator
{
public class PEExportTable
{
private readonly Dictionary<string, int> _namedExportRva;
private PEExportTable(PEReader peReader)
{
Debug.Assert(peReader.PEHeaders is object);
Debug.Assert(peReader.PEHeaders.PEHeader is object);
_namedExportRva = new Dictionary<string, int>();
DirectoryEntry exportTable = peReader.PEHeaders.PEHeader.ExportTableDirectory;
if ((exportTable.Size == 0) || (exportTable.RelativeVirtualAddress == 0))
return;
PEMemoryBlock peImage = peReader.GetEntireImage();
BlobReader exportTableHeader = peImage.GetReader(peReader.GetOffset(exportTable.RelativeVirtualAddress), exportTable.Size);
if (exportTableHeader.Length == 0)
{
return;
}
// +0x00: reserved
exportTableHeader.ReadUInt32();
// +0x04: TODO: time/date stamp
exportTableHeader.ReadUInt32();
// +0x08: major version
exportTableHeader.ReadUInt16();
// +0x0A: minor version
exportTableHeader.ReadUInt16();
// +0x0C: DLL name RVA
exportTableHeader.ReadUInt32();
// +0x10: ordinal base
int minOrdinal = exportTableHeader.ReadInt32();
// +0x14: number of entries in the address table
int addressEntryCount = exportTableHeader.ReadInt32();
// +0x18: number of name pointers
int namePointerCount = exportTableHeader.ReadInt32();
// +0x1C: export address table RVA
int addressTableRVA = exportTableHeader.ReadInt32();
// +0x20: name pointer RVA
int namePointerRVA = exportTableHeader.ReadInt32();
// +0x24: ordinal table RVA
int ordinalTableRVA = exportTableHeader.ReadInt32();
int[] addressTable = new int[addressEntryCount];
BlobReader addressTableReader = peImage.GetReader(peReader.GetOffset(addressTableRVA), sizeof(int) * addressEntryCount);
for (int entryIndex = 0; entryIndex < addressEntryCount; entryIndex++)
{
addressTable[entryIndex] = addressTableReader.ReadInt32();
}
ushort[] ordinalTable = new ushort[namePointerCount];
BlobReader ordinalTableReader = peImage.GetReader(peReader.GetOffset(ordinalTableRVA), sizeof(ushort) * namePointerCount);
for (int entryIndex = 0; entryIndex < namePointerCount; entryIndex++)
{
ushort ordinalIndex = ordinalTableReader.ReadUInt16();
ordinalTable[entryIndex] = ordinalIndex;
}
BlobReader namePointerReader = peImage.GetReader(peReader.GetOffset(namePointerRVA), sizeof(int) * namePointerCount);
for (int entryIndex = 0; entryIndex < namePointerCount; entryIndex++)
{
int nameRVA = namePointerReader.ReadInt32();
if (nameRVA != 0)
{
int nameOffset = peReader.GetOffset(nameRVA);
BlobReader nameReader = peImage.GetReader(nameOffset, peImage.Length - nameOffset);
StringBuilder nameBuilder = new StringBuilder();
for (byte ascii; (ascii = nameReader.ReadByte()) != 0;)
{
nameBuilder.Append((char)ascii);
}
_namedExportRva.Add(nameBuilder.ToString(), addressTable[ordinalTable[entryIndex]]);
}
}
}
public static PEExportTable Parse(PEReader peReader)
{
return new PEExportTable(peReader);
}
public bool TryGetValue(string exportName, out int rva) => _namedExportRva.TryGetValue(exportName, out rva);
}
public static class PEReaderExtensions
{
/// <summary>
/// Get the index in the image byte array corresponding to the RVA
/// </summary>
/// <param name="reader">PE reader representing the executable image to parse</param>
/// <param name="rva">The relative virtual address</param>
public static int GetOffset(this PEReader reader, int rva)
{
int index = reader.PEHeaders.GetContainingSectionIndex(rva);
if (index == -1)
{
throw new BadImageFormatException("Failed to convert invalid RVA to offset: " + rva);
}
SectionHeader containingSection = reader.PEHeaders.SectionHeaders[index];
return rva - containingSection.VirtualAddress + containingSection.PointerToRawData;
}
/// <summary>
/// Parse export table directory for a given PE reader.
/// </summary>
/// <param name="reader">PE reader representing the executable image to parse</param>
public static PEExportTable GetExportTable(this PEReader reader)
{
return PEExportTable.Parse(reader);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text;
namespace BuildValidator
{
public class PEExportTable
{
private readonly Dictionary<string, int> _namedExportRva;
private PEExportTable(PEReader peReader)
{
Debug.Assert(peReader.PEHeaders is object);
Debug.Assert(peReader.PEHeaders.PEHeader is object);
_namedExportRva = new Dictionary<string, int>();
DirectoryEntry exportTable = peReader.PEHeaders.PEHeader.ExportTableDirectory;
if ((exportTable.Size == 0) || (exportTable.RelativeVirtualAddress == 0))
return;
PEMemoryBlock peImage = peReader.GetEntireImage();
BlobReader exportTableHeader = peImage.GetReader(peReader.GetOffset(exportTable.RelativeVirtualAddress), exportTable.Size);
if (exportTableHeader.Length == 0)
{
return;
}
// +0x00: reserved
exportTableHeader.ReadUInt32();
// +0x04: TODO: time/date stamp
exportTableHeader.ReadUInt32();
// +0x08: major version
exportTableHeader.ReadUInt16();
// +0x0A: minor version
exportTableHeader.ReadUInt16();
// +0x0C: DLL name RVA
exportTableHeader.ReadUInt32();
// +0x10: ordinal base
int minOrdinal = exportTableHeader.ReadInt32();
// +0x14: number of entries in the address table
int addressEntryCount = exportTableHeader.ReadInt32();
// +0x18: number of name pointers
int namePointerCount = exportTableHeader.ReadInt32();
// +0x1C: export address table RVA
int addressTableRVA = exportTableHeader.ReadInt32();
// +0x20: name pointer RVA
int namePointerRVA = exportTableHeader.ReadInt32();
// +0x24: ordinal table RVA
int ordinalTableRVA = exportTableHeader.ReadInt32();
int[] addressTable = new int[addressEntryCount];
BlobReader addressTableReader = peImage.GetReader(peReader.GetOffset(addressTableRVA), sizeof(int) * addressEntryCount);
for (int entryIndex = 0; entryIndex < addressEntryCount; entryIndex++)
{
addressTable[entryIndex] = addressTableReader.ReadInt32();
}
ushort[] ordinalTable = new ushort[namePointerCount];
BlobReader ordinalTableReader = peImage.GetReader(peReader.GetOffset(ordinalTableRVA), sizeof(ushort) * namePointerCount);
for (int entryIndex = 0; entryIndex < namePointerCount; entryIndex++)
{
ushort ordinalIndex = ordinalTableReader.ReadUInt16();
ordinalTable[entryIndex] = ordinalIndex;
}
BlobReader namePointerReader = peImage.GetReader(peReader.GetOffset(namePointerRVA), sizeof(int) * namePointerCount);
for (int entryIndex = 0; entryIndex < namePointerCount; entryIndex++)
{
int nameRVA = namePointerReader.ReadInt32();
if (nameRVA != 0)
{
int nameOffset = peReader.GetOffset(nameRVA);
BlobReader nameReader = peImage.GetReader(nameOffset, peImage.Length - nameOffset);
StringBuilder nameBuilder = new StringBuilder();
for (byte ascii; (ascii = nameReader.ReadByte()) != 0;)
{
nameBuilder.Append((char)ascii);
}
_namedExportRva.Add(nameBuilder.ToString(), addressTable[ordinalTable[entryIndex]]);
}
}
}
public static PEExportTable Parse(PEReader peReader)
{
return new PEExportTable(peReader);
}
public bool TryGetValue(string exportName, out int rva) => _namedExportRva.TryGetValue(exportName, out rva);
}
public static class PEReaderExtensions
{
/// <summary>
/// Get the index in the image byte array corresponding to the RVA
/// </summary>
/// <param name="reader">PE reader representing the executable image to parse</param>
/// <param name="rva">The relative virtual address</param>
public static int GetOffset(this PEReader reader, int rva)
{
int index = reader.PEHeaders.GetContainingSectionIndex(rva);
if (index == -1)
{
throw new BadImageFormatException("Failed to convert invalid RVA to offset: " + rva);
}
SectionHeader containingSection = reader.PEHeaders.SectionHeaders[index];
return rva - containingSection.VirtualAddress + containingSection.PointerToRawData;
}
/// <summary>
/// Parse export table directory for a given PE reader.
/// </summary>
/// <param name="reader">PE reader representing the executable image to parse</param>
public static PEExportTable GetExportTable(this PEReader reader)
{
return PEExportTable.Parse(reader);
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenShortCircuitOperatorTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenShortCircuitOperatorTests : CSharpTestBase
{
[Fact]
public void TestShortCircuitAnd()
{
var source = @"
class C
{
public static bool Test(char ch, bool result)
{
System.Console.WriteLine(ch);
return result;
}
public static void Main()
{
const bool c1 = true;
const bool c2 = false;
bool v1 = true;
bool v2 = false;
System.Console.WriteLine(true && true);
System.Console.WriteLine(true && false);
System.Console.WriteLine(false && true);
System.Console.WriteLine(false && false);
System.Console.WriteLine(c1 && c1);
System.Console.WriteLine(c1 && c2);
System.Console.WriteLine(c2 && c1);
System.Console.WriteLine(c2 && c2);
System.Console.WriteLine(v1 && v1);
System.Console.WriteLine(v1 && v2);
System.Console.WriteLine(v2 && v1);
System.Console.WriteLine(v2 && v2);
System.Console.WriteLine(Test('L', true) && Test('R', true));
System.Console.WriteLine(Test('L', true) && Test('R', false));
System.Console.WriteLine(Test('L', false) && Test('R', true));
System.Console.WriteLine(Test('L', false) && Test('R', false));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
True
False
False
False
True
False
False
False
True
False
False
False
L
R
True
L
R
False
L
False
L
False
");
compilation.VerifyIL("C.Main", @"
{
// Code size 189 (0xbd)
.maxstack 2
.locals init (bool V_0, //v1
bool V_1) //v2
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: ldc.i4.1
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldc.i4.0
IL_000b: call ""void System.Console.WriteLine(bool)""
IL_0010: ldc.i4.0
IL_0011: call ""void System.Console.WriteLine(bool)""
IL_0016: ldc.i4.0
IL_0017: call ""void System.Console.WriteLine(bool)""
IL_001c: ldc.i4.1
IL_001d: call ""void System.Console.WriteLine(bool)""
IL_0022: ldc.i4.0
IL_0023: call ""void System.Console.WriteLine(bool)""
IL_0028: ldc.i4.0
IL_0029: call ""void System.Console.WriteLine(bool)""
IL_002e: ldc.i4.0
IL_002f: call ""void System.Console.WriteLine(bool)""
IL_0034: ldloc.0
IL_0035: ldloc.0
IL_0036: and
IL_0037: call ""void System.Console.WriteLine(bool)""
IL_003c: ldloc.0
IL_003d: ldloc.1
IL_003e: and
IL_003f: call ""void System.Console.WriteLine(bool)""
IL_0044: ldloc.1
IL_0045: ldloc.0
IL_0046: and
IL_0047: call ""void System.Console.WriteLine(bool)""
IL_004c: ldloc.1
IL_004d: ldloc.1
IL_004e: and
IL_004f: call ""void System.Console.WriteLine(bool)""
IL_0054: ldc.i4.s 76
IL_0056: ldc.i4.1
IL_0057: call ""bool C.Test(char, bool)""
IL_005c: brfalse.s IL_0068
IL_005e: ldc.i4.s 82
IL_0060: ldc.i4.1
IL_0061: call ""bool C.Test(char, bool)""
IL_0066: br.s IL_0069
IL_0068: ldc.i4.0
IL_0069: call ""void System.Console.WriteLine(bool)""
IL_006e: ldc.i4.s 76
IL_0070: ldc.i4.1
IL_0071: call ""bool C.Test(char, bool)""
IL_0076: brfalse.s IL_0082
IL_0078: ldc.i4.s 82
IL_007a: ldc.i4.0
IL_007b: call ""bool C.Test(char, bool)""
IL_0080: br.s IL_0083
IL_0082: ldc.i4.0
IL_0083: call ""void System.Console.WriteLine(bool)""
IL_0088: ldc.i4.s 76
IL_008a: ldc.i4.0
IL_008b: call ""bool C.Test(char, bool)""
IL_0090: brfalse.s IL_009c
IL_0092: ldc.i4.s 82
IL_0094: ldc.i4.1
IL_0095: call ""bool C.Test(char, bool)""
IL_009a: br.s IL_009d
IL_009c: ldc.i4.0
IL_009d: call ""void System.Console.WriteLine(bool)""
IL_00a2: ldc.i4.s 76
IL_00a4: ldc.i4.0
IL_00a5: call ""bool C.Test(char, bool)""
IL_00aa: brfalse.s IL_00b6
IL_00ac: ldc.i4.s 82
IL_00ae: ldc.i4.0
IL_00af: call ""bool C.Test(char, bool)""
IL_00b4: br.s IL_00b7
IL_00b6: ldc.i4.0
IL_00b7: call ""void System.Console.WriteLine(bool)""
IL_00bc: ret
}");
}
[Fact]
public void TestShortCircuitOr()
{
var source = @"
class C
{
public static bool Test(char ch, bool result)
{
System.Console.WriteLine(ch);
return result;
}
public static void Main()
{
const bool c1 = true;
const bool c2 = false;
bool v1 = true;
bool v2 = false;
System.Console.WriteLine(true || true);
System.Console.WriteLine(true || false);
System.Console.WriteLine(false || true);
System.Console.WriteLine(false || false);
System.Console.WriteLine(c1 || c1);
System.Console.WriteLine(c1 || c2);
System.Console.WriteLine(c2 || c1);
System.Console.WriteLine(c2 || c2);
System.Console.WriteLine(v1 || v1);
System.Console.WriteLine(v1 || v2);
System.Console.WriteLine(v2 || v1);
System.Console.WriteLine(v2 || v2);
System.Console.WriteLine(Test('L', true) || Test('R', true));
System.Console.WriteLine(Test('L', true) || Test('R', false));
System.Console.WriteLine(Test('L', false) || Test('R', true));
System.Console.WriteLine(Test('L', false) || Test('R', false));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
True
True
True
False
True
True
True
False
True
True
True
False
L
True
L
True
L
R
True
L
R
False
");
compilation.VerifyIL("C.Main", @"
{
// Code size 189 (0xbd)
.maxstack 2
.locals init (bool V_0, //v1
bool V_1) //v2
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: ldc.i4.1
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldc.i4.1
IL_000b: call ""void System.Console.WriteLine(bool)""
IL_0010: ldc.i4.1
IL_0011: call ""void System.Console.WriteLine(bool)""
IL_0016: ldc.i4.0
IL_0017: call ""void System.Console.WriteLine(bool)""
IL_001c: ldc.i4.1
IL_001d: call ""void System.Console.WriteLine(bool)""
IL_0022: ldc.i4.1
IL_0023: call ""void System.Console.WriteLine(bool)""
IL_0028: ldc.i4.1
IL_0029: call ""void System.Console.WriteLine(bool)""
IL_002e: ldc.i4.0
IL_002f: call ""void System.Console.WriteLine(bool)""
IL_0034: ldloc.0
IL_0035: ldloc.0
IL_0036: or
IL_0037: call ""void System.Console.WriteLine(bool)""
IL_003c: ldloc.0
IL_003d: ldloc.1
IL_003e: or
IL_003f: call ""void System.Console.WriteLine(bool)""
IL_0044: ldloc.1
IL_0045: ldloc.0
IL_0046: or
IL_0047: call ""void System.Console.WriteLine(bool)""
IL_004c: ldloc.1
IL_004d: ldloc.1
IL_004e: or
IL_004f: call ""void System.Console.WriteLine(bool)""
IL_0054: ldc.i4.s 76
IL_0056: ldc.i4.1
IL_0057: call ""bool C.Test(char, bool)""
IL_005c: brtrue.s IL_0068
IL_005e: ldc.i4.s 82
IL_0060: ldc.i4.1
IL_0061: call ""bool C.Test(char, bool)""
IL_0066: br.s IL_0069
IL_0068: ldc.i4.1
IL_0069: call ""void System.Console.WriteLine(bool)""
IL_006e: ldc.i4.s 76
IL_0070: ldc.i4.1
IL_0071: call ""bool C.Test(char, bool)""
IL_0076: brtrue.s IL_0082
IL_0078: ldc.i4.s 82
IL_007a: ldc.i4.0
IL_007b: call ""bool C.Test(char, bool)""
IL_0080: br.s IL_0083
IL_0082: ldc.i4.1
IL_0083: call ""void System.Console.WriteLine(bool)""
IL_0088: ldc.i4.s 76
IL_008a: ldc.i4.0
IL_008b: call ""bool C.Test(char, bool)""
IL_0090: brtrue.s IL_009c
IL_0092: ldc.i4.s 82
IL_0094: ldc.i4.1
IL_0095: call ""bool C.Test(char, bool)""
IL_009a: br.s IL_009d
IL_009c: ldc.i4.1
IL_009d: call ""void System.Console.WriteLine(bool)""
IL_00a2: ldc.i4.s 76
IL_00a4: ldc.i4.0
IL_00a5: call ""bool C.Test(char, bool)""
IL_00aa: brtrue.s IL_00b6
IL_00ac: ldc.i4.s 82
IL_00ae: ldc.i4.0
IL_00af: call ""bool C.Test(char, bool)""
IL_00b4: br.s IL_00b7
IL_00b6: ldc.i4.1
IL_00b7: call ""void System.Console.WriteLine(bool)""
IL_00bc: ret
}");
}
[Fact]
public void TestChainedShortCircuitOperators()
{
var source = @"
class C
{
public static bool Test(char ch, bool result)
{
System.Console.WriteLine(ch);
return result;
}
public static void Main()
{
// AND AND
System.Console.WriteLine(Test('A', true) && Test('B', true) && Test('C' , true));
System.Console.WriteLine(Test('A', true) && Test('B', true) && Test('C' , false));
System.Console.WriteLine(Test('A', true) && Test('B', false) && Test('C' , true));
System.Console.WriteLine(Test('A', true) && Test('B', false) && Test('C' , false));
System.Console.WriteLine(Test('A', false) && Test('B', true) && Test('C' , true));
System.Console.WriteLine(Test('A', false) && Test('B', true) && Test('C' , false));
System.Console.WriteLine(Test('A', false) && Test('B', false) && Test('C' , true));
System.Console.WriteLine(Test('A', false) && Test('B', false) && Test('C' , false));
// AND OR
System.Console.WriteLine(Test('A', true) && Test('B', true) || Test('C' , true));
System.Console.WriteLine(Test('A', true) && Test('B', true) || Test('C' , false));
System.Console.WriteLine(Test('A', true) && Test('B', false) || Test('C' , true));
System.Console.WriteLine(Test('A', true) && Test('B', false) || Test('C' , false));
System.Console.WriteLine(Test('A', false) && Test('B', true) || Test('C' , true));
System.Console.WriteLine(Test('A', false) && Test('B', true) || Test('C' , false));
System.Console.WriteLine(Test('A', false) && Test('B', false) || Test('C' , true));
System.Console.WriteLine(Test('A', false) && Test('B', false) || Test('C' , false));
// OR AND
System.Console.WriteLine(Test('A', true) || Test('B', true) && Test('C' , true));
System.Console.WriteLine(Test('A', true) || Test('B', true) && Test('C' , false));
System.Console.WriteLine(Test('A', true) || Test('B', false) && Test('C' , true));
System.Console.WriteLine(Test('A', true) || Test('B', false) && Test('C' , false));
System.Console.WriteLine(Test('A', false) || Test('B', true) && Test('C' , true));
System.Console.WriteLine(Test('A', false) || Test('B', true) && Test('C' , false));
System.Console.WriteLine(Test('A', false) || Test('B', false) && Test('C' , true));
System.Console.WriteLine(Test('A', false) || Test('B', false) && Test('C' , false));
// OR OR
System.Console.WriteLine(Test('A', true) || Test('B', true) || Test('C' , true));
System.Console.WriteLine(Test('A', true) || Test('B', true) || Test('C' , false));
System.Console.WriteLine(Test('A', true) || Test('B', false) || Test('C' , true));
System.Console.WriteLine(Test('A', true) || Test('B', false) || Test('C' , false));
System.Console.WriteLine(Test('A', false) || Test('B', true) || Test('C' , true));
System.Console.WriteLine(Test('A', false) || Test('B', true) || Test('C' , false));
System.Console.WriteLine(Test('A', false) || Test('B', false) || Test('C' , true));
System.Console.WriteLine(Test('A', false) || Test('B', false) || Test('C' , false));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
A
B
C
True
A
B
C
False
A
B
False
A
B
False
A
False
A
False
A
False
A
False
A
B
True
A
B
True
A
B
C
True
A
B
C
False
A
C
True
A
C
False
A
C
True
A
C
False
A
True
A
True
A
True
A
True
A
B
C
True
A
B
C
False
A
B
False
A
B
False
A
True
A
True
A
True
A
True
A
B
True
A
B
True
A
B
C
True
A
B
C
False
");
compilation.VerifyIL("C.Main", @"{
// Code size 1177 (0x499)
.maxstack 2
IL_0000: ldc.i4.s 65
IL_0002: ldc.i4.1
IL_0003: call ""bool C.Test(char, bool)""
IL_0008: brfalse.s IL_001e
IL_000a: ldc.i4.s 66
IL_000c: ldc.i4.1
IL_000d: call ""bool C.Test(char, bool)""
IL_0012: brfalse.s IL_001e
IL_0014: ldc.i4.s 67
IL_0016: ldc.i4.1
IL_0017: call ""bool C.Test(char, bool)""
IL_001c: br.s IL_001f
IL_001e: ldc.i4.0
IL_001f: call ""void System.Console.WriteLine(bool)""
IL_0024: ldc.i4.s 65
IL_0026: ldc.i4.1
IL_0027: call ""bool C.Test(char, bool)""
IL_002c: brfalse.s IL_0042
IL_002e: ldc.i4.s 66
IL_0030: ldc.i4.1
IL_0031: call ""bool C.Test(char, bool)""
IL_0036: brfalse.s IL_0042
IL_0038: ldc.i4.s 67
IL_003a: ldc.i4.0
IL_003b: call ""bool C.Test(char, bool)""
IL_0040: br.s IL_0043
IL_0042: ldc.i4.0
IL_0043: call ""void System.Console.WriteLine(bool)""
IL_0048: ldc.i4.s 65
IL_004a: ldc.i4.1
IL_004b: call ""bool C.Test(char, bool)""
IL_0050: brfalse.s IL_0066
IL_0052: ldc.i4.s 66
IL_0054: ldc.i4.0
IL_0055: call ""bool C.Test(char, bool)""
IL_005a: brfalse.s IL_0066
IL_005c: ldc.i4.s 67
IL_005e: ldc.i4.1
IL_005f: call ""bool C.Test(char, bool)""
IL_0064: br.s IL_0067
IL_0066: ldc.i4.0
IL_0067: call ""void System.Console.WriteLine(bool)""
IL_006c: ldc.i4.s 65
IL_006e: ldc.i4.1
IL_006f: call ""bool C.Test(char, bool)""
IL_0074: brfalse.s IL_008a
IL_0076: ldc.i4.s 66
IL_0078: ldc.i4.0
IL_0079: call ""bool C.Test(char, bool)""
IL_007e: brfalse.s IL_008a
IL_0080: ldc.i4.s 67
IL_0082: ldc.i4.0
IL_0083: call ""bool C.Test(char, bool)""
IL_0088: br.s IL_008b
IL_008a: ldc.i4.0
IL_008b: call ""void System.Console.WriteLine(bool)""
IL_0090: ldc.i4.s 65
IL_0092: ldc.i4.0
IL_0093: call ""bool C.Test(char, bool)""
IL_0098: brfalse.s IL_00ae
IL_009a: ldc.i4.s 66
IL_009c: ldc.i4.1
IL_009d: call ""bool C.Test(char, bool)""
IL_00a2: brfalse.s IL_00ae
IL_00a4: ldc.i4.s 67
IL_00a6: ldc.i4.1
IL_00a7: call ""bool C.Test(char, bool)""
IL_00ac: br.s IL_00af
IL_00ae: ldc.i4.0
IL_00af: call ""void System.Console.WriteLine(bool)""
IL_00b4: ldc.i4.s 65
IL_00b6: ldc.i4.0
IL_00b7: call ""bool C.Test(char, bool)""
IL_00bc: brfalse.s IL_00d2
IL_00be: ldc.i4.s 66
IL_00c0: ldc.i4.1
IL_00c1: call ""bool C.Test(char, bool)""
IL_00c6: brfalse.s IL_00d2
IL_00c8: ldc.i4.s 67
IL_00ca: ldc.i4.0
IL_00cb: call ""bool C.Test(char, bool)""
IL_00d0: br.s IL_00d3
IL_00d2: ldc.i4.0
IL_00d3: call ""void System.Console.WriteLine(bool)""
IL_00d8: ldc.i4.s 65
IL_00da: ldc.i4.0
IL_00db: call ""bool C.Test(char, bool)""
IL_00e0: brfalse.s IL_00f6
IL_00e2: ldc.i4.s 66
IL_00e4: ldc.i4.0
IL_00e5: call ""bool C.Test(char, bool)""
IL_00ea: brfalse.s IL_00f6
IL_00ec: ldc.i4.s 67
IL_00ee: ldc.i4.1
IL_00ef: call ""bool C.Test(char, bool)""
IL_00f4: br.s IL_00f7
IL_00f6: ldc.i4.0
IL_00f7: call ""void System.Console.WriteLine(bool)""
IL_00fc: ldc.i4.s 65
IL_00fe: ldc.i4.0
IL_00ff: call ""bool C.Test(char, bool)""
IL_0104: brfalse.s IL_011a
IL_0106: ldc.i4.s 66
IL_0108: ldc.i4.0
IL_0109: call ""bool C.Test(char, bool)""
IL_010e: brfalse.s IL_011a
IL_0110: ldc.i4.s 67
IL_0112: ldc.i4.0
IL_0113: call ""bool C.Test(char, bool)""
IL_0118: br.s IL_011b
IL_011a: ldc.i4.0
IL_011b: call ""void System.Console.WriteLine(bool)""
IL_0120: ldc.i4.s 65
IL_0122: ldc.i4.1
IL_0123: call ""bool C.Test(char, bool)""
IL_0128: brfalse.s IL_0134
IL_012a: ldc.i4.s 66
IL_012c: ldc.i4.1
IL_012d: call ""bool C.Test(char, bool)""
IL_0132: brtrue.s IL_013e
IL_0134: ldc.i4.s 67
IL_0136: ldc.i4.1
IL_0137: call ""bool C.Test(char, bool)""
IL_013c: br.s IL_013f
IL_013e: ldc.i4.1
IL_013f: call ""void System.Console.WriteLine(bool)""
IL_0144: ldc.i4.s 65
IL_0146: ldc.i4.1
IL_0147: call ""bool C.Test(char, bool)""
IL_014c: brfalse.s IL_0158
IL_014e: ldc.i4.s 66
IL_0150: ldc.i4.1
IL_0151: call ""bool C.Test(char, bool)""
IL_0156: brtrue.s IL_0162
IL_0158: ldc.i4.s 67
IL_015a: ldc.i4.0
IL_015b: call ""bool C.Test(char, bool)""
IL_0160: br.s IL_0163
IL_0162: ldc.i4.1
IL_0163: call ""void System.Console.WriteLine(bool)""
IL_0168: ldc.i4.s 65
IL_016a: ldc.i4.1
IL_016b: call ""bool C.Test(char, bool)""
IL_0170: brfalse.s IL_017c
IL_0172: ldc.i4.s 66
IL_0174: ldc.i4.0
IL_0175: call ""bool C.Test(char, bool)""
IL_017a: brtrue.s IL_0186
IL_017c: ldc.i4.s 67
IL_017e: ldc.i4.1
IL_017f: call ""bool C.Test(char, bool)""
IL_0184: br.s IL_0187
IL_0186: ldc.i4.1
IL_0187: call ""void System.Console.WriteLine(bool)""
IL_018c: ldc.i4.s 65
IL_018e: ldc.i4.1
IL_018f: call ""bool C.Test(char, bool)""
IL_0194: brfalse.s IL_01a0
IL_0196: ldc.i4.s 66
IL_0198: ldc.i4.0
IL_0199: call ""bool C.Test(char, bool)""
IL_019e: brtrue.s IL_01aa
IL_01a0: ldc.i4.s 67
IL_01a2: ldc.i4.0
IL_01a3: call ""bool C.Test(char, bool)""
IL_01a8: br.s IL_01ab
IL_01aa: ldc.i4.1
IL_01ab: call ""void System.Console.WriteLine(bool)""
IL_01b0: ldc.i4.s 65
IL_01b2: ldc.i4.0
IL_01b3: call ""bool C.Test(char, bool)""
IL_01b8: brfalse.s IL_01c4
IL_01ba: ldc.i4.s 66
IL_01bc: ldc.i4.1
IL_01bd: call ""bool C.Test(char, bool)""
IL_01c2: brtrue.s IL_01ce
IL_01c4: ldc.i4.s 67
IL_01c6: ldc.i4.1
IL_01c7: call ""bool C.Test(char, bool)""
IL_01cc: br.s IL_01cf
IL_01ce: ldc.i4.1
IL_01cf: call ""void System.Console.WriteLine(bool)""
IL_01d4: ldc.i4.s 65
IL_01d6: ldc.i4.0
IL_01d7: call ""bool C.Test(char, bool)""
IL_01dc: brfalse.s IL_01e8
IL_01de: ldc.i4.s 66
IL_01e0: ldc.i4.1
IL_01e1: call ""bool C.Test(char, bool)""
IL_01e6: brtrue.s IL_01f2
IL_01e8: ldc.i4.s 67
IL_01ea: ldc.i4.0
IL_01eb: call ""bool C.Test(char, bool)""
IL_01f0: br.s IL_01f3
IL_01f2: ldc.i4.1
IL_01f3: call ""void System.Console.WriteLine(bool)""
IL_01f8: ldc.i4.s 65
IL_01fa: ldc.i4.0
IL_01fb: call ""bool C.Test(char, bool)""
IL_0200: brfalse.s IL_020c
IL_0202: ldc.i4.s 66
IL_0204: ldc.i4.0
IL_0205: call ""bool C.Test(char, bool)""
IL_020a: brtrue.s IL_0216
IL_020c: ldc.i4.s 67
IL_020e: ldc.i4.1
IL_020f: call ""bool C.Test(char, bool)""
IL_0214: br.s IL_0217
IL_0216: ldc.i4.1
IL_0217: call ""void System.Console.WriteLine(bool)""
IL_021c: ldc.i4.s 65
IL_021e: ldc.i4.0
IL_021f: call ""bool C.Test(char, bool)""
IL_0224: brfalse.s IL_0230
IL_0226: ldc.i4.s 66
IL_0228: ldc.i4.0
IL_0229: call ""bool C.Test(char, bool)""
IL_022e: brtrue.s IL_023a
IL_0230: ldc.i4.s 67
IL_0232: ldc.i4.0
IL_0233: call ""bool C.Test(char, bool)""
IL_0238: br.s IL_023b
IL_023a: ldc.i4.1
IL_023b: call ""void System.Console.WriteLine(bool)""
IL_0240: ldc.i4.s 65
IL_0242: ldc.i4.1
IL_0243: call ""bool C.Test(char, bool)""
IL_0248: brtrue.s IL_0261
IL_024a: ldc.i4.s 66
IL_024c: ldc.i4.1
IL_024d: call ""bool C.Test(char, bool)""
IL_0252: brfalse.s IL_025e
IL_0254: ldc.i4.s 67
IL_0256: ldc.i4.1
IL_0257: call ""bool C.Test(char, bool)""
IL_025c: br.s IL_0262
IL_025e: ldc.i4.0
IL_025f: br.s IL_0262
IL_0261: ldc.i4.1
IL_0262: call ""void System.Console.WriteLine(bool)""
IL_0267: ldc.i4.s 65
IL_0269: ldc.i4.1
IL_026a: call ""bool C.Test(char, bool)""
IL_026f: brtrue.s IL_0288
IL_0271: ldc.i4.s 66
IL_0273: ldc.i4.1
IL_0274: call ""bool C.Test(char, bool)""
IL_0279: brfalse.s IL_0285
IL_027b: ldc.i4.s 67
IL_027d: ldc.i4.0
IL_027e: call ""bool C.Test(char, bool)""
IL_0283: br.s IL_0289
IL_0285: ldc.i4.0
IL_0286: br.s IL_0289
IL_0288: ldc.i4.1
IL_0289: call ""void System.Console.WriteLine(bool)""
IL_028e: ldc.i4.s 65
IL_0290: ldc.i4.1
IL_0291: call ""bool C.Test(char, bool)""
IL_0296: brtrue.s IL_02af
IL_0298: ldc.i4.s 66
IL_029a: ldc.i4.0
IL_029b: call ""bool C.Test(char, bool)""
IL_02a0: brfalse.s IL_02ac
IL_02a2: ldc.i4.s 67
IL_02a4: ldc.i4.1
IL_02a5: call ""bool C.Test(char, bool)""
IL_02aa: br.s IL_02b0
IL_02ac: ldc.i4.0
IL_02ad: br.s IL_02b0
IL_02af: ldc.i4.1
IL_02b0: call ""void System.Console.WriteLine(bool)""
IL_02b5: ldc.i4.s 65
IL_02b7: ldc.i4.1
IL_02b8: call ""bool C.Test(char, bool)""
IL_02bd: brtrue.s IL_02d6
IL_02bf: ldc.i4.s 66
IL_02c1: ldc.i4.0
IL_02c2: call ""bool C.Test(char, bool)""
IL_02c7: brfalse.s IL_02d3
IL_02c9: ldc.i4.s 67
IL_02cb: ldc.i4.0
IL_02cc: call ""bool C.Test(char, bool)""
IL_02d1: br.s IL_02d7
IL_02d3: ldc.i4.0
IL_02d4: br.s IL_02d7
IL_02d6: ldc.i4.1
IL_02d7: call ""void System.Console.WriteLine(bool)""
IL_02dc: ldc.i4.s 65
IL_02de: ldc.i4.0
IL_02df: call ""bool C.Test(char, bool)""
IL_02e4: brtrue.s IL_02fd
IL_02e6: ldc.i4.s 66
IL_02e8: ldc.i4.1
IL_02e9: call ""bool C.Test(char, bool)""
IL_02ee: brfalse.s IL_02fa
IL_02f0: ldc.i4.s 67
IL_02f2: ldc.i4.1
IL_02f3: call ""bool C.Test(char, bool)""
IL_02f8: br.s IL_02fe
IL_02fa: ldc.i4.0
IL_02fb: br.s IL_02fe
IL_02fd: ldc.i4.1
IL_02fe: call ""void System.Console.WriteLine(bool)""
IL_0303: ldc.i4.s 65
IL_0305: ldc.i4.0
IL_0306: call ""bool C.Test(char, bool)""
IL_030b: brtrue.s IL_0324
IL_030d: ldc.i4.s 66
IL_030f: ldc.i4.1
IL_0310: call ""bool C.Test(char, bool)""
IL_0315: brfalse.s IL_0321
IL_0317: ldc.i4.s 67
IL_0319: ldc.i4.0
IL_031a: call ""bool C.Test(char, bool)""
IL_031f: br.s IL_0325
IL_0321: ldc.i4.0
IL_0322: br.s IL_0325
IL_0324: ldc.i4.1
IL_0325: call ""void System.Console.WriteLine(bool)""
IL_032a: ldc.i4.s 65
IL_032c: ldc.i4.0
IL_032d: call ""bool C.Test(char, bool)""
IL_0332: brtrue.s IL_034b
IL_0334: ldc.i4.s 66
IL_0336: ldc.i4.0
IL_0337: call ""bool C.Test(char, bool)""
IL_033c: brfalse.s IL_0348
IL_033e: ldc.i4.s 67
IL_0340: ldc.i4.1
IL_0341: call ""bool C.Test(char, bool)""
IL_0346: br.s IL_034c
IL_0348: ldc.i4.0
IL_0349: br.s IL_034c
IL_034b: ldc.i4.1
IL_034c: call ""void System.Console.WriteLine(bool)""
IL_0351: ldc.i4.s 65
IL_0353: ldc.i4.0
IL_0354: call ""bool C.Test(char, bool)""
IL_0359: brtrue.s IL_0372
IL_035b: ldc.i4.s 66
IL_035d: ldc.i4.0
IL_035e: call ""bool C.Test(char, bool)""
IL_0363: brfalse.s IL_036f
IL_0365: ldc.i4.s 67
IL_0367: ldc.i4.0
IL_0368: call ""bool C.Test(char, bool)""
IL_036d: br.s IL_0373
IL_036f: ldc.i4.0
IL_0370: br.s IL_0373
IL_0372: ldc.i4.1
IL_0373: call ""void System.Console.WriteLine(bool)""
IL_0378: ldc.i4.s 65
IL_037a: ldc.i4.1
IL_037b: call ""bool C.Test(char, bool)""
IL_0380: brtrue.s IL_0396
IL_0382: ldc.i4.s 66
IL_0384: ldc.i4.1
IL_0385: call ""bool C.Test(char, bool)""
IL_038a: brtrue.s IL_0396
IL_038c: ldc.i4.s 67
IL_038e: ldc.i4.1
IL_038f: call ""bool C.Test(char, bool)""
IL_0394: br.s IL_0397
IL_0396: ldc.i4.1
IL_0397: call ""void System.Console.WriteLine(bool)""
IL_039c: ldc.i4.s 65
IL_039e: ldc.i4.1
IL_039f: call ""bool C.Test(char, bool)""
IL_03a4: brtrue.s IL_03ba
IL_03a6: ldc.i4.s 66
IL_03a8: ldc.i4.1
IL_03a9: call ""bool C.Test(char, bool)""
IL_03ae: brtrue.s IL_03ba
IL_03b0: ldc.i4.s 67
IL_03b2: ldc.i4.0
IL_03b3: call ""bool C.Test(char, bool)""
IL_03b8: br.s IL_03bb
IL_03ba: ldc.i4.1
IL_03bb: call ""void System.Console.WriteLine(bool)""
IL_03c0: ldc.i4.s 65
IL_03c2: ldc.i4.1
IL_03c3: call ""bool C.Test(char, bool)""
IL_03c8: brtrue.s IL_03de
IL_03ca: ldc.i4.s 66
IL_03cc: ldc.i4.0
IL_03cd: call ""bool C.Test(char, bool)""
IL_03d2: brtrue.s IL_03de
IL_03d4: ldc.i4.s 67
IL_03d6: ldc.i4.1
IL_03d7: call ""bool C.Test(char, bool)""
IL_03dc: br.s IL_03df
IL_03de: ldc.i4.1
IL_03df: call ""void System.Console.WriteLine(bool)""
IL_03e4: ldc.i4.s 65
IL_03e6: ldc.i4.1
IL_03e7: call ""bool C.Test(char, bool)""
IL_03ec: brtrue.s IL_0402
IL_03ee: ldc.i4.s 66
IL_03f0: ldc.i4.0
IL_03f1: call ""bool C.Test(char, bool)""
IL_03f6: brtrue.s IL_0402
IL_03f8: ldc.i4.s 67
IL_03fa: ldc.i4.0
IL_03fb: call ""bool C.Test(char, bool)""
IL_0400: br.s IL_0403
IL_0402: ldc.i4.1
IL_0403: call ""void System.Console.WriteLine(bool)""
IL_0408: ldc.i4.s 65
IL_040a: ldc.i4.0
IL_040b: call ""bool C.Test(char, bool)""
IL_0410: brtrue.s IL_0426
IL_0412: ldc.i4.s 66
IL_0414: ldc.i4.1
IL_0415: call ""bool C.Test(char, bool)""
IL_041a: brtrue.s IL_0426
IL_041c: ldc.i4.s 67
IL_041e: ldc.i4.1
IL_041f: call ""bool C.Test(char, bool)""
IL_0424: br.s IL_0427
IL_0426: ldc.i4.1
IL_0427: call ""void System.Console.WriteLine(bool)""
IL_042c: ldc.i4.s 65
IL_042e: ldc.i4.0
IL_042f: call ""bool C.Test(char, bool)""
IL_0434: brtrue.s IL_044a
IL_0436: ldc.i4.s 66
IL_0438: ldc.i4.1
IL_0439: call ""bool C.Test(char, bool)""
IL_043e: brtrue.s IL_044a
IL_0440: ldc.i4.s 67
IL_0442: ldc.i4.0
IL_0443: call ""bool C.Test(char, bool)""
IL_0448: br.s IL_044b
IL_044a: ldc.i4.1
IL_044b: call ""void System.Console.WriteLine(bool)""
IL_0450: ldc.i4.s 65
IL_0452: ldc.i4.0
IL_0453: call ""bool C.Test(char, bool)""
IL_0458: brtrue.s IL_046e
IL_045a: ldc.i4.s 66
IL_045c: ldc.i4.0
IL_045d: call ""bool C.Test(char, bool)""
IL_0462: brtrue.s IL_046e
IL_0464: ldc.i4.s 67
IL_0466: ldc.i4.1
IL_0467: call ""bool C.Test(char, bool)""
IL_046c: br.s IL_046f
IL_046e: ldc.i4.1
IL_046f: call ""void System.Console.WriteLine(bool)""
IL_0474: ldc.i4.s 65
IL_0476: ldc.i4.0
IL_0477: call ""bool C.Test(char, bool)""
IL_047c: brtrue.s IL_0492
IL_047e: ldc.i4.s 66
IL_0480: ldc.i4.0
IL_0481: call ""bool C.Test(char, bool)""
IL_0486: brtrue.s IL_0492
IL_0488: ldc.i4.s 67
IL_048a: ldc.i4.0
IL_048b: call ""bool C.Test(char, bool)""
IL_0490: br.s IL_0493
IL_0492: ldc.i4.1
IL_0493: call ""void System.Console.WriteLine(bool)""
IL_0498: ret
}
");
}
[Fact]
public void TestConditionalMemberAccess001()
{
var source = @"
public class C
{
static void Main()
{
Test(null);
System.Console.Write('#');
int[] a = new int[] { };
Test(a);
}
static void Test(int[] x)
{
System.Console.Write(x?.ToString().ToString().ToString() ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, expectedOutput: "NULL#System.Int32[]");
comp.VerifyIL("C.Test", @"
{
// Code size 37 (0x25)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0006
IL_0003: ldnull
IL_0004: br.s IL_0016
IL_0006: ldarg.0
IL_0007: callvirt ""string object.ToString()""
IL_000c: callvirt ""string object.ToString()""
IL_0011: callvirt ""string object.ToString()""
IL_0016: dup
IL_0017: brtrue.s IL_001f
IL_0019: pop
IL_001a: ldstr ""NULL""
IL_001f: call ""void System.Console.Write(string)""
IL_0024: ret
}
");
}
[Fact]
public void TestConditionalMemberAccess001ext()
{
var source = @"
public static class C
{
static void Main()
{
Test(null);
System.Console.Write('#');
int[] a = new int[] { };
Test(a);
}
static void Test(int[] x)
{
System.Console.Write(x?.ToStr().ToStr().ToStr() ?? ""NULL"");
}
static string ToStr(this object arg)
{
return arg.ToString();
}
}";
var comp = CompileAndVerify(source, expectedOutput: "NULL#System.Int32[]");
comp.VerifyIL("C.Test", @"
{
// Code size 37 (0x25)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0006
IL_0003: ldnull
IL_0004: br.s IL_0016
IL_0006: ldarg.0
IL_0007: call ""string C.ToStr(object)""
IL_000c: call ""string C.ToStr(object)""
IL_0011: call ""string C.ToStr(object)""
IL_0016: dup
IL_0017: brtrue.s IL_001f
IL_0019: pop
IL_001a: ldstr ""NULL""
IL_001f: call ""void System.Console.Write(string)""
IL_0024: ret
}
");
}
[Fact]
public void TestConditionalMemberAccess001dyn()
{
var source = @"
public static class C
{
static void Main()
{
Test(null);
System.Console.Write('#');
int[] a = new int[] { };
Test(a);
}
static void Test(dynamic x)
{
System.Console.Write(x?.ToString().ToString()?.ToString() ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#System.Int32[]");
comp.VerifyIL("C.Test", @"
{
// Code size 355 (0x163)
.maxstack 14
.locals init (object V_0,
object V_1)
IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3""
IL_0005: brtrue.s IL_0046
IL_0007: ldc.i4 0x100
IL_000c: ldstr ""Write""
IL_0011: ldnull
IL_0012: ldtoken ""C""
IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001c: ldc.i4.2
IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0022: dup
IL_0023: ldc.i4.0
IL_0024: ldc.i4.s 33
IL_0026: ldnull
IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002c: stelem.ref
IL_002d: dup
IL_002e: ldc.i4.1
IL_002f: ldc.i4.0
IL_0030: ldnull
IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0036: stelem.ref
IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3""
IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3""
IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target""
IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3""
IL_0055: ldtoken ""System.Console""
IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_005f: ldarg.0
IL_0060: stloc.0
IL_0061: ldloc.0
IL_0062: brtrue.s IL_006a
IL_0064: ldnull
IL_0065: br IL_0154
IL_006a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1""
IL_006f: brtrue.s IL_00a1
IL_0071: ldc.i4.0
IL_0072: ldstr ""ToString""
IL_0077: ldnull
IL_0078: ldtoken ""C""
IL_007d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0082: ldc.i4.1
IL_0083: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0088: dup
IL_0089: ldc.i4.0
IL_008a: ldc.i4.0
IL_008b: ldnull
IL_008c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0091: stelem.ref
IL_0092: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0097: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_009c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1""
IL_00a1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1""
IL_00a6: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target""
IL_00ab: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1""
IL_00b0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0""
IL_00b5: brtrue.s IL_00e7
IL_00b7: ldc.i4.0
IL_00b8: ldstr ""ToString""
IL_00bd: ldnull
IL_00be: ldtoken ""C""
IL_00c3: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_00c8: ldc.i4.1
IL_00c9: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_00ce: dup
IL_00cf: ldc.i4.0
IL_00d0: ldc.i4.0
IL_00d1: ldnull
IL_00d2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_00d7: stelem.ref
IL_00d8: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_00dd: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_00e2: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0""
IL_00e7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0""
IL_00ec: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target""
IL_00f1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0""
IL_00f6: ldloc.0
IL_00f7: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_00fc: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_0101: stloc.1
IL_0102: ldloc.1
IL_0103: brtrue.s IL_0108
IL_0105: ldnull
IL_0106: br.s IL_0154
IL_0108: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2""
IL_010d: brtrue.s IL_013f
IL_010f: ldc.i4.0
IL_0110: ldstr ""ToString""
IL_0115: ldnull
IL_0116: ldtoken ""C""
IL_011b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0120: ldc.i4.1
IL_0121: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0126: dup
IL_0127: ldc.i4.0
IL_0128: ldc.i4.0
IL_0129: ldnull
IL_012a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_012f: stelem.ref
IL_0130: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0135: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_013a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2""
IL_013f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2""
IL_0144: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target""
IL_0149: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2""
IL_014e: ldloc.1
IL_014f: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_0154: dup
IL_0155: brtrue.s IL_015d
IL_0157: pop
IL_0158: ldstr ""NULL""
IL_015d: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)""
IL_0162: ret
}
");
}
[Fact]
public void TestConditionalMemberAccess001dyn1()
{
var source = @"
public static class C
{
static void Main()
{
Test(null);
System.Console.Write('#');
int[] a = new int[] { };
Test(a);
}
static void Test(dynamic x)
{
System.Console.Write(x?.ToString()?[1].ToString() ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#y");
}
[Fact]
public void TestConditionalMemberAccess001dyn2()
{
var source = @"
public static class C
{
static void Main()
{
Test(null, ""aa"");
System.Console.Write('#');
Test(""aa"", ""bb"");
}
static void Test(string s, dynamic ds)
{
System.Console.Write(s?.CompareTo(ds) ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#-1");
}
[Fact]
public void TestConditionalMemberAccess001dyn3()
{
var source = @"
public static class C
{
static void Main()
{
Test(null, 1);
System.Console.Write('#');
int[] a = new int[] { };
Test(a, 1);
}
static void Test(int[] x, dynamic i)
{
System.Console.Write(x?.ToString()?[i].ToString() ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#y");
}
[Fact]
public void TestConditionalMemberAccess001dyn4()
{
var source = @"
public static class C
{
static void Main()
{
Test(null);
System.Console.Write('#');
int[] a = new int[] {1,2,3};
Test(a);
}
static void Test(dynamic x)
{
System.Console.Write(x?.Length.ToString() ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#3");
}
[Fact]
public void TestConditionalMemberAccess001dyn5()
{
var source = @"
public static class C
{
static void Main()
{
Test(null);
System.Console.Write('#');
int[] a = new int[] {1,2,3};
Test(a);
}
static void Test(dynamic x)
{
System.Console.Write(x?.Length?.ToString() ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#3");
}
[Fact]
public void TestConditionalMemberAccessUnused()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString();
var dummy2 = ""qqq""?.ToString();
var dummy3 = 1.ToString()?.ToString();
}
}";
var comp = CompileAndVerify(source, expectedOutput: "");
comp.VerifyIL("C.Main", @"
{
// Code size 32 (0x20)
.maxstack 2
.locals init (int V_0)
IL_0000: ldstr ""qqq""
IL_0005: callvirt ""string object.ToString()""
IL_000a: pop
IL_000b: ldc.i4.1
IL_000c: stloc.0
IL_000d: ldloca.s V_0
IL_000f: call ""string int.ToString()""
IL_0014: dup
IL_0015: brtrue.s IL_0019
IL_0017: pop
IL_0018: ret
IL_0019: callvirt ""string object.ToString()""
IL_001e: pop
IL_001f: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUsed()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString();
var dummy2 = ""qqq""?.ToString();
var dummy3 = 1.ToString()?.ToString();
dummy1 += dummy2 += dummy3;
}
}";
var comp = CompileAndVerify(source, expectedOutput: "");
comp.VerifyIL("C.Main", @"
{
// Code size 50 (0x32)
.maxstack 3
.locals init (string V_0, //dummy2
string V_1, //dummy3
int V_2)
IL_0000: ldnull
IL_0001: ldstr ""qqq""
IL_0006: callvirt ""string object.ToString()""
IL_000b: stloc.0
IL_000c: ldc.i4.1
IL_000d: stloc.2
IL_000e: ldloca.s V_2
IL_0010: call ""string int.ToString()""
IL_0015: dup
IL_0016: brtrue.s IL_001c
IL_0018: pop
IL_0019: ldnull
IL_001a: br.s IL_0021
IL_001c: callvirt ""string object.ToString()""
IL_0021: stloc.1
IL_0022: ldloc.0
IL_0023: ldloc.1
IL_0024: call ""string string.Concat(string, string)""
IL_0029: dup
IL_002a: stloc.0
IL_002b: call ""string string.Concat(string, string)""
IL_0030: pop
IL_0031: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUnused1()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString().Length;
var dummy2 = ""qqq""?.ToString().Length;
var dummy3 = 1.ToString()?.ToString().Length;
}
}";
var comp = CompileAndVerify(source, expectedOutput: "");
comp.VerifyIL("C.Main", @"
{
// Code size 42 (0x2a)
.maxstack 2
.locals init (int V_0)
IL_0000: ldstr ""qqq""
IL_0005: callvirt ""string object.ToString()""
IL_000a: callvirt ""int string.Length.get""
IL_000f: pop
IL_0010: ldc.i4.1
IL_0011: stloc.0
IL_0012: ldloca.s V_0
IL_0014: call ""string int.ToString()""
IL_0019: dup
IL_001a: brtrue.s IL_001e
IL_001c: pop
IL_001d: ret
IL_001e: callvirt ""string object.ToString()""
IL_0023: callvirt ""int string.Length.get""
IL_0028: pop
IL_0029: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUsed1()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString().Length;
System.Console.WriteLine(dummy1);
var dummy2 = ""qqq""?.ToString().Length;
System.Console.WriteLine(dummy2);
var dummy3 = 1.ToString()?.ToString().Length;
System.Console.WriteLine(dummy3);
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"3
1");
comp.VerifyIL("C.Main", @"
{
// Code size 99 (0x63)
.maxstack 2
.locals init (int? V_0,
int V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""int?""
IL_0008: ldloc.0
IL_0009: box ""int?""
IL_000e: call ""void System.Console.WriteLine(object)""
IL_0013: ldstr ""qqq""
IL_0018: callvirt ""string object.ToString()""
IL_001d: callvirt ""int string.Length.get""
IL_0022: newobj ""int?..ctor(int)""
IL_0027: box ""int?""
IL_002c: call ""void System.Console.WriteLine(object)""
IL_0031: ldc.i4.1
IL_0032: stloc.1
IL_0033: ldloca.s V_1
IL_0035: call ""string int.ToString()""
IL_003a: dup
IL_003b: brtrue.s IL_0049
IL_003d: pop
IL_003e: ldloca.s V_0
IL_0040: initobj ""int?""
IL_0046: ldloc.0
IL_0047: br.s IL_0058
IL_0049: callvirt ""string object.ToString()""
IL_004e: callvirt ""int string.Length.get""
IL_0053: newobj ""int?..ctor(int)""
IL_0058: box ""int?""
IL_005d: call ""void System.Console.WriteLine(object)""
IL_0062: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUnused2()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString().NullableLength()?.ToString();
var dummy2 = ""qqq""?.ToString().NullableLength().ToString();
var dummy3 = 1.ToString()?.ToString().NullableLength()?.ToString();
}
}
public static class C1
{
public static int? NullableLength(this string self)
{
return self.Length;
}
}
";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "");
comp.VerifyIL("C.Main", @"
{
// Code size 82 (0x52)
.maxstack 2
.locals init (int? V_0,
int V_1)
IL_0000: ldstr ""qqq""
IL_0005: callvirt ""string object.ToString()""
IL_000a: call ""int? C1.NullableLength(string)""
IL_000f: stloc.0
IL_0010: ldloca.s V_0
IL_0012: constrained. ""int?""
IL_0018: callvirt ""string object.ToString()""
IL_001d: pop
IL_001e: ldc.i4.1
IL_001f: stloc.1
IL_0020: ldloca.s V_1
IL_0022: call ""string int.ToString()""
IL_0027: dup
IL_0028: brtrue.s IL_002c
IL_002a: pop
IL_002b: ret
IL_002c: callvirt ""string object.ToString()""
IL_0031: call ""int? C1.NullableLength(string)""
IL_0036: stloc.0
IL_0037: ldloca.s V_0
IL_0039: dup
IL_003a: call ""bool int?.HasValue.get""
IL_003f: brtrue.s IL_0043
IL_0041: pop
IL_0042: ret
IL_0043: call ""int int?.GetValueOrDefault()""
IL_0048: stloc.1
IL_0049: ldloca.s V_1
IL_004b: call ""string int.ToString()""
IL_0050: pop
IL_0051: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUnused2a()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString()?.Length.ToString();
var dummy2 = ""qqq""?.ToString().Length.ToString();
var dummy3 = 1.ToString()?.ToString().Length.ToString();
}
}";
var comp = CompileAndVerify(source, expectedOutput: "");
comp.VerifyIL("C.Main", @"
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (int V_0)
IL_0000: ldstr ""qqq""
IL_0005: callvirt ""string object.ToString()""
IL_000a: callvirt ""int string.Length.get""
IL_000f: stloc.0
IL_0010: ldloca.s V_0
IL_0012: call ""string int.ToString()""
IL_0017: pop
IL_0018: ldc.i4.1
IL_0019: stloc.0
IL_001a: ldloca.s V_0
IL_001c: call ""string int.ToString()""
IL_0021: dup
IL_0022: brtrue.s IL_0026
IL_0024: pop
IL_0025: ret
IL_0026: callvirt ""string object.ToString()""
IL_002b: callvirt ""int string.Length.get""
IL_0030: stloc.0
IL_0031: ldloca.s V_0
IL_0033: call ""string int.ToString()""
IL_0038: pop
IL_0039: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUsed2()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString().NullableLength()?.ToString();
System.Console.WriteLine(dummy1);
var dummy2 = ""qqq""?.ToString().NullableLength()?.ToString();
System.Console.WriteLine(dummy2);
var dummy3 = 1.ToString()?.ToString().NullableLength()?.ToString();
System.Console.WriteLine(dummy3);
}
}
public static class C1
{
public static int? NullableLength(this string self)
{
return self.Length;
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"3
1");
comp.VerifyIL("C.Main", @"
{
// Code size 114 (0x72)
.maxstack 2
.locals init (int? V_0,
int V_1)
IL_0000: ldnull
IL_0001: call ""void System.Console.WriteLine(string)""
IL_0006: ldstr ""qqq""
IL_000b: callvirt ""string object.ToString()""
IL_0010: call ""int? C1.NullableLength(string)""
IL_0015: stloc.0
IL_0016: ldloca.s V_0
IL_0018: dup
IL_0019: call ""bool int?.HasValue.get""
IL_001e: brtrue.s IL_0024
IL_0020: pop
IL_0021: ldnull
IL_0022: br.s IL_0031
IL_0024: call ""int int?.GetValueOrDefault()""
IL_0029: stloc.1
IL_002a: ldloca.s V_1
IL_002c: call ""string int.ToString()""
IL_0031: call ""void System.Console.WriteLine(string)""
IL_0036: ldc.i4.1
IL_0037: stloc.1
IL_0038: ldloca.s V_1
IL_003a: call ""string int.ToString()""
IL_003f: dup
IL_0040: brtrue.s IL_0046
IL_0042: pop
IL_0043: ldnull
IL_0044: br.s IL_006c
IL_0046: callvirt ""string object.ToString()""
IL_004b: call ""int? C1.NullableLength(string)""
IL_0050: stloc.0
IL_0051: ldloca.s V_0
IL_0053: dup
IL_0054: call ""bool int?.HasValue.get""
IL_0059: brtrue.s IL_005f
IL_005b: pop
IL_005c: ldnull
IL_005d: br.s IL_006c
IL_005f: call ""int int?.GetValueOrDefault()""
IL_0064: stloc.1
IL_0065: ldloca.s V_1
IL_0067: call ""string int.ToString()""
IL_006c: call ""void System.Console.WriteLine(string)""
IL_0071: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUsed2a()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString()?.Length.ToString();
System.Console.WriteLine(dummy1);
var dummy2 = ""qqq""?.ToString()?.Length.ToString();
System.Console.WriteLine(dummy2);
var dummy3 = 1.ToString()?.ToString()?.Length.ToString();
System.Console.WriteLine(dummy3);
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"3
1");
comp.VerifyIL("C.Main", @"
{
// Code size 88 (0x58)
.maxstack 2
.locals init (int V_0)
IL_0000: ldnull
IL_0001: call ""void System.Console.WriteLine(string)""
IL_0006: ldstr ""qqq""
IL_000b: callvirt ""string object.ToString()""
IL_0010: dup
IL_0011: brtrue.s IL_0017
IL_0013: pop
IL_0014: ldnull
IL_0015: br.s IL_0024
IL_0017: call ""int string.Length.get""
IL_001c: stloc.0
IL_001d: ldloca.s V_0
IL_001f: call ""string int.ToString()""
IL_0024: call ""void System.Console.WriteLine(string)""
IL_0029: ldc.i4.1
IL_002a: stloc.0
IL_002b: ldloca.s V_0
IL_002d: call ""string int.ToString()""
IL_0032: dup
IL_0033: brtrue.s IL_0039
IL_0035: pop
IL_0036: ldnull
IL_0037: br.s IL_0052
IL_0039: callvirt ""string object.ToString()""
IL_003e: dup
IL_003f: brtrue.s IL_0045
IL_0041: pop
IL_0042: ldnull
IL_0043: br.s IL_0052
IL_0045: call ""int string.Length.get""
IL_004a: stloc.0
IL_004b: ldloca.s V_0
IL_004d: call ""string int.ToString()""
IL_0052: call ""void System.Console.WriteLine(string)""
IL_0057: ret
}
");
}
[Fact]
[WorkItem(976765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/976765")]
public void ConditionalMemberAccessConstrained()
{
var source = @"
class Program
{
static void M<T>(T x) where T: System.Exception
{
object s = x?.ToString();
System.Console.WriteLine(s);
s = x?.GetType();
System.Console.WriteLine(s);
}
static void Main()
{
M(new System.Exception(""a""));
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"System.Exception: a
System.Exception");
comp.VerifyIL("Program.M<T>", @"
{
// Code size 47 (0x2f)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: dup
IL_0007: brtrue.s IL_000d
IL_0009: pop
IL_000a: ldnull
IL_000b: br.s IL_0012
IL_000d: callvirt ""string object.ToString()""
IL_0012: call ""void System.Console.WriteLine(object)""
IL_0017: ldarg.0
IL_0018: box ""T""
IL_001d: dup
IL_001e: brtrue.s IL_0024
IL_0020: pop
IL_0021: ldnull
IL_0022: br.s IL_0029
IL_0024: callvirt ""System.Type System.Exception.GetType()""
IL_0029: call ""void System.Console.WriteLine(object)""
IL_002e: ret
}
");
}
[Fact]
[WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")]
public void ConditionalMemberAccessStatement()
{
var source = @"
class Program
{
class C1
{
public void Print0()
{
System.Console.WriteLine(""print0"");
}
public int Print1()
{
System.Console.WriteLine(""print1"");
return 1;
}
public object Print2()
{
System.Console.WriteLine(""print2"");
return 1;
}
}
static void M(C1 x)
{
x?.Print0();
x?.Print1();
x?.Print2();
}
static void Main()
{
M(null);
M(new C1());
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"print0
print1
print2");
comp.VerifyIL("Program.M(Program.C1)", @"
{
// Code size 30 (0x1e)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0009
IL_0003: ldarg.0
IL_0004: call ""void Program.C1.Print0()""
IL_0009: ldarg.0
IL_000a: brfalse.s IL_0013
IL_000c: ldarg.0
IL_000d: call ""int Program.C1.Print1()""
IL_0012: pop
IL_0013: ldarg.0
IL_0014: brfalse.s IL_001d
IL_0016: ldarg.0
IL_0017: call ""object Program.C1.Print2()""
IL_001c: pop
IL_001d: ret
}
");
}
[Fact]
[WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")]
public void ConditionalMemberAccessStatement01()
{
var source = @"
class Program
{
struct S1
{
public void Print0()
{
System.Console.WriteLine(""print0"");
}
public int Print1()
{
System.Console.WriteLine(""print1"");
return 1;
}
public object Print2()
{
System.Console.WriteLine(""print2"");
return 1;
}
}
static void M(S1? x)
{
x?.Print0();
x?.Print1();
x?.Print2()?.ToString().ToString()?.ToString();
}
static void Main()
{
M(null);
M(new S1());
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"print0
print1
print2");
comp.VerifyIL("Program.M(Program.S1?)", @"
{
// Code size 100 (0x64)
.maxstack 2
.locals init (Program.S1 V_0)
IL_0000: ldarga.s V_0
IL_0002: call ""bool Program.S1?.HasValue.get""
IL_0007: brfalse.s IL_0018
IL_0009: ldarga.s V_0
IL_000b: call ""Program.S1 Program.S1?.GetValueOrDefault()""
IL_0010: stloc.0
IL_0011: ldloca.s V_0
IL_0013: call ""void Program.S1.Print0()""
IL_0018: ldarga.s V_0
IL_001a: call ""bool Program.S1?.HasValue.get""
IL_001f: brfalse.s IL_0031
IL_0021: ldarga.s V_0
IL_0023: call ""Program.S1 Program.S1?.GetValueOrDefault()""
IL_0028: stloc.0
IL_0029: ldloca.s V_0
IL_002b: call ""int Program.S1.Print1()""
IL_0030: pop
IL_0031: ldarga.s V_0
IL_0033: call ""bool Program.S1?.HasValue.get""
IL_0038: brfalse.s IL_0063
IL_003a: ldarga.s V_0
IL_003c: call ""Program.S1 Program.S1?.GetValueOrDefault()""
IL_0041: stloc.0
IL_0042: ldloca.s V_0
IL_0044: call ""object Program.S1.Print2()""
IL_0049: dup
IL_004a: brtrue.s IL_004e
IL_004c: pop
IL_004d: ret
IL_004e: callvirt ""string object.ToString()""
IL_0053: callvirt ""string object.ToString()""
IL_0058: dup
IL_0059: brtrue.s IL_005d
IL_005b: pop
IL_005c: ret
IL_005d: callvirt ""string object.ToString()""
IL_0062: pop
IL_0063: ret
}
");
}
[ConditionalFact(typeof(DesktopOnly))]
[WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")]
public void ConditionalMemberAccessStatement02()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
class C1
{
public void Print0(int i)
{
System.Console.WriteLine(""print0"");
}
public int Print1(int i)
{
System.Console.WriteLine(""print1"");
return 1;
}
public object Print2(int i)
{
System.Console.WriteLine(""print2"");
return 1;
}
}
static async Task<int> Val()
{
await Task.Yield();
return 1;
}
static async Task<int> M(C1 x)
{
x?.Print0(await Val());
x?.Print1(await Val());
x?.Print2(await Val());
return 1;
}
static void Main()
{
M(null).Wait();
M(new C1()).Wait();
}
}
";
var comp = CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: @"print0
print1
print2");
}
[ConditionalFact(typeof(DesktopOnly))]
[WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")]
public void ConditionalMemberAccessStatement03()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
struct C1
{
public void Print0(int i)
{
System.Console.WriteLine(""print0"");
}
public int Print1(int i)
{
System.Console.WriteLine(""print1"");
return 1;
}
public object Print2(int i)
{
System.Console.WriteLine(""print2"");
return 1;
}
}
static async Task<int> Val()
{
await Task.Yield();
return 1;
}
static async Task<int> M(C1? x)
{
x?.Print0(await Val());
x?.Print1(await Val());
x?.Print2(await Val());
return 1;
}
static void Main()
{
M(null).Wait();
M(new C1()).Wait();
}
}
";
var comp = CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: @"print0
print1
print2");
}
[Fact]
public void ConditionalMemberAccessUnConstrained()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
class C1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(ref c, ref c);
S1 s = new S1();
Test(ref s, ref s);
}
static void Test<T>(ref T x, ref T y) where T : IDisposable
{
x?.Dispose();
y?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True
False
True");
comp.VerifyIL("Program.Test<T>(ref T, ref T)", @"
{
// Code size 94 (0x5e)
.maxstack 2
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0024
IL_0011: ldobj ""T""
IL_0016: stloc.0
IL_0017: ldloca.s V_0
IL_0019: ldloc.0
IL_001a: box ""T""
IL_001f: brtrue.s IL_0024
IL_0021: pop
IL_0022: br.s IL_002f
IL_0024: constrained. ""T""
IL_002a: callvirt ""void System.IDisposable.Dispose()""
IL_002f: ldarg.1
IL_0030: ldloca.s V_0
IL_0032: initobj ""T""
IL_0038: ldloc.0
IL_0039: box ""T""
IL_003e: brtrue.s IL_0052
IL_0040: ldobj ""T""
IL_0045: stloc.0
IL_0046: ldloca.s V_0
IL_0048: ldloc.0
IL_0049: box ""T""
IL_004e: brtrue.s IL_0052
IL_0050: pop
IL_0051: ret
IL_0052: constrained. ""T""
IL_0058: callvirt ""void System.IDisposable.Dispose()""
IL_005d: ret
}");
}
[Fact]
public void ConditionalMemberAccessUnConstrained1()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
class C1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
var c = new C1[] {new C1()};
Test(c, c);
var s = new S1[] {new S1()};
Test(s, s);
}
static void Test<T>(T[] x, T[] y) where T : IDisposable
{
x[0]?.Dispose();
y[0]?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True
False
True");
comp.VerifyIL("Program.Test<T>(T[], T[])", @"
{
// Code size 110 (0x6e)
.maxstack 2
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: readonly.
IL_0004: ldelema ""T""
IL_0009: ldloca.s V_0
IL_000b: initobj ""T""
IL_0011: ldloc.0
IL_0012: box ""T""
IL_0017: brtrue.s IL_002c
IL_0019: ldobj ""T""
IL_001e: stloc.0
IL_001f: ldloca.s V_0
IL_0021: ldloc.0
IL_0022: box ""T""
IL_0027: brtrue.s IL_002c
IL_0029: pop
IL_002a: br.s IL_0037
IL_002c: constrained. ""T""
IL_0032: callvirt ""void System.IDisposable.Dispose()""
IL_0037: ldarg.1
IL_0038: ldc.i4.0
IL_0039: readonly.
IL_003b: ldelema ""T""
IL_0040: ldloca.s V_0
IL_0042: initobj ""T""
IL_0048: ldloc.0
IL_0049: box ""T""
IL_004e: brtrue.s IL_0062
IL_0050: ldobj ""T""
IL_0055: stloc.0
IL_0056: ldloca.s V_0
IL_0058: ldloc.0
IL_0059: box ""T""
IL_005e: brtrue.s IL_0062
IL_0060: pop
IL_0061: ret
IL_0062: constrained. ""T""
IL_0068: callvirt ""void System.IDisposable.Dispose()""
IL_006d: ret
}
");
}
[Fact]
public void ConditionalMemberAccessConstrained1()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
class C1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
var c = new C1[] {new C1()};
Test(c, c);
}
static void Test<T>(T[] x, T[] y) where T : class, IDisposable
{
x[0]?.Dispose();
y[0]?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True
");
comp.VerifyIL("Program.Test<T>(T[], T[])", @"
{
// Code size 46 (0x2e)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelem ""T""
IL_0007: box ""T""
IL_000c: dup
IL_000d: brtrue.s IL_0012
IL_000f: pop
IL_0010: br.s IL_0017
IL_0012: callvirt ""void System.IDisposable.Dispose()""
IL_0017: ldarg.1
IL_0018: ldc.i4.0
IL_0019: ldelem ""T""
IL_001e: box ""T""
IL_0023: dup
IL_0024: brtrue.s IL_0028
IL_0026: pop
IL_0027: ret
IL_0028: callvirt ""void System.IDisposable.Dispose()""
IL_002d: ret
}
");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedVal()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
class C1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(c);
S1 s = new S1();
Test(s);
}
static void Test<T>(T x) where T : IDisposable
{
x?.Dispose();
x?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True
False
True");
comp.VerifyIL("Program.Test<T>(T)", @"
{
// Code size 43 (0x2b)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: brfalse.s IL_0015
IL_0008: ldarga.s V_0
IL_000a: constrained. ""T""
IL_0010: callvirt ""void System.IDisposable.Dispose()""
IL_0015: ldarg.0
IL_0016: box ""T""
IL_001b: brfalse.s IL_002a
IL_001d: ldarga.s V_0
IL_001f: constrained. ""T""
IL_0025: callvirt ""void System.IDisposable.Dispose()""
IL_002a: ret
}
");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedVal001()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
class C1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(() => c);
S1 s = new S1();
Test(() => s);
}
static void Test<T>(Func<T> x) where T : IDisposable
{
x()?.Dispose();
x()?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True
False
False");
comp.VerifyIL("Program.Test<T>(System.Func<T>)", @"
{
// Code size 72 (0x48)
.maxstack 2
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: callvirt ""T System.Func<T>.Invoke()""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: dup
IL_000a: ldobj ""T""
IL_000f: box ""T""
IL_0014: brtrue.s IL_0019
IL_0016: pop
IL_0017: br.s IL_0024
IL_0019: constrained. ""T""
IL_001f: callvirt ""void System.IDisposable.Dispose()""
IL_0024: ldarg.0
IL_0025: callvirt ""T System.Func<T>.Invoke()""
IL_002a: stloc.0
IL_002b: ldloca.s V_0
IL_002d: dup
IL_002e: ldobj ""T""
IL_0033: box ""T""
IL_0038: brtrue.s IL_003c
IL_003a: pop
IL_003b: ret
IL_003c: constrained. ""T""
IL_0042: callvirt ""void System.IDisposable.Dispose()""
IL_0047: ret
}
");
}
[Fact]
public void ConditionalMemberAccessConstrainedVal001()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
class C1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(() => c);
}
static void Test<T>(Func<T> x) where T : class, IDisposable
{
x()?.Dispose();
x()?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True");
comp.VerifyIL("Program.Test<T>(System.Func<T>)", @"
{
// Code size 44 (0x2c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: callvirt ""T System.Func<T>.Invoke()""
IL_0006: box ""T""
IL_000b: dup
IL_000c: brtrue.s IL_0011
IL_000e: pop
IL_000f: br.s IL_0016
IL_0011: callvirt ""void System.IDisposable.Dispose()""
IL_0016: ldarg.0
IL_0017: callvirt ""T System.Func<T>.Invoke()""
IL_001c: box ""T""
IL_0021: dup
IL_0022: brtrue.s IL_0026
IL_0024: pop
IL_0025: ret
IL_0026: callvirt ""void System.IDisposable.Dispose()""
IL_002b: ret
}
");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedDyn()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
interface IDisposable1
{
void Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public void Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable1
{
private bool disposed;
public void Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(ref c, ref c);
S1 s = new S1();
Test(ref s, ref s);
}
static void Test<T>(ref T x, ref T y) where T : IDisposable1
{
dynamic d = 1;
x?.Dispose(d);
y?.Dispose(d);
}
}
";
var comp = CompileAndVerify(source, references: new MetadataReference[] { CSharpRef }, expectedOutput: @"False
True
False
False");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedDynVal()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
interface IDisposable1
{
void Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public void Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable1
{
private bool disposed;
public void Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(c, c);
S1 s = new S1();
Test(s, s);
}
static void Test<T>(T x, T y) where T : IDisposable1
{
dynamic d = 1;
x?.Dispose(d);
y?.Dispose(d);
}
}
";
var comp = CompileAndVerify(source, references: new MetadataReference[] { CSharpRef }, expectedOutput: @"False
True
False
False");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedAsync()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
interface IDisposable1
{
void Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public void Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable1
{
private bool disposed;
public void Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1[] c = new C1[] { new C1() };
Test(c, c).Wait();
S1[] s = new S1[] { new S1() };
Test(s, s).Wait();
}
static async Task<int> Val()
{
await Task.Yield();
return 0;
}
static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1
{
x[0]?.Dispose(await Val());
y[0]?.Dispose(await Val());
return 1;
}
}";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True
False
True");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedAsyncVal()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
interface IDisposable1
{
int Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public int Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
return 1;
}
}
struct S1 : IDisposable1
{
private bool disposed;
public int Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
return 1;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(c, c).Wait();
S1 s = new S1();
Test(s, s).Wait();
}
static async Task<int> Val()
{
await Task.Yield();
return 0;
}
static async Task<int> Test<T>(T x, T y) where T : IDisposable1
{
x?.Dispose(await Val());
y?.Dispose(await Val());
return 1;
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True
False
False");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedAsyncValExt()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DE;
namespace DE
{
public static class IDispExt
{
public static void DisposeExt(this Program.IDisposable1 d, int i)
{
d.Dispose(i);
}
}
}
public class Program
{
public interface IDisposable1
{
int Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public int Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
return 1;
}
}
struct S1 : IDisposable1
{
private bool disposed;
public int Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
return 1;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(c, c).Wait();
S1 s = new S1();
Test(s, s).Wait();
}
static async Task<int> Val()
{
await Task.Yield();
return 0;
}
static async Task<int> Test<T>(T x, T y) where T : IDisposable1
{
x?.DisposeExt(await Val());
y?.DisposeExt(await Val());
return 1;
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True
False
False");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedAsyncNested()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
interface IDisposable1
{
IDisposable1 Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public IDisposable1 Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed ^= true;
return this;
}
}
struct S1 : IDisposable1
{
private bool disposed;
public IDisposable1 Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed ^= true;
return this;
}
}
static void Main(string[] args)
{
C1[] c = new C1[] { new C1() };
Test(c, c).Wait();
System.Console.WriteLine();
S1[] s = new S1[] { new S1() };
Test(s, s).Wait();
}
static async Task<int> Val()
{
await Task.Yield();
return 0;
}
static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1
{
x[0]?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val());
y[0]?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val());
return 1;
}
}";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True
False
True
False
True
False
True
False
True
False
True
True
False
True
False");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedAsyncNestedArr()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
interface IDisposable1
{
IDisposable1[] Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public IDisposable1[] Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed ^= true;
return new IDisposable1[] { this };
}
}
struct S1 : IDisposable1
{
private bool disposed;
public IDisposable1[] Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed ^= true;
return new IDisposable1[]{this};
}
}
static void Main(string[] args)
{
C1[] c = new C1[] { new C1() };
Test(c, c).Wait();
System.Console.WriteLine();
S1[] s = new S1[] { new S1() };
Test(s, s).Wait();
}
static async Task<int> Val()
{
await Task.Yield();
return 0;
}
static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1
{
x[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val());
y[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val());
return 1;
}
}";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True
False
True
False
True
False
True
False
True
False
True
True
False
True
False");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedAsyncSuperNested()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
interface IDisposable1
{
Task<int> Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public Task<int> Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed ^= true;
return Task.FromResult(i);
}
}
struct S1 : IDisposable1
{
private bool disposed;
public Task<int> Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed ^= true;
return Task.FromResult(i);
}
}
static void Main(string[] args)
{
C1[] c = new C1[] { new C1() };
Test(c, c).Wait();
System.Console.WriteLine();
S1[] s = new S1[] { new S1() };
Test(s, s).Wait();
}
static async Task<int> Val()
{
await Task.Yield();
return 0;
}
static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1
{
x[0]?.Dispose(await x[0]?.Dispose(await x[0]?.Dispose(await x[0]?.Dispose(await Val()))));
y[0]?.Dispose(await y[0]?.Dispose(await y[0]?.Dispose(await y[0]?.Dispose(await Val()))));
return 1;
}
}";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True
False
True
False
True
False
True
False
True
False
True
False
True
False
True");
}
[Fact]
public void ConditionalExtensionAccessGeneric001()
{
var source = @"
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
long? x = 1;
Test0(x);
return;
}
static void Test0<T>(T x)
{
x?.CheckT();
}
}
static class Ext
{
public static void CheckT<T>(this T x)
{
System.Console.WriteLine(typeof(T));
return;
}
}
";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"System.Nullable`1[System.Int64]");
comp.VerifyIL("Test.Test0<T>(T)", @"
{
// Code size 21 (0x15)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: brfalse.s IL_0014
IL_0008: ldarga.s V_0
IL_000a: ldobj ""T""
IL_000f: call ""void Ext.CheckT<T>(T)""
IL_0014: ret
}
");
}
[Fact]
public void ConditionalExtensionAccessGeneric002()
{
var source = @"
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
long? x = 1;
Test0(ref x);
return;
}
static void Test0<T>(ref T x)
{
x?.CheckT();
}
}
static class Ext
{
public static void CheckT<T>(this T x)
{
System.Console.WriteLine(typeof(T));
return;
}
}
";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"System.Nullable`1[System.Int64]");
comp.VerifyIL("Test.Test0<T>(ref T)", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0023
IL_0011: ldobj ""T""
IL_0016: stloc.0
IL_0017: ldloca.s V_0
IL_0019: ldloc.0
IL_001a: box ""T""
IL_001f: brtrue.s IL_0023
IL_0021: pop
IL_0022: ret
IL_0023: ldobj ""T""
IL_0028: call ""void Ext.CheckT<T>(T)""
IL_002d: ret
}
");
}
[Fact]
public void ConditionalExtensionAccessGeneric003()
{
var source = @"
using System;
using System.Linq;
using System.Collections.Generic;
class Test
{
static void Main()
{
Test0(""qqq"");
}
static void Test0<T>(T x) where T:IEnumerable<char>
{
x?.Count();
}
static void Test1<T>(ref T x) where T:IEnumerable<char>
{
x?.Count();
}
}
";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"");
comp.VerifyIL("Test.Test0<T>(T)", @"
{
// Code size 27 (0x1b)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: brfalse.s IL_001a
IL_0008: ldarga.s V_0
IL_000a: ldobj ""T""
IL_000f: box ""T""
IL_0014: call ""int System.Linq.Enumerable.Count<char>(System.Collections.Generic.IEnumerable<char>)""
IL_0019: pop
IL_001a: ret
}
").VerifyIL("Test.Test1<T>(ref T)", @"
{
// Code size 52 (0x34)
.maxstack 2
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0023
IL_0011: ldobj ""T""
IL_0016: stloc.0
IL_0017: ldloca.s V_0
IL_0019: ldloc.0
IL_001a: box ""T""
IL_001f: brtrue.s IL_0023
IL_0021: pop
IL_0022: ret
IL_0023: ldobj ""T""
IL_0028: box ""T""
IL_002d: call ""int System.Linq.Enumerable.Count<char>(System.Collections.Generic.IEnumerable<char>)""
IL_0032: pop
IL_0033: ret
}
");
}
[Fact]
public void ConditionalExtensionAccessGenericAsync001()
{
var source = @"
using System.Threading.Tasks;
class Test
{
static void Main()
{
}
async Task<int?> TestAsync<T>(T[] x) where T : I1
{
return x[0]?.CallAsync(await PassAsync());
}
static async Task<int> PassAsync()
{
await Task.Yield();
return 1;
}
}
interface I1
{
int CallAsync(int x);
}
";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { CSharpRef });
base.CompileAndVerify(comp);
}
[Fact]
public void ConditionalExtensionAccessGenericAsyncNullable001()
{
var source = @"
using System;
using System.Threading.Tasks;
class Test
{
static void Main()
{
var arr = new S1?[] { new S1(), new S1()};
TestAsync(arr).Wait();
System.Console.WriteLine(arr[1].Value.called);
}
static async Task<int?> TestAsync<T>(T?[] x)
where T : struct, I1
{
return x[await PassAsync()]?.CallAsync(await PassAsync());
}
static async Task<int> PassAsync()
{
await Task.Yield();
return 1;
}
}
struct S1 : I1
{
public int called;
public int CallAsync(int x)
{
called++;
System.Console.Write(called + 41);
return called;
}
}
interface I1
{
int CallAsync(int x);
}
";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { CSharpRef }, options: TestOptions.ReleaseExe);
base.CompileAndVerify(comp, expectedOutput: "420");
}
[Fact]
public void ConditionalMemberAccessCoalesce001()
{
var source = @"
class Program
{
class C1
{
public int x{get; set;}
public int? y{get; set;}
}
static void Main()
{
var c = new C1();
System.Console.WriteLine(Test1(c));
System.Console.WriteLine(Test1(null));
System.Console.WriteLine(Test2(c));
System.Console.WriteLine(Test2(null));
}
static int Test1(C1 c)
{
return c?.x ?? 42;
}
static int Test2(C1 c)
{
return c?.y ?? 42;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"0
42
42
42");
comp.VerifyIL("Program.Test1(Program.C1)", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0006
IL_0003: ldc.i4.s 42
IL_0005: ret
IL_0006: ldarg.0
IL_0007: call ""int Program.C1.x.get""
IL_000c: ret
}
").VerifyIL("Program.Test2(Program.C1)", @"
{
// Code size 41 (0x29)
.maxstack 1
.locals init (int? V_0,
int? V_1)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000e
IL_0003: ldloca.s V_1
IL_0005: initobj ""int?""
IL_000b: ldloc.1
IL_000c: br.s IL_0014
IL_000e: ldarg.0
IL_000f: call ""int? Program.C1.y.get""
IL_0014: stloc.0
IL_0015: ldloca.s V_0
IL_0017: call ""bool int?.HasValue.get""
IL_001c: brtrue.s IL_0021
IL_001e: ldc.i4.s 42
IL_0020: ret
IL_0021: ldloca.s V_0
IL_0023: call ""int int?.GetValueOrDefault()""
IL_0028: ret
}
");
}
[Fact]
public void ConditionalMemberAccessCoalesce001n()
{
var source = @"
class Program
{
class C1
{
public int x{get; set;}
public int? y{get; set;}
}
static void Main()
{
var c = new C1();
System.Console.WriteLine(Test1(c));
System.Console.WriteLine(Test1(null));
System.Console.WriteLine(Test2(c));
System.Console.WriteLine(Test2(null));
}
static int? Test1(C1 c)
{
return c?.x ?? (int?)42;
}
static int? Test2(C1 c)
{
return c?.y ?? (int?)42;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"0
42
42
42");
comp.VerifyIL("Program.Test1(Program.C1)", @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000b
IL_0003: ldc.i4.s 42
IL_0005: newobj ""int?..ctor(int)""
IL_000a: ret
IL_000b: ldarg.0
IL_000c: call ""int Program.C1.x.get""
IL_0011: newobj ""int?..ctor(int)""
IL_0016: ret
}
").VerifyIL("Program.Test2(Program.C1)", @"
{
// Code size 40 (0x28)
.maxstack 1
.locals init (int? V_0,
int? V_1)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000e
IL_0003: ldloca.s V_1
IL_0005: initobj ""int?""
IL_000b: ldloc.1
IL_000c: br.s IL_0014
IL_000e: ldarg.0
IL_000f: call ""int? Program.C1.y.get""
IL_0014: stloc.0
IL_0015: ldloca.s V_0
IL_0017: call ""bool int?.HasValue.get""
IL_001c: brtrue.s IL_0026
IL_001e: ldc.i4.s 42
IL_0020: newobj ""int?..ctor(int)""
IL_0025: ret
IL_0026: ldloc.0
IL_0027: ret
}");
}
[Fact]
public void ConditionalMemberAccessCoalesce001r()
{
var source = @"
class Program
{
class C1
{
public int x {get; set;}
public int? y {get; set;}
}
static void Main()
{
var c = new C1();
C1 n = null;
System.Console.WriteLine(Test1(ref c));
System.Console.WriteLine(Test1(ref n));
System.Console.WriteLine(Test2(ref c));
System.Console.WriteLine(Test2(ref n));
}
static int Test1(ref C1 c)
{
return c?.x ?? 42;
}
static int Test2(ref C1 c)
{
return c?.y ?? 42;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"0
42
42
42");
comp.VerifyIL("Program.Test1(ref Program.C1)", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: dup
IL_0003: brtrue.s IL_0009
IL_0005: pop
IL_0006: ldc.i4.s 42
IL_0008: ret
IL_0009: call ""int Program.C1.x.get""
IL_000e: ret
}
").VerifyIL("Program.Test2(ref Program.C1)", @"
{
// Code size 43 (0x2b)
.maxstack 2
.locals init (int? V_0,
int? V_1)
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: dup
IL_0003: brtrue.s IL_0011
IL_0005: pop
IL_0006: ldloca.s V_1
IL_0008: initobj ""int?""
IL_000e: ldloc.1
IL_000f: br.s IL_0016
IL_0011: call ""int? Program.C1.y.get""
IL_0016: stloc.0
IL_0017: ldloca.s V_0
IL_0019: call ""bool int?.HasValue.get""
IL_001e: brtrue.s IL_0023
IL_0020: ldc.i4.s 42
IL_0022: ret
IL_0023: ldloca.s V_0
IL_0025: call ""int int?.GetValueOrDefault()""
IL_002a: ret
}
");
}
[Fact]
public void ConditionalMemberAccessCoalesce002()
{
var source = @"
class Program
{
struct C1
{
public int x{get; set;}
public int? y{get; set;}
}
static void Main()
{
var c = new C1();
System.Console.WriteLine(Test1(c));
System.Console.WriteLine(Test1(null));
System.Console.WriteLine(Test2(c));
System.Console.WriteLine(Test2(null));
}
static int Test1(C1? c)
{
return c?.x ?? 42;
}
static int Test2(C1? c)
{
return c?.y ?? 42;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"0
42
42
42");
comp.VerifyIL("Program.Test1(Program.C1?)", @"
{
// Code size 28 (0x1c)
.maxstack 1
.locals init (Program.C1 V_0)
IL_0000: ldarga.s V_0
IL_0002: call ""bool Program.C1?.HasValue.get""
IL_0007: brtrue.s IL_000c
IL_0009: ldc.i4.s 42
IL_000b: ret
IL_000c: ldarga.s V_0
IL_000e: call ""Program.C1 Program.C1?.GetValueOrDefault()""
IL_0013: stloc.0
IL_0014: ldloca.s V_0
IL_0016: call ""readonly int Program.C1.x.get""
IL_001b: ret
}
").VerifyIL("Program.Test2(Program.C1?)", @"
{
// Code size 56 (0x38)
.maxstack 1
.locals init (int? V_0,
int? V_1,
Program.C1 V_2)
IL_0000: ldarga.s V_0
IL_0002: call ""bool Program.C1?.HasValue.get""
IL_0007: brtrue.s IL_0014
IL_0009: ldloca.s V_1
IL_000b: initobj ""int?""
IL_0011: ldloc.1
IL_0012: br.s IL_0023
IL_0014: ldarga.s V_0
IL_0016: call ""Program.C1 Program.C1?.GetValueOrDefault()""
IL_001b: stloc.2
IL_001c: ldloca.s V_2
IL_001e: call ""readonly int? Program.C1.y.get""
IL_0023: stloc.0
IL_0024: ldloca.s V_0
IL_0026: call ""bool int?.HasValue.get""
IL_002b: brtrue.s IL_0030
IL_002d: ldc.i4.s 42
IL_002f: ret
IL_0030: ldloca.s V_0
IL_0032: call ""int int?.GetValueOrDefault()""
IL_0037: ret
}
");
}
[Fact]
public void ConditionalMemberAccessCoalesce002r()
{
var source = @"
class Program
{
struct C1
{
public int x{get; set;}
public int? y{get; set;}
}
static void Main()
{
C1? c = new C1();
C1? n = null;
System.Console.WriteLine(Test1(ref c));
System.Console.WriteLine(Test1(ref n));
System.Console.WriteLine(Test2(ref c));
System.Console.WriteLine(Test2(ref n));
}
static int Test1(ref C1? c)
{
return c?.x ?? 42;
}
static int Test2(ref C1? c)
{
return c?.y ?? 42;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"0
42
42
42");
comp.VerifyIL("Program.Test1(ref Program.C1?)", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (Program.C1 V_0)
IL_0000: ldarg.0
IL_0001: dup
IL_0002: call ""bool Program.C1?.HasValue.get""
IL_0007: brtrue.s IL_000d
IL_0009: pop
IL_000a: ldc.i4.s 42
IL_000c: ret
IL_000d: call ""Program.C1 Program.C1?.GetValueOrDefault()""
IL_0012: stloc.0
IL_0013: ldloca.s V_0
IL_0015: call ""readonly int Program.C1.x.get""
IL_001a: ret
}
").VerifyIL("Program.Test2(ref Program.C1?)", @"
{
// Code size 55 (0x37)
.maxstack 2
.locals init (int? V_0,
int? V_1,
Program.C1 V_2)
IL_0000: ldarg.0
IL_0001: dup
IL_0002: call ""bool Program.C1?.HasValue.get""
IL_0007: brtrue.s IL_0015
IL_0009: pop
IL_000a: ldloca.s V_1
IL_000c: initobj ""int?""
IL_0012: ldloc.1
IL_0013: br.s IL_0022
IL_0015: call ""Program.C1 Program.C1?.GetValueOrDefault()""
IL_001a: stloc.2
IL_001b: ldloca.s V_2
IL_001d: call ""readonly int? Program.C1.y.get""
IL_0022: stloc.0
IL_0023: ldloca.s V_0
IL_0025: call ""bool int?.HasValue.get""
IL_002a: brtrue.s IL_002f
IL_002c: ldc.i4.s 42
IL_002e: ret
IL_002f: ldloca.s V_0
IL_0031: call ""int int?.GetValueOrDefault()""
IL_0036: ret
}
");
}
[Fact]
public void ConditionalMemberAccessCoalesceDefault()
{
var source = @"
class Program
{
class C1
{
public int x { get; set; }
}
static void Main()
{
var c = new C1() { x = 42 };
System.Console.WriteLine(Test(c));
System.Console.WriteLine(Test(null));
}
static int Test(C1 c)
{
return c?.x ?? 0;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"
42
0");
comp.VerifyIL("Program.Test(Program.C1)", @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int Program.C1.x.get""
IL_000b: ret
}
");
}
[Fact]
public void ConditionalMemberAccessNullCheck001()
{
var source = @"
class Program
{
class C1
{
public int x{get; set;}
}
static void Main()
{
var c = new C1();
System.Console.WriteLine(Test1(c));
System.Console.WriteLine(Test1(null));
System.Console.WriteLine(Test2(c));
System.Console.WriteLine(Test2(null));
System.Console.WriteLine(Test3(c));
System.Console.WriteLine(Test3(null));
}
static bool Test1(C1 c)
{
return c?.x == null;
}
static bool Test2(C1 c)
{
return c?.x != null;
}
static bool Test3(C1 c)
{
return c?.x > null;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True
True
False
False
False");
comp.VerifyIL("Program.Test1(Program.C1)", @"
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.1
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int Program.C1.x.get""
IL_000b: pop
IL_000c: ldc.i4.0
IL_000d: ret
}
").VerifyIL("Program.Test2(Program.C1)", @"
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int Program.C1.x.get""
IL_000b: pop
IL_000c: ldc.i4.1
IL_000d: ret
}
").VerifyIL("Program.Test3(Program.C1)", @"
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int Program.C1.x.get""
IL_000b: pop
IL_000c: ldc.i4.0
IL_000d: ret
}
");
}
[Fact]
public void ConditionalMemberAccessBinary001()
{
var source = @"
public enum N
{
zero = 0,
one = 1,
mone = -1
}
class Program
{
class C1
{
public N x{get; set;}
}
static void Main()
{
var c = new C1();
System.Console.WriteLine(Test1(c));
System.Console.WriteLine(Test1(null));
System.Console.WriteLine(Test2(c));
System.Console.WriteLine(Test2(null));
System.Console.WriteLine(Test3(c));
System.Console.WriteLine(Test3(null));
}
static bool Test1(C1 c)
{
return c?.x == N.zero;
}
static bool Test2(C1 c)
{
return c?.x != N.one;
}
static bool Test3(C1 c)
{
return c?.x > N.mone;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"True
False
True
True
True
False");
comp.VerifyIL("Program.Test1(Program.C1)", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""N Program.C1.x.get""
IL_000b: ldc.i4.0
IL_000c: ceq
IL_000e: ret
}
").VerifyIL("Program.Test2(Program.C1)", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.1
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""N Program.C1.x.get""
IL_000b: ldc.i4.1
IL_000c: ceq
IL_000e: ldc.i4.0
IL_000f: ceq
IL_0011: ret
}
").VerifyIL("Program.Test3(Program.C1)", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""N Program.C1.x.get""
IL_000b: ldc.i4.m1
IL_000c: cgt
IL_000e: ret
}
");
}
[Fact]
public void ConditionalMemberAccessBinary002()
{
var source = @"
static class ext
{
public static Program.C1.S1 y(this Program.C1 self)
{
return self.x;
}
}
class Program
{
public class C1
{
public struct S1
{
public static bool operator <(S1 s1, int s2)
{
System.Console.WriteLine('<');
return true;
}
public static bool operator >(S1 s1, int s2)
{
System.Console.WriteLine('>');
return false;
}
}
public S1 x { get; set; }
}
static void Main()
{
C1 c = new C1();
C1 n = null;
System.Console.WriteLine(Test1(c));
System.Console.WriteLine(Test1(n));
System.Console.WriteLine(Test2(ref c));
System.Console.WriteLine(Test2(ref n));
System.Console.WriteLine(Test3(c));
System.Console.WriteLine(Test3(n));
System.Console.WriteLine(Test4(ref c));
System.Console.WriteLine(Test4(ref n));
}
static bool Test1(C1 c)
{
return c?.x > -1;
}
static bool Test2(ref C1 c)
{
return c?.x < -1;
}
static bool Test3(C1 c)
{
return c?.y() > -1;
}
static bool Test4(ref C1 c)
{
return c?.y() < -1;
}
}
";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @" >
False
False
<
True
False
>
False
False
<
True
False");
comp.VerifyIL("Program.Test1(Program.C1)", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""Program.C1.S1 Program.C1.x.get""
IL_000b: ldc.i4.m1
IL_000c: call ""bool Program.C1.S1.op_GreaterThan(Program.C1.S1, int)""
IL_0011: ret
}
").VerifyIL("Program.Test2(ref Program.C1)", @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: dup
IL_0003: brtrue.s IL_0008
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
IL_0008: call ""Program.C1.S1 Program.C1.x.get""
IL_000d: ldc.i4.m1
IL_000e: call ""bool Program.C1.S1.op_LessThan(Program.C1.S1, int)""
IL_0013: ret
}
").VerifyIL("Program.Test3(Program.C1)", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""Program.C1.S1 ext.y(Program.C1)""
IL_000b: ldc.i4.m1
IL_000c: call ""bool Program.C1.S1.op_GreaterThan(Program.C1.S1, int)""
IL_0011: ret
}
").VerifyIL("Program.Test4(ref Program.C1)", @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: dup
IL_0003: brtrue.s IL_0008
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
IL_0008: call ""Program.C1.S1 ext.y(Program.C1)""
IL_000d: ldc.i4.m1
IL_000e: call ""bool Program.C1.S1.op_LessThan(Program.C1.S1, int)""
IL_0013: ret
}
");
}
[Fact]
public void ConditionalMemberAccessOptimizedLocal001()
{
var source = @"
using System;
class Program
{
class C1 : System.IDisposable
{
public bool disposed;
public void Dispose()
{
disposed = true;
}
}
static void Main()
{
Test1();
Test2<C1>();
}
static void Test1()
{
var c = new C1();
c?.Dispose();
}
static void Test2<T>() where T : IDisposable, new()
{
var c = new T();
c?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"");
comp.VerifyIL("Program.Test1()", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: newobj ""Program.C1..ctor()""
IL_0005: dup
IL_0006: brtrue.s IL_000a
IL_0008: pop
IL_0009: ret
IL_000a: call ""void Program.C1.Dispose()""
IL_000f: ret
}
").VerifyIL("Program.Test2<T>()", @"
{
// Code size 28 (0x1c)
.maxstack 1
.locals init (T V_0) //c
IL_0000: call ""T System.Activator.CreateInstance<T>()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: box ""T""
IL_000c: brfalse.s IL_001b
IL_000e: ldloca.s V_0
IL_0010: constrained. ""T""
IL_0016: callvirt ""void System.IDisposable.Dispose()""
IL_001b: ret
}
");
}
[Fact]
public void ConditionalMemberAccessOptimizedLocal002()
{
var source = @"
using System;
class Program
{
interface I1
{
void Goo(I1 arg);
}
class C1 : I1
{
public void Goo(I1 arg)
{
}
}
static void Main()
{
Test1();
Test2<C1>();
}
static void Test1()
{
var c = new C1();
c?.Goo(c);
}
static void Test2<T>() where T : I1, new()
{
var c = new T();
c?.Goo(c);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"");
comp.VerifyIL("Program.Test1()", @"
{
// Code size 17 (0x11)
.maxstack 2
.locals init (Program.C1 V_0) //c
IL_0000: newobj ""Program.C1..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: brfalse.s IL_0010
IL_0009: ldloc.0
IL_000a: ldloc.0
IL_000b: call ""void Program.C1.Goo(Program.I1)""
IL_0010: ret
}
").VerifyIL("Program.Test2<T>()", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (T V_0) //c
IL_0000: call ""T System.Activator.CreateInstance<T>()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: box ""T""
IL_000c: brfalse.s IL_0021
IL_000e: ldloca.s V_0
IL_0010: ldloc.0
IL_0011: box ""T""
IL_0016: constrained. ""T""
IL_001c: callvirt ""void Program.I1.Goo(Program.I1)""
IL_0021: ret
}
");
}
[Fact]
public void ConditionalMemberAccessRace001()
{
var source = @"
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
string s = ""hello"";
System.Action a = () =>
{
for (int i = 0; i < 1000000; i++)
{
try
{
s = s?.Length.ToString();
s = null;
Thread.Yield();
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex);
}
finally
{
s = s ?? ""hello"";
}
}
};
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
a();
System.Console.WriteLine(""Success"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"Success");
}
[Fact(), WorkItem(836, "GitHub")]
public void ConditionalMemberAccessRace002()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
string s = ""hello"";
Test(s);
}
private static void Test<T>(T s) where T : IEnumerable<char>
{
Action a = () =>
{
for (int i = 0; i < 1000000; i++)
{
var temp = s;
try
{
s?.GetEnumerator();
s = default(T);
Thread.Yield();
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex);
}
finally
{
s = temp;
}
}
};
var tasks = new List<Task>();
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
a();
// wait for all tasks to exit or we may have
// test issues when unloading ApDomain while threads still running in it
Task.WaitAll(tasks.ToArray());
System.Console.WriteLine(""Success"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"Success");
}
[Fact]
public void ConditionalMemberAccessConditional001()
{
var source = @"
using System;
class Program
{
static void Main()
{
Test1<string>(null);
Test2<string>(null);
}
static string Test1<T>(T[] arr)
{
if (arr != null && arr.Length > 0)
{
return arr[0].ToString();
}
return ""none"";
}
static string Test2<T>(T[] arr)
{
if (arr?.Length > 0)
{
return arr[0].ToString();
}
return ""none"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"");
comp.VerifyIL("Program.Test1<T>(T[])", @"
{
// Code size 34 (0x22)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_001c
IL_0003: ldarg.0
IL_0004: ldlen
IL_0005: brfalse.s IL_001c
IL_0007: ldarg.0
IL_0008: ldc.i4.0
IL_0009: readonly.
IL_000b: ldelema ""T""
IL_0010: constrained. ""T""
IL_0016: callvirt ""string object.ToString()""
IL_001b: ret
IL_001c: ldstr ""none""
IL_0021: ret
}
").VerifyIL("Program.Test2<T>(T[])", @"
{
// Code size 34 (0x22)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_001c
IL_0003: ldarg.0
IL_0004: ldlen
IL_0005: brfalse.s IL_001c
IL_0007: ldarg.0
IL_0008: ldc.i4.0
IL_0009: readonly.
IL_000b: ldelema ""T""
IL_0010: constrained. ""T""
IL_0016: callvirt ""string object.ToString()""
IL_001b: ret
IL_001c: ldstr ""none""
IL_0021: ret
}
");
}
[Fact]
public void ConditionalMemberAccessConditional002()
{
var source = @"
using System;
class Program
{
static void Main()
{
Test1<string>(null);
Test2<string>(null);
}
static string Test1<T>(T[] arr)
{
if (!(arr != null && arr.Length > 0))
{
return ""none"";
}
return arr[0].ToString();
}
static string Test2<T>(T[] arr)
{
if (!(arr?.Length > 0))
{
return ""none"";
}
return arr[0].ToString();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"");
comp.VerifyIL("Program.Test1<T>(T[])", @"
{
// Code size 34 (0x22)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0007
IL_0003: ldarg.0
IL_0004: ldlen
IL_0005: brtrue.s IL_000d
IL_0007: ldstr ""none""
IL_000c: ret
IL_000d: ldarg.0
IL_000e: ldc.i4.0
IL_000f: readonly.
IL_0011: ldelema ""T""
IL_0016: constrained. ""T""
IL_001c: callvirt ""string object.ToString()""
IL_0021: ret
}
").VerifyIL("Program.Test2<T>(T[])", @"
{
// Code size 34 (0x22)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0007
IL_0003: ldarg.0
IL_0004: ldlen
IL_0005: brtrue.s IL_000d
IL_0007: ldstr ""none""
IL_000c: ret
IL_000d: ldarg.0
IL_000e: ldc.i4.0
IL_000f: readonly.
IL_0011: ldelema ""T""
IL_0016: constrained. ""T""
IL_001c: callvirt ""string object.ToString()""
IL_0021: ret
}
");
}
[Fact]
public void ConditionalMemberAccessConditional003()
{
var source = @"
using System;
class Program
{
static void Main()
{
System.Console.WriteLine(Test1<string>(null));
System.Console.WriteLine(Test2<string>(null));
System.Console.WriteLine(Test1<string>(new string[] {}));
System.Console.WriteLine(Test2<string>(new string[] {}));
System.Console.WriteLine(Test1<string>(new string[] { System.String.Empty }));
System.Console.WriteLine(Test2<string>(new string[] { System.String.Empty }));
}
static string Test1<T>(T[] arr1)
{
var arr = arr1;
if (arr != null && arr.Length == 0)
{
return ""empty"";
}
return ""not empty"";
}
static string Test2<T>(T[] arr1)
{
var arr = arr1;
if (!(arr?.Length != 0))
{
return ""empty"";
}
return ""not empty"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"not empty
not empty
empty
empty
not empty
not empty");
comp.VerifyIL("Program.Test1<T>(T[])", @"
{
// Code size 21 (0x15)
.maxstack 1
.locals init (T[] V_0) //arr
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brfalse.s IL_000f
IL_0005: ldloc.0
IL_0006: ldlen
IL_0007: brtrue.s IL_000f
IL_0009: ldstr ""empty""
IL_000e: ret
IL_000f: ldstr ""not empty""
IL_0014: ret
}
").VerifyIL("Program.Test2<T>(T[])", @"
{
// Code size 26 (0x1a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0008
IL_0004: pop
IL_0005: ldc.i4.1
IL_0006: br.s IL_000c
IL_0008: ldlen
IL_0009: ldc.i4.0
IL_000a: cgt.un
IL_000c: brtrue.s IL_0014
IL_000e: ldstr ""empty""
IL_0013: ret
IL_0014: ldstr ""not empty""
IL_0019: ret
}
");
}
[Fact]
public void ConditionalMemberAccessConditional004()
{
var source = @"
using System;
class Program
{
static void Main()
{
var w = new WeakReference<string>(null);
Test0(ref w);
Test1(ref w);
Test2(ref w);
Test3(ref w);
}
static string Test0(ref WeakReference<string> slot)
{
string value = null;
WeakReference<string> weak = slot;
if (weak != null && weak.TryGetTarget(out value))
{
return value;
}
return ""hello"";
}
static string Test1(ref WeakReference<string> slot)
{
string value = null;
WeakReference<string> weak = slot;
if (weak?.TryGetTarget(out value) == true)
{
return value;
}
return ""hello"";
}
static string Test2(ref WeakReference<string> slot)
{
string value = null;
if (slot?.TryGetTarget(out value) == true)
{
return value;
}
return ""hello"";
}
static string Test3(ref WeakReference<string> slot)
{
string value = null;
if (slot?.TryGetTarget(out value) ?? false)
{
return value;
}
return ""hello"";
}
}
";
var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "").
VerifyIL("Program.Test0(ref System.WeakReference<string>)", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (string V_0, //value
System.WeakReference<string> V_1) //weak
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldind.ref
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: brfalse.s IL_0014
IL_0008: ldloc.1
IL_0009: ldloca.s V_0
IL_000b: callvirt ""bool System.WeakReference<string>.TryGetTarget(out string)""
IL_0010: brfalse.s IL_0014
IL_0012: ldloc.0
IL_0013: ret
IL_0014: ldstr ""hello""
IL_0019: ret
}
").VerifyIL("Program.Test1(ref System.WeakReference<string>)", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (string V_0) //value
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldind.ref
IL_0004: dup
IL_0005: brtrue.s IL_000b
IL_0007: pop
IL_0008: ldc.i4.0
IL_0009: br.s IL_0012
IL_000b: ldloca.s V_0
IL_000d: call ""bool System.WeakReference<string>.TryGetTarget(out string)""
IL_0012: brfalse.s IL_0016
IL_0014: ldloc.0
IL_0015: ret
IL_0016: ldstr ""hello""
IL_001b: ret
}
").VerifyIL("Program.Test2(ref System.WeakReference<string>)", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (string V_0) //value
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldind.ref
IL_0004: dup
IL_0005: brtrue.s IL_000b
IL_0007: pop
IL_0008: ldc.i4.0
IL_0009: br.s IL_0012
IL_000b: ldloca.s V_0
IL_000d: call ""bool System.WeakReference<string>.TryGetTarget(out string)""
IL_0012: brfalse.s IL_0016
IL_0014: ldloc.0
IL_0015: ret
IL_0016: ldstr ""hello""
IL_001b: ret
}
").VerifyIL("Program.Test3(ref System.WeakReference<string>)", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (string V_0) //value
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldind.ref
IL_0004: dup
IL_0005: brtrue.s IL_000b
IL_0007: pop
IL_0008: ldc.i4.0
IL_0009: br.s IL_0012
IL_000b: ldloca.s V_0
IL_000d: call ""bool System.WeakReference<string>.TryGetTarget(out string)""
IL_0012: brfalse.s IL_0016
IL_0014: ldloc.0
IL_0015: ret
IL_0016: ldstr ""hello""
IL_001b: ret
}
");
}
[WorkItem(1042288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042288")]
[Fact]
public void Bug1042288()
{
var source = @"
using System;
class Test
{
static void Main()
{
var c1 = new C1();
System.Console.WriteLine(c1?.M1() ?? (long)1000);
return;
}
}
class C1
{
public int M1()
{
return 1;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"1");
comp.VerifyIL("Test.Main", @"
{
// Code size 62 (0x3e)
.maxstack 2
.locals init (int? V_0,
int? V_1)
IL_0000: newobj ""C1..ctor()""
IL_0005: dup
IL_0006: brtrue.s IL_0014
IL_0008: pop
IL_0009: ldloca.s V_1
IL_000b: initobj ""int?""
IL_0011: ldloc.1
IL_0012: br.s IL_001e
IL_0014: call ""int C1.M1()""
IL_0019: newobj ""int?..ctor(int)""
IL_001e: stloc.0
IL_001f: ldloca.s V_0
IL_0021: call ""bool int?.HasValue.get""
IL_0026: brtrue.s IL_0030
IL_0028: ldc.i4 0x3e8
IL_002d: conv.i8
IL_002e: br.s IL_0038
IL_0030: ldloca.s V_0
IL_0032: call ""int int?.GetValueOrDefault()""
IL_0037: conv.i8
IL_0038: call ""void System.Console.WriteLine(long)""
IL_003d: ret
}
");
}
[WorkItem(470, "CodPlex")]
[Fact]
public void CodPlexBug470_01()
{
var source = @"
class C
{
public static void Main()
{
System.Console.WriteLine(MyMethod(null));
System.Console.WriteLine(MyMethod(new MyType()));
}
public static decimal MyMethod(MyType myObject)
{
return myObject?.MyField ?? 0m;
}
}
public class MyType
{
public decimal MyField = 123;
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0
123");
verifier.VerifyIL("C.MyMethod", @"
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0009
IL_0003: ldsfld ""decimal decimal.Zero""
IL_0008: ret
IL_0009: ldarg.0
IL_000a: ldfld ""decimal MyType.MyField""
IL_000f: ret
}");
}
[WorkItem(470, "CodPlex")]
[Fact]
public void CodPlexBug470_02()
{
var source = @"
class C
{
public static void Main()
{
System.Console.WriteLine(MyMethod(null));
System.Console.WriteLine(MyMethod(new MyType()));
}
public static decimal MyMethod(MyType myObject)
{
return myObject?.MyField ?? default(decimal);
}
}
public class MyType
{
public decimal MyField = 123;
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0
123");
verifier.VerifyIL("C.MyMethod", @"
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0009
IL_0003: ldsfld ""decimal decimal.Zero""
IL_0008: ret
IL_0009: ldarg.0
IL_000a: ldfld ""decimal MyType.MyField""
IL_000f: ret
}");
}
[WorkItem(470, "CodPlex")]
[Fact]
public void CodPlexBug470_03()
{
var source = @"
using System;
class C
{
public static void Main()
{
System.Console.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, ""{0}"", MyMethod(null)));
System.Console.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, ""{0}"", MyMethod(new MyType())));
}
public static DateTime MyMethod(MyType myObject)
{
return myObject?.MyField ?? default(DateTime);
}
}
public class MyType
{
public DateTime MyField = new DateTime(100000000);
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"01/01/0001 00:00:00
01/01/0001 00:00:10");
verifier.VerifyIL("C.MyMethod", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (System.DateTime V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""System.DateTime""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldarg.0
IL_000e: ldfld ""System.DateTime MyType.MyField""
IL_0013: ret
}");
}
[WorkItem(470, "CodPlex")]
[Fact]
public void CodPlexBug470_04()
{
var source = @"
class C
{
public static void Main()
{
System.Console.WriteLine(MyMethod(null).F);
System.Console.WriteLine(MyMethod(new MyType()).F);
}
public static MyStruct MyMethod(MyType myObject)
{
return myObject?.MyField ?? default(MyStruct);
}
}
public class MyType
{
public MyStruct MyField = new MyStruct() {F = 123};
}
public struct MyStruct
{
public int F;
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0
123");
verifier.VerifyIL("C.MyMethod", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (MyStruct V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""MyStruct""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldarg.0
IL_000e: ldfld ""MyStruct MyType.MyField""
IL_0013: ret
}");
}
[WorkItem(1103294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103294")]
[Fact]
public void Bug1103294_01()
{
var source = @"
class C
{
static void Main()
{
System.Console.WriteLine(""---"");
Goo<int>(new C<int>());
System.Console.WriteLine(""---"");
Goo<int>(null);
System.Console.WriteLine(""---"");
}
static void Goo<T>(C<T> x)
{
x?.M();
}
}
class C<T>
{
public T M()
{
System.Console.WriteLine(""M"");
return default(T);
}
}";
var verifier = CompileAndVerify(source, expectedOutput: @"---
M
---
---");
verifier.VerifyIL("C.Goo<T>", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brfalse.s IL_000a
IL_0003: ldarg.0
IL_0004: call ""T C<T>.M()""
IL_0009: pop
IL_000a: ret
}");
}
[WorkItem(1103294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103294")]
[Fact]
public void Bug1103294_02()
{
var source = @"
unsafe class C
{
static void Main()
{
System.Console.WriteLine(""---"");
Goo(new C());
System.Console.WriteLine(""---"");
Goo(null);
System.Console.WriteLine(""---"");
}
static void Goo(C x)
{
x?.M();
}
public int* M()
{
System.Console.WriteLine(""M"");
return null;
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), verify: Verification.Fails, expectedOutput: @"---
M
---
---");
verifier.VerifyIL("C.Goo", @"
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: nop
IL_0001: ldarg.0
IL_0002: brtrue.s IL_0006
IL_0004: br.s IL_000d
IL_0006: ldarg.0
IL_0007: call ""int* C.M()""
IL_000c: pop
IL_000d: ret
}");
}
[WorkItem(23422, "https://github.com/dotnet/roslyn/issues/23422")]
[Fact]
public void ConditionalRefLike()
{
var source = @"
class C
{
static void Main()
{
System.Console.WriteLine(""---"");
Goo(new C());
System.Console.WriteLine(""---"");
Goo(null);
System.Console.WriteLine(""---"");
}
static void Goo(C x)
{
x?.M();
}
public RefLike M()
{
System.Console.WriteLine(""M"");
return default;
}
public ref struct RefLike{}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), expectedOutput: @"---
M
---
---");
verifier.VerifyIL("C.Goo", @"
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: nop
IL_0001: ldarg.0
IL_0002: brtrue.s IL_0006
IL_0004: br.s IL_000d
IL_0006: ldarg.0
IL_0007: call ""C.RefLike C.M()""
IL_000c: pop
IL_000d: ret
}");
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_01()
{
var source = @"
using System;
class Test
{
static void Main()
{
System.Console.WriteLine(""---"");
C.F1(null);
System.Console.WriteLine(""---"");
C.F1(new C());
System.Console.WriteLine(""---"");
C.F2(null);
System.Console.WriteLine(""---"");
C.F2(new C());
System.Console.WriteLine(""---"");
}
}
class C
{
static public void F1(C c)
{
System.Console.WriteLine(""F1"");
Action a = () => c?.M();
a();
}
static public void F2(C c) => c?.M();
void M() => System.Console.WriteLine(""M"");
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"---
F1
---
F1
M
---
---
M
---");
verifier.VerifyIL("C.<>c__DisplayClass0_0.<F1>b__0", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<>c__DisplayClass0_0.c""
IL_0006: dup
IL_0007: brtrue.s IL_000c
IL_0009: pop
IL_000a: br.s IL_0012
IL_000c: call ""void C.M()""
IL_0011: nop
IL_0012: ret
}");
verifier.VerifyIL("C.F2", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: br.s IL_000c
IL_0005: ldarg.0
IL_0006: call ""void C.M()""
IL_000b: nop
IL_000c: ret
}");
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_02()
{
var source = @"
using System;
class Test
{
static void Main()
{
}
}
class C
{
static public void F1(C c)
{
System.Console.WriteLine(""F1"");
Func<object> a = () => c?.M();
}
static public object F2(C c) => c?.M();
static public object P1 => (new C())?.M();
void M() => System.Console.WriteLine(""M"");
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (16,32): error CS0029: Cannot implicitly convert type 'void' to 'object'
// Func<object> a = () => c?.M();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c?.M()").WithArguments("void", "object").WithLocation(16, 32),
// (16,32): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// Func<object> a = () => c?.M();
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "c?.M()").WithArguments("lambda expression").WithLocation(16, 32),
// (19,37): error CS0029: Cannot implicitly convert type 'void' to 'object'
// static public object F2(C c) => c?.M();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c?.M()").WithArguments("void", "object").WithLocation(19, 37),
// (21,32): error CS0029: Cannot implicitly convert type 'void' to 'object'
// static public object P1 => (new C())?.M();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new C())?.M()").WithArguments("void", "object").WithLocation(21, 32)
);
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_03()
{
var source = @"
using System;
class Test
{
static void Main()
{
System.Console.WriteLine(""---"");
C<int>.F1(null);
System.Console.WriteLine(""---"");
C<int>.F1(new C<int>());
System.Console.WriteLine(""---"");
C<int>.F2(null);
System.Console.WriteLine(""---"");
C<int>.F2(new C<int>());
System.Console.WriteLine(""---"");
}
}
class C<T>
{
static public void F1(C<T> c)
{
System.Console.WriteLine(""F1"");
Action a = () => c?.M();
a();
}
static public void F2(C<T> c) => c?.M();
T M()
{
System.Console.WriteLine(""M"");
return default(T);
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"---
F1
---
F1
M
---
---
M
---");
verifier.VerifyIL("C<T>.<>c__DisplayClass0_0.<F1>b__0()", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C<T> C<T>.<>c__DisplayClass0_0.c""
IL_0006: dup
IL_0007: brtrue.s IL_000c
IL_0009: pop
IL_000a: br.s IL_0012
IL_000c: call ""T C<T>.M()""
IL_0011: pop
IL_0012: ret
}");
verifier.VerifyIL("C<T>.F2", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: br.s IL_000c
IL_0005: ldarg.0
IL_0006: call ""T C<T>.M()""
IL_000b: pop
IL_000c: ret
}");
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_04()
{
var source = @"
using System;
class Test
{
static void Main()
{
}
}
class C<T>
{
static public void F1(C<T> c)
{
Func<object> a = () => c?.M();
}
static public object F2(C<T> c) => c?.M();
static public object P1 => (new C<T>())?.M();
T M()
{
return default(T);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (15,33): error CS0023: Operator '?' cannot be applied to operand of type 'T'
// Func<object> a = () => c?.M();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(15, 33),
// (18,41): error CS0023: Operator '?' cannot be applied to operand of type 'T'
// static public object F2(C<T> c) => c?.M();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(18, 41),
// (20,44): error CS0023: Operator '?' cannot be applied to operand of type 'T'
// static public object P1 => (new C<T>())?.M();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(20, 44)
);
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_05()
{
var source = @"
using System;
class Test
{
static void Main()
{
System.Console.WriteLine(""---"");
C.F1(null);
System.Console.WriteLine(""---"");
C.F1(new C());
System.Console.WriteLine(""---"");
C.F2(null);
System.Console.WriteLine(""---"");
C.F2(new C());
System.Console.WriteLine(""---"");
}
}
unsafe class C
{
static public void F1(C c)
{
System.Console.WriteLine(""F1"");
Action<object> a = o => c?.M();
a(null);
}
static public void F2(C c) => c?.M();
void* M()
{
System.Console.WriteLine(""M"");
return null;
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), verify: Verification.Fails, expectedOutput: @"---
F1
---
F1
M
---
---
M
---");
verifier.VerifyIL("C.<>c__DisplayClass0_0.<F1>b__0", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<>c__DisplayClass0_0.c""
IL_0006: dup
IL_0007: brtrue.s IL_000c
IL_0009: pop
IL_000a: br.s IL_0012
IL_000c: call ""void* C.M()""
IL_0011: pop
IL_0012: ret
}");
verifier.VerifyIL("C.F2", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: br.s IL_000c
IL_0005: ldarg.0
IL_0006: call ""void* C.M()""
IL_000b: pop
IL_000c: ret
}");
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_06()
{
var source = @"
using System;
class Test
{
static void Main()
{
}
}
unsafe class C
{
static public void F1(C c)
{
System.Console.WriteLine(""F1"");
Func<object, object> a = o => c?.M();
}
static public object F2(C c) => c?.M();
static public object P1 => (new C())?.M();
void* M()
{
System.Console.WriteLine(""M"");
return null;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
// (16,40): error CS0023: Operator '?' cannot be applied to operand of type 'void*'
// Func<object, object> a = o => c?.M();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(16, 40),
// (19,38): error CS0023: Operator '?' cannot be applied to operand of type 'void*'
// static public object F2(C c) => c?.M();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(19, 38),
// (21,41): error CS0023: Operator '?' cannot be applied to operand of type 'void*'
// static public object P1 => (new C())?.M();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(21, 41)
);
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_07()
{
var source = @"
using System;
class Test
{
static void Main()
{
C<int>.Test();
}
}
class C<T>
{
public static void Test()
{
var x = new [] {null, new C<T>()};
for (int i = 0; i < 2; x[i-1]?.M())
{
System.Console.WriteLine(""---"");
System.Console.WriteLine(""Loop"");
i++;
}
System.Console.WriteLine(""---"");
}
public T M()
{
System.Console.WriteLine(""M"");
return default(T);
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @" ---
Loop
---
Loop
M
---");
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_08()
{
var source = @"
using System;
class Test
{
static void Main()
{
C<int>.Test();
}
}
class C<T>
{
public static void Test()
{
var x = new [] {null, new C<T>()};
System.Console.WriteLine(""---"");
for (x[0]?.M(); false;)
{
}
System.Console.WriteLine(""---"");
for (x[1]?.M(); false;)
{
}
System.Console.WriteLine(""---"");
}
public T M()
{
System.Console.WriteLine(""M"");
return default(T);
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"---
---
M
---");
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_09()
{
var source = @"
class Test
{
static void Main()
{
}
}
class C<T>
{
public static void Test()
{
C<T> x = null;
for (; x?.M();)
{
}
}
public T M()
{
return default(T);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (15,17): error CS0023: Operator '?' cannot be applied to operand of type 'T'
// for (; x?.M();)
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(15, 17)
);
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_10()
{
var source = @"
using System;
class Test
{
static void Main()
{
C<int>.Test();
}
}
class C<T>
{
public static void Test()
{
System.Console.WriteLine(""---"");
M1(a => a?.M(), null);
System.Console.WriteLine(""---"");
M1((a) => a?.M(), new C<T>());
System.Console.WriteLine(""---"");
}
static void M1(Action<C<T>> x, C<T> y)
{
System.Console.WriteLine(""M1(Action<C<T>> x)"");
x(y);
}
static void M1(Func<C<T>, object> x, C<T> y)
{
System.Console.WriteLine(""M1(Func<C<T>, object> x)"");
x(y);
}
public T M()
{
System.Console.WriteLine(""M"");
return default(T);
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"---
M1(Action<C<T>> x)
---
M1(Action<C<T>> x)
M
---");
}
[WorkItem(74, "https://github.com/dotnet/roslyn/issues/74")]
[Fact]
public void ConditionalInAsyncTask()
{
var source = @"
#pragma warning disable CS1998 // suppress 'no await in async' warning
using System;
using System.Threading.Tasks;
class Goo<T>
{
public T Method(int i)
{
Console.Write(i);
return default(T); // returns value of unconstrained type parameter type
}
public void M1(Goo<T> x) => x?.Method(4);
public async void M2(Goo<T> x) => x?.Method(5);
public async Task M3(Goo<T> x) => x?.Method(6);
public async Task M4() {
Goo<T> a = new Goo<T>();
Goo<T> b = null;
Action f1 = async () => a?.Method(1);
f1();
f1 = async () => b?.Method(0);
f1();
Func<Task> f2 = async () => a?.Method(2);
await f2();
Func<Task> f3 = async () => b?.Method(3);
await f3();
M1(a); M1(b);
M2(a); M2(b);
await M3(a);
await M3(b);
}
}
class Program
{
public static void Main()
{
// this will complete synchronously as there are no truly async ops.
new Goo<int>().M4();
}
}";
var compilation = CreateCompilationWithMscorlib45(
source, references: new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput: "12456");
}
[WorkItem(825, "https://github.com/dotnet/roslyn/issues/825")]
[Fact]
public void ConditionalBoolExpr01()
{
var source = @"
class C
{
public static void Main()
{
System.Console.WriteLine(HasLength(null, 0));
}
static bool HasLength(string s, int len)
{
return s?.Length == len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"False");
verifier.VerifyIL("C.HasLength", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int string.Length.get""
IL_000b: ldarg.1
IL_000c: ceq
IL_000e: ret
}");
}
[WorkItem(825, "https://github.com/dotnet/roslyn/issues/825")]
[Fact]
public void ConditionalBoolExpr01a()
{
var source = @"
class C
{
public static void Main()
{
System.Console.WriteLine(HasLength(null, 0));
}
static bool HasLength(string s, byte len)
{
return s?.Length == len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"False");
verifier.VerifyIL("C.HasLength", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int string.Length.get""
IL_000b: ldarg.1
IL_000c: ceq
IL_000e: ret
}");
}
[WorkItem(825, "https://github.com/dotnet/roslyn/issues/825")]
[WorkItem(5662, "https://github.com/dotnet/roslyn/issues/5662")]
[Fact]
public void ConditionalBoolExpr01b()
{
var source = @"
class C
{
public static void Main()
{
System.Console.WriteLine(HasLength(null, long.MaxValue));
try
{
System.Console.WriteLine(HasLengthChecked(null, long.MaxValue));
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.GetType().Name);
}
}
static bool HasLength(string s, long len)
{
return s?.Length == (int)(byte)len;
}
static bool HasLengthChecked(string s, long len)
{
checked
{
return s?.Length == (int)(byte)len;
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"False
OverflowException");
verifier.VerifyIL("C.HasLength", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int string.Length.get""
IL_000b: ldarg.1
IL_000c: conv.u1
IL_000d: ceq
IL_000f: ret
}").VerifyIL("C.HasLengthChecked", @"
{
// Code size 48 (0x30)
.maxstack 2
.locals init (int? V_0,
int V_1,
int? V_2)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000e
IL_0003: ldloca.s V_2
IL_0005: initobj ""int?""
IL_000b: ldloc.2
IL_000c: br.s IL_0019
IL_000e: ldarg.0
IL_000f: call ""int string.Length.get""
IL_0014: newobj ""int?..ctor(int)""
IL_0019: stloc.0
IL_001a: ldarg.1
IL_001b: conv.ovf.u1
IL_001c: stloc.1
IL_001d: ldloca.s V_0
IL_001f: call ""int int?.GetValueOrDefault()""
IL_0024: ldloc.1
IL_0025: ceq
IL_0027: ldloca.s V_0
IL_0029: call ""bool int?.HasValue.get""
IL_002e: and
IL_002f: ret
}");
}
[Fact]
public void ConditionalBoolExpr02()
{
var source = @"
class C
{
public static void Main()
{
System.Console.Write(HasLength(null, 0));
System.Console.Write(HasLength(null, 3));
System.Console.Write(HasLength(""q"", 2));
}
static bool HasLength(string s, int len)
{
return (s?.Length ?? 2) + 1 == len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"FalseTrueTrue");
verifier.VerifyIL("C.HasLength", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0006
IL_0003: ldc.i4.2
IL_0004: br.s IL_000c
IL_0006: ldarg.0
IL_0007: call ""int string.Length.get""
IL_000c: ldc.i4.1
IL_000d: add
IL_000e: ldarg.1
IL_000f: ceq
IL_0011: ret
}");
}
[Fact]
public void ConditionalBoolExpr02a()
{
var source = @"
class C
{
public static void Main()
{
System.Console.Write(NotHasLength(null, 0));
System.Console.Write(NotHasLength(null, 3));
System.Console.Write(NotHasLength(""q"", 2));
}
static bool NotHasLength(string s, int len)
{
return s?.Length + 1 != len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalse");
verifier.VerifyIL("C.NotHasLength", @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.1
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int string.Length.get""
IL_000b: ldc.i4.1
IL_000c: add
IL_000d: ldarg.1
IL_000e: ceq
IL_0010: ldc.i4.0
IL_0011: ceq
IL_0013: ret
}");
}
[Fact]
public void ConditionalBoolExpr02b()
{
var source = @"
class C
{
public static void Main()
{
System.Console.Write(NotHasLength(null, 0));
System.Console.Write(NotHasLength(null, 3));
System.Console.Write(NotHasLength(""q"", 2));
System.Console.Write(NotHasLength(null, null));
}
static bool NotHasLength(string s, int? len)
{
return s?.Length + 1 != len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalseFalse");
verifier.VerifyIL("C.NotHasLength", @"
{
// Code size 42 (0x2a)
.maxstack 2
.locals init (int? V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000b
IL_0003: ldarga.s V_1
IL_0005: call ""bool int?.HasValue.get""
IL_000a: ret
IL_000b: ldarg.0
IL_000c: call ""int string.Length.get""
IL_0011: ldc.i4.1
IL_0012: add
IL_0013: ldarg.1
IL_0014: stloc.0
IL_0015: ldloca.s V_0
IL_0017: call ""int int?.GetValueOrDefault()""
IL_001c: ceq
IL_001e: ldloca.s V_0
IL_0020: call ""bool int?.HasValue.get""
IL_0025: and
IL_0026: ldc.i4.0
IL_0027: ceq
IL_0029: ret
}");
}
[Fact]
public void ConditionalBoolExpr03()
{
var source = @"
using System.Threading.Tasks;
static class C
{
public static void Main()
{
System.Console.Write(HasLength(null, 0).Result);
System.Console.Write(HasLength(null, 3).Result);
System.Console.Write(HasLength(""q"", 2).Result);
}
static async Task<bool> HasLength(string s, int len)
{
return (s?.Goo(await Bar()) ?? await Bar() + await Bar()) + 1 == len;
}
static int Goo(this string s, int arg)
{
return s.Length;
}
static async Task<int> Bar()
{
await Task.Yield();
return 1;
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"FalseTrueTrue");
}
[Fact]
public void ConditionalBoolExpr04()
{
var source = @"
using System.Threading.Tasks;
static class C
{
public static void Main()
{
System.Console.Write(HasLength((string)null, 0).Result);
System.Console.Write(HasLength((string)null, 3).Result);
System.Console.Write(HasLength(""q"", 2).Result);
}
static async Task<bool> HasLength<T>(T s, int len)
{
return (s?.Goo(await Bar()) ?? 2) + 1 == len;
}
static int Goo<T>(this T s, int arg)
{
return ((string)(object)s).Length;
}
static async Task<int> Bar()
{
await Task.Yield();
return 1;
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"FalseTrueTrue");
}
[Fact]
public void ConditionalBoolExpr05()
{
var source = @"
using System.Threading.Tasks;
static class C
{
public static void Main()
{
System.Console.Write(HasLength((string)null, 0).Result);
System.Console.Write(HasLength((string)null, 3).Result);
System.Console.Write(HasLength(""q"", 2).Result);
}
static async Task<bool> HasLength<T>(T s, int len)
{
return (s?.Goo(await Bar(await Bar())) ?? 2) + 1 == len;
}
static int Goo<T>(this T s, int arg)
{
return ((string)(object)s).Length;
}
static async Task<int> Bar()
{
await Task.Yield();
return 1;
}
static async Task<int> Bar(int arg)
{
await Task.Yield();
return arg;
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"FalseTrueTrue");
}
[Fact]
public void ConditionalBoolExpr06()
{
var source = @"
using System.Threading.Tasks;
static class C
{
public static void Main()
{
System.Console.Write(HasLength(null, 0).Result);
System.Console.Write(HasLength(null, 7).Result);
System.Console.Write(HasLength(""q"", 7).Result);
}
static async Task<bool> HasLength(string s, int len)
{
System.Console.WriteLine(s?.Goo(await Bar())?.Goo(await Bar()) + ""#"");
return s?.Goo(await Bar())?.Goo(await Bar()).Length == len;
}
static string Goo(this string s, string arg)
{
return s + arg;
}
static async Task<string> Bar()
{
await Task.Yield();
return ""Bar"";
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"#
False#
FalseqBarBar#
True");
}
[Fact]
public void ConditionalBoolExpr07()
{
var source = @"
using System.Threading.Tasks;
static class C
{
public static void Main()
{
System.Console.WriteLine(Test(null).Result);
System.Console.WriteLine(Test(""q"").Result);
}
static async Task<bool> Test(string s)
{
return (await Bar(s))?.Goo(await Bar())?.ToString()?.Length > 1;
}
static string Goo(this string s, string arg1)
{
return s + arg1;
}
static async Task<string> Bar()
{
await Task.Yield();
return ""Bar"";
}
static async Task<string> Bar(string arg)
{
await Task.Yield();
return arg;
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True");
}
[Fact]
public void ConditionalBoolExpr08()
{
var source = @"
using System.Threading.Tasks;
static class C
{
public static void Main()
{
System.Console.WriteLine(Test(null).Result);
System.Console.WriteLine(Test(""q"").Result);
}
static async Task<bool> Test(string s)
{
return (await Bar(s))?.Insert(0, await Bar())?.ToString()?.Length > 1;
}
static async Task<string> Bar()
{
await Task.Yield();
return ""Bar"";
}
static async Task<dynamic> Bar(string arg)
{
await Task.Yield();
return arg;
}
}";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True");
}
[Fact]
public void ConditionalUserDef01()
{
var source = @"
class C
{
struct S1
{
public static bool operator ==(S1? x, S1?y)
{
System.Console.Write(""=="");
return true;
}
public static bool operator !=(S1? x, S1? y)
{
System.Console.Write(""!="");
return false;
}
}
class C1
{
public S1 Goo()
{
return new S1();
}
}
public static void Main()
{
System.Console.WriteLine(TestEq(null, new S1()));
System.Console.WriteLine(TestEq(new C1(), new S1()));
System.Console.WriteLine(TestNeq(null, new S1()));
System.Console.WriteLine(TestNeq(new C1(), new S1()));
}
static bool TestEq(C1 c, S1 arg)
{
return c?.Goo() == arg;
}
static bool TestNeq(C1 c, S1 arg)
{
return c?.Goo() != arg;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"==True
==True
!=False
!=False");
verifier.VerifyIL("C.TestNeq", @"
{
// Code size 37 (0x25)
.maxstack 2
.locals init (C.S1? V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000e
IL_0003: ldloca.s V_0
IL_0005: initobj ""C.S1?""
IL_000b: ldloc.0
IL_000c: br.s IL_0019
IL_000e: ldarg.0
IL_000f: call ""C.S1 C.C1.Goo()""
IL_0014: newobj ""C.S1?..ctor(C.S1)""
IL_0019: ldarg.1
IL_001a: newobj ""C.S1?..ctor(C.S1)""
IL_001f: call ""bool C.S1.op_Inequality(C.S1?, C.S1?)""
IL_0024: ret
}");
}
[Fact]
public void ConditionalUserDef01n()
{
var source = @"
class C
{
struct S1
{
public static bool operator ==(S1? x, S1?y)
{
System.Console.Write(""=="");
return true;
}
public static bool operator !=(S1? x, S1? y)
{
System.Console.Write(""!="");
return false;
}
}
class C1
{
public S1 Goo()
{
return new S1();
}
}
public static void Main()
{
System.Console.WriteLine(TestEq(null, new S1()));
System.Console.WriteLine(TestEq(new C1(), new S1()));
System.Console.WriteLine(TestEq(new C1(), null));
System.Console.WriteLine(TestNeq(null, new S1()));
System.Console.WriteLine(TestNeq(new C1(), new S1()));
System.Console.WriteLine(TestNeq(new C1(), null));
}
static bool TestEq(C1 c, S1? arg)
{
return c?.Goo() == arg;
}
static bool TestNeq(C1 c, S1? arg)
{
return c?.Goo() != arg;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"==True
==True
==True
!=False
!=False
!=False");
verifier.VerifyIL("C.TestNeq", @"
{
// Code size 32 (0x20)
.maxstack 2
.locals init (C.S1? V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000e
IL_0003: ldloca.s V_0
IL_0005: initobj ""C.S1?""
IL_000b: ldloc.0
IL_000c: br.s IL_0019
IL_000e: ldarg.0
IL_000f: call ""C.S1 C.C1.Goo()""
IL_0014: newobj ""C.S1?..ctor(C.S1)""
IL_0019: ldarg.1
IL_001a: call ""bool C.S1.op_Inequality(C.S1?, C.S1?)""
IL_001f: ret
}");
}
[Fact]
public void ConditionalUserDef02()
{
var source = @"
class C
{
struct S1
{
public static bool operator ==(S1 x, S1 y)
{
System.Console.Write(""=="");
return true;
}
public static bool operator !=(S1 x, S1 y)
{
System.Console.Write(""!="");
return false;
}
}
class C1
{
public S1 Goo()
{
return new S1();
}
}
public static void Main()
{
System.Console.WriteLine(TestEq(null, new S1()));
System.Console.WriteLine(TestEq(new C1(), new S1()));
System.Console.WriteLine(TestNeq(null, new S1()));
System.Console.WriteLine(TestNeq(new C1(), new S1()));
}
static bool TestEq(C1 c, S1 arg)
{
return c?.Goo() == arg;
}
static bool TestNeq(C1 c, S1 arg)
{
return c?.Goo() != arg;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"False
==True
True
!=False");
verifier.VerifyIL("C.TestNeq", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.1
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""C.S1 C.C1.Goo()""
IL_000b: ldarg.1
IL_000c: call ""bool C.S1.op_Inequality(C.S1, C.S1)""
IL_0011: ret
}");
}
[Fact]
public void ConditionalUserDef02n()
{
var source = @"
class C
{
struct S1
{
public static bool operator ==(S1 x, S1 y)
{
System.Console.Write(""=="");
return true;
}
public static bool operator !=(S1 x, S1 y)
{
System.Console.Write(""!="");
return false;
}
}
class C1
{
public S1 Goo()
{
return new S1();
}
}
public static void Main()
{
System.Console.WriteLine(TestEq(null, new S1()));
System.Console.WriteLine(TestEq(new C1(), new S1()));
System.Console.WriteLine(TestEq(new C1(), null));
System.Console.WriteLine(TestNeq(null, new S1()));
System.Console.WriteLine(TestNeq(new C1(), new S1()));
System.Console.WriteLine(TestNeq(new C1(), null));
}
static bool TestEq(C1 c, S1? arg)
{
return c?.Goo() == arg;
}
static bool TestNeq(C1 c, S1? arg)
{
return c?.Goo() != arg;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"False
==True
False
True
!=False
True");
verifier.VerifyIL("C.TestNeq", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (C.S1 V_0,
C.S1? V_1)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000b
IL_0003: ldarga.s V_1
IL_0005: call ""bool C.S1?.HasValue.get""
IL_000a: ret
IL_000b: ldarg.0
IL_000c: call ""C.S1 C.C1.Goo()""
IL_0011: stloc.0
IL_0012: ldarg.1
IL_0013: stloc.1
IL_0014: ldloca.s V_1
IL_0016: call ""bool C.S1?.HasValue.get""
IL_001b: brtrue.s IL_001f
IL_001d: ldc.i4.1
IL_001e: ret
IL_001f: ldloc.0
IL_0020: ldloca.s V_1
IL_0022: call ""C.S1 C.S1?.GetValueOrDefault()""
IL_0027: call ""bool C.S1.op_Inequality(C.S1, C.S1)""
IL_002c: ret
}");
}
[Fact]
public void Bug1()
{
var source = @"
using System;
class Test
{
static void Main()
{
var c1 = new C1();
M1(c1);
M2(c1);
}
static void M1(C1 c1)
{
if (c1?.P == 1) Console.WriteLine(1);
}
static void M2(C1 c1)
{
if (c1 != null && c1.P == 1) Console.WriteLine(1);
}
}
class C1
{
public int P => 1;
}
";
var comp = CompileAndVerify(source, expectedOutput: @"1
1");
comp.VerifyIL("Test.M1", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0012
IL_0003: ldarg.0
IL_0004: call ""int C1.P.get""
IL_0009: ldc.i4.1
IL_000a: bne.un.s IL_0012
IL_000c: ldc.i4.1
IL_000d: call ""void System.Console.WriteLine(int)""
IL_0012: ret
}
");
comp.VerifyIL("Test.M2", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0012
IL_0003: ldarg.0
IL_0004: callvirt ""int C1.P.get""
IL_0009: ldc.i4.1
IL_000a: bne.un.s IL_0012
IL_000c: ldc.i4.1
IL_000d: call ""void System.Console.WriteLine(int)""
IL_0012: ret
}
");
}
[Fact]
public void ConditionalBoolExpr02ba()
{
var source = @"
class C
{
public static void Main()
{
System.Console.Write(NotHasLength(null, 0));
System.Console.Write(NotHasLength(null, 3));
System.Console.Write(NotHasLength(1, 2));
}
static bool NotHasLength(int? s, int len)
{
return s?.GetHashCode() + 1 != len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalse");
verifier.VerifyIL("C.NotHasLength", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brtrue.s IL_000b
IL_0009: ldc.i4.1
IL_000a: ret
IL_000b: ldarga.s V_0
IL_000d: call ""int int?.GetValueOrDefault()""
IL_0012: stloc.0
IL_0013: ldloca.s V_0
IL_0015: call ""int int.GetHashCode()""
IL_001a: ldc.i4.1
IL_001b: add
IL_001c: ldarg.1
IL_001d: ceq
IL_001f: ldc.i4.0
IL_0020: ceq
IL_0022: ret
}
");
}
[Fact]
public void ConditionalBoolExpr02bb()
{
var source = @"
class C
{
public static void Main()
{
System.Console.Write(NotHasLength(null, 0));
System.Console.Write(NotHasLength(null, 3));
System.Console.Write(NotHasLength(1, 2));
System.Console.Write(NotHasLength(null, null));
}
static bool NotHasLength(int? s, int? len)
{
return s?.GetHashCode() + 1 != len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalseFalse");
verifier.VerifyIL("C.NotHasLength", @"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (int? V_0,
int V_1)
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brtrue.s IL_0011
IL_0009: ldarga.s V_1
IL_000b: call ""bool int?.HasValue.get""
IL_0010: ret
IL_0011: ldarga.s V_0
IL_0013: call ""int int?.GetValueOrDefault()""
IL_0018: stloc.1
IL_0019: ldloca.s V_1
IL_001b: call ""int int.GetHashCode()""
IL_0020: ldc.i4.1
IL_0021: add
IL_0022: ldarg.1
IL_0023: stloc.0
IL_0024: ldloca.s V_0
IL_0026: call ""int int?.GetValueOrDefault()""
IL_002b: ceq
IL_002d: ldloca.s V_0
IL_002f: call ""bool int?.HasValue.get""
IL_0034: and
IL_0035: ldc.i4.0
IL_0036: ceq
IL_0038: ret
}");
}
[Fact]
public void ConditionalUnary()
{
var source = @"
class C
{
public static void Main()
{
var x = - - -((string)null)?.Length ?? - - -string.Empty?.Length;
System.Console.WriteLine(x);
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0");
verifier.VerifyIL("C.Main", @"
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (int? V_0)
IL_0000: ldsfld ""string string.Empty""
IL_0005: dup
IL_0006: brtrue.s IL_0014
IL_0008: pop
IL_0009: ldloca.s V_0
IL_000b: initobj ""int?""
IL_0011: ldloc.0
IL_0012: br.s IL_0021
IL_0014: call ""int string.Length.get""
IL_0019: neg
IL_001a: neg
IL_001b: neg
IL_001c: newobj ""int?..ctor(int)""
IL_0021: box ""int?""
IL_0026: call ""void System.Console.WriteLine(object)""
IL_002b: ret
}
");
}
[WorkItem(7388, "https://github.com/dotnet/roslyn/issues/7388")]
[Fact]
public void ConditionalClassConstrained001()
{
var source = @"
using System;
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
var v = new A<object>();
System.Console.WriteLine(A<object>.Test(v));
}
public class A<T> : object where T : class
{
public T Value { get { return (T)(object)42; }}
public static T Test(A<T> val)
{
return val?.Value;
}
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"42");
verifier.VerifyIL("ConsoleApplication9.Program.A<T>.Test(ConsoleApplication9.Program.A<T>)", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""T""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldarg.0
IL_000e: call ""T ConsoleApplication9.Program.A<T>.Value.get""
IL_0013: ret
}");
}
[Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")]
public void ConditionalAccessOffOfUnconstrainedDefault1()
{
var source = @"
using System;
public class Test<T>
{
public string Run()
{
return default(T)?.ToString();
}
}
class Program
{
static void Main()
{
Console.WriteLine(""--"");
Console.WriteLine(new Test<string>().Run());
Console.WriteLine(""--"");
Console.WriteLine(new Test<int>().Run());
Console.WriteLine(""--"");
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput:
@"--
--
0
--");
verifier.VerifyIL("Test<T>.Run", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (T V_0,
string V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0014
IL_0011: ldnull
IL_0012: br.s IL_0028
IL_0014: ldloca.s V_0
IL_0016: dup
IL_0017: initobj ""T""
IL_001d: constrained. ""T""
IL_0023: callvirt ""string object.ToString()""
IL_0028: stloc.1
IL_0029: br.s IL_002b
IL_002b: ldloc.1
IL_002c: ret
}");
}
[Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")]
public void ConditionalAccessOffOfUnconstrainedDefault2()
{
var source = @"
using System;
public class Test<T>
{
public string Run()
{
var v = default(T);
return v?.ToString();
}
}
class Program
{
static void Main()
{
Console.WriteLine(""--"");
Console.WriteLine(new Test<string>().Run());
Console.WriteLine(""--"");
Console.WriteLine(new Test<int>().Run());
Console.WriteLine(""--"");
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput:
@"--
--
0
--");
verifier.VerifyIL("Test<T>.Run", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init (T V_0, //v
string V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0014
IL_0011: ldnull
IL_0012: br.s IL_0021
IL_0014: ldloca.s V_0
IL_0016: constrained. ""T""
IL_001c: callvirt ""string object.ToString()""
IL_0021: stloc.1
IL_0022: br.s IL_0024
IL_0024: ldloc.1
IL_0025: ret
}");
}
[Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")]
public void ConditionalAccessOffOfInterfaceConstrainedDefault1()
{
var source = @"
using System;
public class Test<T> where T : IComparable
{
public string Run()
{
return default(T)?.ToString();
}
}
class Program
{
static void Main()
{
Console.WriteLine(""--"");
Console.WriteLine(new Test<string>().Run());
Console.WriteLine(""--"");
Console.WriteLine(new Test<int>().Run());
Console.WriteLine(""--"");
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput:
@"--
--
0
--");
verifier.VerifyIL("Test<T>.Run", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (T V_0,
string V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0014
IL_0011: ldnull
IL_0012: br.s IL_0028
IL_0014: ldloca.s V_0
IL_0016: dup
IL_0017: initobj ""T""
IL_001d: constrained. ""T""
IL_0023: callvirt ""string object.ToString()""
IL_0028: stloc.1
IL_0029: br.s IL_002b
IL_002b: ldloc.1
IL_002c: ret
}");
}
[Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")]
public void ConditionalAccessOffOfInterfaceConstrainedDefault2()
{
var source = @"
using System;
public class Test<T> where T : IComparable
{
public string Run()
{
var v = default(T);
return v?.ToString();
}
}
class Program
{
static void Main()
{
Console.WriteLine(""--"");
Console.WriteLine(new Test<string>().Run());
Console.WriteLine(""--"");
Console.WriteLine(new Test<int>().Run());
Console.WriteLine(""--"");
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput:
@"--
--
0
--");
verifier.VerifyIL("Test<T>.Run", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init (T V_0, //v
string V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0014
IL_0011: ldnull
IL_0012: br.s IL_0021
IL_0014: ldloca.s V_0
IL_0016: constrained. ""T""
IL_001c: callvirt ""string object.ToString()""
IL_0021: stloc.1
IL_0022: br.s IL_0024
IL_0024: ldloc.1
IL_0025: ret
}");
}
[Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")]
public void ConditionalAccessOffOfClassConstrainedDefault1()
{
var source = @"
using System;
public class Test<T> where T : class
{
public string Run()
{
return default(T)?.ToString();
}
}
class Program
{
static void Main()
{
Console.WriteLine(""--"");
Console.WriteLine(new Test<string>().Run());
Console.WriteLine(""--"");
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput:
@"--
--");
verifier.VerifyIL("Test<T>.Run", @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (string V_0)
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.0
IL_0003: br.s IL_0005
IL_0005: ldloc.0
IL_0006: ret
}");
}
[Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")]
public void ConditionalAccessOffOfClassConstrainedDefault2()
{
var source = @"
using System;
public class Test<T> where T : class
{
public string Run()
{
var v = default(T);
return v?.ToString();
}
}
class Program
{
static void Main()
{
Console.WriteLine(""--"");
Console.WriteLine(new Test<string>().Run());
Console.WriteLine(""--"");
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput:
@"--
--");
verifier.VerifyIL("Test<T>.Run", @"
{
// Code size 32 (0x20)
.maxstack 2
.locals init (T V_0, //v
string V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: dup
IL_0010: brtrue.s IL_0016
IL_0012: pop
IL_0013: ldnull
IL_0014: br.s IL_001b
IL_0016: callvirt ""string object.ToString()""
IL_001b: stloc.1
IL_001c: br.s IL_001e
IL_001e: ldloc.1
IL_001f: ret
}");
}
[Fact]
[CompilerTrait(CompilerFeature.PEVerifyCompat)]
public void ConditionalAccessOffReadOnlyNullable1()
{
var source = @"
using System;
class Program
{
private static readonly Guid? g = null;
static void Main()
{
Console.WriteLine(g?.ToString());
}
}
";
var comp = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"", verify: Verification.Fails);
comp.VerifyIL("Program.Main", @"
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (System.Guid V_0)
IL_0000: nop
IL_0001: ldsflda ""System.Guid? Program.g""
IL_0006: dup
IL_0007: call ""bool System.Guid?.HasValue.get""
IL_000c: brtrue.s IL_0012
IL_000e: pop
IL_000f: ldnull
IL_0010: br.s IL_0025
IL_0012: call ""System.Guid System.Guid?.GetValueOrDefault()""
IL_0017: stloc.0
IL_0018: ldloca.s V_0
IL_001a: constrained. ""System.Guid""
IL_0020: callvirt ""string object.ToString()""
IL_0025: call ""void System.Console.WriteLine(string)""
IL_002a: nop
IL_002b: ret
}");
comp = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes);
comp.VerifyIL("Program.Main", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (System.Guid? V_0,
System.Guid V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Guid? Program.g""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: dup
IL_000a: call ""bool System.Guid?.HasValue.get""
IL_000f: brtrue.s IL_0015
IL_0011: pop
IL_0012: ldnull
IL_0013: br.s IL_0028
IL_0015: call ""System.Guid System.Guid?.GetValueOrDefault()""
IL_001a: stloc.1
IL_001b: ldloca.s V_1
IL_001d: constrained. ""System.Guid""
IL_0023: callvirt ""string object.ToString()""
IL_0028: call ""void System.Console.WriteLine(string)""
IL_002d: nop
IL_002e: ret
}");
}
[Fact]
public void ConditionalAccessOffReadOnlyNullable2()
{
var source = @"
using System;
class Program
{
static void Main()
{
Console.WriteLine(default(Guid?)?.ToString());
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"");
verifier.VerifyIL("Program.Main", @"
{
// Code size 55 (0x37)
.maxstack 2
.locals init (System.Guid? V_0,
System.Guid V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: dup
IL_0004: initobj ""System.Guid?""
IL_000a: call ""bool System.Guid?.HasValue.get""
IL_000f: brtrue.s IL_0014
IL_0011: ldnull
IL_0012: br.s IL_0030
IL_0014: ldloca.s V_0
IL_0016: dup
IL_0017: initobj ""System.Guid?""
IL_001d: call ""System.Guid System.Guid?.GetValueOrDefault()""
IL_0022: stloc.1
IL_0023: ldloca.s V_1
IL_0025: constrained. ""System.Guid""
IL_002b: callvirt ""string object.ToString()""
IL_0030: call ""void System.Console.WriteLine(string)""
IL_0035: nop
IL_0036: ret
}");
}
[Fact]
[WorkItem(23351, "https://github.com/dotnet/roslyn/issues/23351")]
public void ConditionalAccessOffConstrainedTypeParameter_Property()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
var obj1 = new MyObject1 { MyDate = new DateTime(636461511000000000L) };
var obj2 = new MyObject2<MyObject1>(obj1);
System.Console.WriteLine(obj1.MyDate.Ticks);
System.Console.WriteLine(obj2.CurrentDate.Value.Ticks);
System.Console.WriteLine(new MyObject2<MyObject1>(null).CurrentDate.HasValue);
}
}
abstract class MyBaseObject1
{
public DateTime MyDate { get; set; }
}
class MyObject1 : MyBaseObject1
{ }
class MyObject2<MyObjectType> where MyObjectType : MyBaseObject1, new()
{
public MyObject2(MyObjectType obj)
{
m_CurrentObject1 = obj;
}
private MyObjectType m_CurrentObject1 = null;
public MyObjectType CurrentObject1 => m_CurrentObject1;
public DateTime? CurrentDate => CurrentObject1?.MyDate;
}
";
var expectedOutput =
@"
636461511000000000
636461511000000000
False
";
CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: expectedOutput);
CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(23351, "https://github.com/dotnet/roslyn/issues/23351")]
public void ConditionalAccessOffConstrainedTypeParameter_Field()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
var obj1 = new MyObject1 { MyDate = new DateTime(636461511000000000L) };
var obj2 = new MyObject2<MyObject1>(obj1);
System.Console.WriteLine(obj1.MyDate.Ticks);
System.Console.WriteLine(obj2.CurrentDate.Value.Ticks);
System.Console.WriteLine(new MyObject2<MyObject1>(null).CurrentDate.HasValue);
}
}
abstract class MyBaseObject1
{
public DateTime MyDate;
}
class MyObject1 : MyBaseObject1
{ }
class MyObject2<MyObjectType> where MyObjectType : MyBaseObject1, new()
{
public MyObject2(MyObjectType obj)
{
m_CurrentObject1 = obj;
}
private MyObjectType m_CurrentObject1 = null;
public MyObjectType CurrentObject1 => m_CurrentObject1;
public DateTime? CurrentDate => CurrentObject1?.MyDate;
}
";
var expectedOutput =
@"
636461511000000000
636461511000000000
False
";
CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: expectedOutput);
CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenShortCircuitOperatorTests : CSharpTestBase
{
[Fact]
public void TestShortCircuitAnd()
{
var source = @"
class C
{
public static bool Test(char ch, bool result)
{
System.Console.WriteLine(ch);
return result;
}
public static void Main()
{
const bool c1 = true;
const bool c2 = false;
bool v1 = true;
bool v2 = false;
System.Console.WriteLine(true && true);
System.Console.WriteLine(true && false);
System.Console.WriteLine(false && true);
System.Console.WriteLine(false && false);
System.Console.WriteLine(c1 && c1);
System.Console.WriteLine(c1 && c2);
System.Console.WriteLine(c2 && c1);
System.Console.WriteLine(c2 && c2);
System.Console.WriteLine(v1 && v1);
System.Console.WriteLine(v1 && v2);
System.Console.WriteLine(v2 && v1);
System.Console.WriteLine(v2 && v2);
System.Console.WriteLine(Test('L', true) && Test('R', true));
System.Console.WriteLine(Test('L', true) && Test('R', false));
System.Console.WriteLine(Test('L', false) && Test('R', true));
System.Console.WriteLine(Test('L', false) && Test('R', false));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
True
False
False
False
True
False
False
False
True
False
False
False
L
R
True
L
R
False
L
False
L
False
");
compilation.VerifyIL("C.Main", @"
{
// Code size 189 (0xbd)
.maxstack 2
.locals init (bool V_0, //v1
bool V_1) //v2
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: ldc.i4.1
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldc.i4.0
IL_000b: call ""void System.Console.WriteLine(bool)""
IL_0010: ldc.i4.0
IL_0011: call ""void System.Console.WriteLine(bool)""
IL_0016: ldc.i4.0
IL_0017: call ""void System.Console.WriteLine(bool)""
IL_001c: ldc.i4.1
IL_001d: call ""void System.Console.WriteLine(bool)""
IL_0022: ldc.i4.0
IL_0023: call ""void System.Console.WriteLine(bool)""
IL_0028: ldc.i4.0
IL_0029: call ""void System.Console.WriteLine(bool)""
IL_002e: ldc.i4.0
IL_002f: call ""void System.Console.WriteLine(bool)""
IL_0034: ldloc.0
IL_0035: ldloc.0
IL_0036: and
IL_0037: call ""void System.Console.WriteLine(bool)""
IL_003c: ldloc.0
IL_003d: ldloc.1
IL_003e: and
IL_003f: call ""void System.Console.WriteLine(bool)""
IL_0044: ldloc.1
IL_0045: ldloc.0
IL_0046: and
IL_0047: call ""void System.Console.WriteLine(bool)""
IL_004c: ldloc.1
IL_004d: ldloc.1
IL_004e: and
IL_004f: call ""void System.Console.WriteLine(bool)""
IL_0054: ldc.i4.s 76
IL_0056: ldc.i4.1
IL_0057: call ""bool C.Test(char, bool)""
IL_005c: brfalse.s IL_0068
IL_005e: ldc.i4.s 82
IL_0060: ldc.i4.1
IL_0061: call ""bool C.Test(char, bool)""
IL_0066: br.s IL_0069
IL_0068: ldc.i4.0
IL_0069: call ""void System.Console.WriteLine(bool)""
IL_006e: ldc.i4.s 76
IL_0070: ldc.i4.1
IL_0071: call ""bool C.Test(char, bool)""
IL_0076: brfalse.s IL_0082
IL_0078: ldc.i4.s 82
IL_007a: ldc.i4.0
IL_007b: call ""bool C.Test(char, bool)""
IL_0080: br.s IL_0083
IL_0082: ldc.i4.0
IL_0083: call ""void System.Console.WriteLine(bool)""
IL_0088: ldc.i4.s 76
IL_008a: ldc.i4.0
IL_008b: call ""bool C.Test(char, bool)""
IL_0090: brfalse.s IL_009c
IL_0092: ldc.i4.s 82
IL_0094: ldc.i4.1
IL_0095: call ""bool C.Test(char, bool)""
IL_009a: br.s IL_009d
IL_009c: ldc.i4.0
IL_009d: call ""void System.Console.WriteLine(bool)""
IL_00a2: ldc.i4.s 76
IL_00a4: ldc.i4.0
IL_00a5: call ""bool C.Test(char, bool)""
IL_00aa: brfalse.s IL_00b6
IL_00ac: ldc.i4.s 82
IL_00ae: ldc.i4.0
IL_00af: call ""bool C.Test(char, bool)""
IL_00b4: br.s IL_00b7
IL_00b6: ldc.i4.0
IL_00b7: call ""void System.Console.WriteLine(bool)""
IL_00bc: ret
}");
}
[Fact]
public void TestShortCircuitOr()
{
var source = @"
class C
{
public static bool Test(char ch, bool result)
{
System.Console.WriteLine(ch);
return result;
}
public static void Main()
{
const bool c1 = true;
const bool c2 = false;
bool v1 = true;
bool v2 = false;
System.Console.WriteLine(true || true);
System.Console.WriteLine(true || false);
System.Console.WriteLine(false || true);
System.Console.WriteLine(false || false);
System.Console.WriteLine(c1 || c1);
System.Console.WriteLine(c1 || c2);
System.Console.WriteLine(c2 || c1);
System.Console.WriteLine(c2 || c2);
System.Console.WriteLine(v1 || v1);
System.Console.WriteLine(v1 || v2);
System.Console.WriteLine(v2 || v1);
System.Console.WriteLine(v2 || v2);
System.Console.WriteLine(Test('L', true) || Test('R', true));
System.Console.WriteLine(Test('L', true) || Test('R', false));
System.Console.WriteLine(Test('L', false) || Test('R', true));
System.Console.WriteLine(Test('L', false) || Test('R', false));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
True
True
True
False
True
True
True
False
True
True
True
False
L
True
L
True
L
R
True
L
R
False
");
compilation.VerifyIL("C.Main", @"
{
// Code size 189 (0xbd)
.maxstack 2
.locals init (bool V_0, //v1
bool V_1) //v2
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: ldc.i4.1
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldc.i4.1
IL_000b: call ""void System.Console.WriteLine(bool)""
IL_0010: ldc.i4.1
IL_0011: call ""void System.Console.WriteLine(bool)""
IL_0016: ldc.i4.0
IL_0017: call ""void System.Console.WriteLine(bool)""
IL_001c: ldc.i4.1
IL_001d: call ""void System.Console.WriteLine(bool)""
IL_0022: ldc.i4.1
IL_0023: call ""void System.Console.WriteLine(bool)""
IL_0028: ldc.i4.1
IL_0029: call ""void System.Console.WriteLine(bool)""
IL_002e: ldc.i4.0
IL_002f: call ""void System.Console.WriteLine(bool)""
IL_0034: ldloc.0
IL_0035: ldloc.0
IL_0036: or
IL_0037: call ""void System.Console.WriteLine(bool)""
IL_003c: ldloc.0
IL_003d: ldloc.1
IL_003e: or
IL_003f: call ""void System.Console.WriteLine(bool)""
IL_0044: ldloc.1
IL_0045: ldloc.0
IL_0046: or
IL_0047: call ""void System.Console.WriteLine(bool)""
IL_004c: ldloc.1
IL_004d: ldloc.1
IL_004e: or
IL_004f: call ""void System.Console.WriteLine(bool)""
IL_0054: ldc.i4.s 76
IL_0056: ldc.i4.1
IL_0057: call ""bool C.Test(char, bool)""
IL_005c: brtrue.s IL_0068
IL_005e: ldc.i4.s 82
IL_0060: ldc.i4.1
IL_0061: call ""bool C.Test(char, bool)""
IL_0066: br.s IL_0069
IL_0068: ldc.i4.1
IL_0069: call ""void System.Console.WriteLine(bool)""
IL_006e: ldc.i4.s 76
IL_0070: ldc.i4.1
IL_0071: call ""bool C.Test(char, bool)""
IL_0076: brtrue.s IL_0082
IL_0078: ldc.i4.s 82
IL_007a: ldc.i4.0
IL_007b: call ""bool C.Test(char, bool)""
IL_0080: br.s IL_0083
IL_0082: ldc.i4.1
IL_0083: call ""void System.Console.WriteLine(bool)""
IL_0088: ldc.i4.s 76
IL_008a: ldc.i4.0
IL_008b: call ""bool C.Test(char, bool)""
IL_0090: brtrue.s IL_009c
IL_0092: ldc.i4.s 82
IL_0094: ldc.i4.1
IL_0095: call ""bool C.Test(char, bool)""
IL_009a: br.s IL_009d
IL_009c: ldc.i4.1
IL_009d: call ""void System.Console.WriteLine(bool)""
IL_00a2: ldc.i4.s 76
IL_00a4: ldc.i4.0
IL_00a5: call ""bool C.Test(char, bool)""
IL_00aa: brtrue.s IL_00b6
IL_00ac: ldc.i4.s 82
IL_00ae: ldc.i4.0
IL_00af: call ""bool C.Test(char, bool)""
IL_00b4: br.s IL_00b7
IL_00b6: ldc.i4.1
IL_00b7: call ""void System.Console.WriteLine(bool)""
IL_00bc: ret
}");
}
[Fact]
public void TestChainedShortCircuitOperators()
{
var source = @"
class C
{
public static bool Test(char ch, bool result)
{
System.Console.WriteLine(ch);
return result;
}
public static void Main()
{
// AND AND
System.Console.WriteLine(Test('A', true) && Test('B', true) && Test('C' , true));
System.Console.WriteLine(Test('A', true) && Test('B', true) && Test('C' , false));
System.Console.WriteLine(Test('A', true) && Test('B', false) && Test('C' , true));
System.Console.WriteLine(Test('A', true) && Test('B', false) && Test('C' , false));
System.Console.WriteLine(Test('A', false) && Test('B', true) && Test('C' , true));
System.Console.WriteLine(Test('A', false) && Test('B', true) && Test('C' , false));
System.Console.WriteLine(Test('A', false) && Test('B', false) && Test('C' , true));
System.Console.WriteLine(Test('A', false) && Test('B', false) && Test('C' , false));
// AND OR
System.Console.WriteLine(Test('A', true) && Test('B', true) || Test('C' , true));
System.Console.WriteLine(Test('A', true) && Test('B', true) || Test('C' , false));
System.Console.WriteLine(Test('A', true) && Test('B', false) || Test('C' , true));
System.Console.WriteLine(Test('A', true) && Test('B', false) || Test('C' , false));
System.Console.WriteLine(Test('A', false) && Test('B', true) || Test('C' , true));
System.Console.WriteLine(Test('A', false) && Test('B', true) || Test('C' , false));
System.Console.WriteLine(Test('A', false) && Test('B', false) || Test('C' , true));
System.Console.WriteLine(Test('A', false) && Test('B', false) || Test('C' , false));
// OR AND
System.Console.WriteLine(Test('A', true) || Test('B', true) && Test('C' , true));
System.Console.WriteLine(Test('A', true) || Test('B', true) && Test('C' , false));
System.Console.WriteLine(Test('A', true) || Test('B', false) && Test('C' , true));
System.Console.WriteLine(Test('A', true) || Test('B', false) && Test('C' , false));
System.Console.WriteLine(Test('A', false) || Test('B', true) && Test('C' , true));
System.Console.WriteLine(Test('A', false) || Test('B', true) && Test('C' , false));
System.Console.WriteLine(Test('A', false) || Test('B', false) && Test('C' , true));
System.Console.WriteLine(Test('A', false) || Test('B', false) && Test('C' , false));
// OR OR
System.Console.WriteLine(Test('A', true) || Test('B', true) || Test('C' , true));
System.Console.WriteLine(Test('A', true) || Test('B', true) || Test('C' , false));
System.Console.WriteLine(Test('A', true) || Test('B', false) || Test('C' , true));
System.Console.WriteLine(Test('A', true) || Test('B', false) || Test('C' , false));
System.Console.WriteLine(Test('A', false) || Test('B', true) || Test('C' , true));
System.Console.WriteLine(Test('A', false) || Test('B', true) || Test('C' , false));
System.Console.WriteLine(Test('A', false) || Test('B', false) || Test('C' , true));
System.Console.WriteLine(Test('A', false) || Test('B', false) || Test('C' , false));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
A
B
C
True
A
B
C
False
A
B
False
A
B
False
A
False
A
False
A
False
A
False
A
B
True
A
B
True
A
B
C
True
A
B
C
False
A
C
True
A
C
False
A
C
True
A
C
False
A
True
A
True
A
True
A
True
A
B
C
True
A
B
C
False
A
B
False
A
B
False
A
True
A
True
A
True
A
True
A
B
True
A
B
True
A
B
C
True
A
B
C
False
");
compilation.VerifyIL("C.Main", @"{
// Code size 1177 (0x499)
.maxstack 2
IL_0000: ldc.i4.s 65
IL_0002: ldc.i4.1
IL_0003: call ""bool C.Test(char, bool)""
IL_0008: brfalse.s IL_001e
IL_000a: ldc.i4.s 66
IL_000c: ldc.i4.1
IL_000d: call ""bool C.Test(char, bool)""
IL_0012: brfalse.s IL_001e
IL_0014: ldc.i4.s 67
IL_0016: ldc.i4.1
IL_0017: call ""bool C.Test(char, bool)""
IL_001c: br.s IL_001f
IL_001e: ldc.i4.0
IL_001f: call ""void System.Console.WriteLine(bool)""
IL_0024: ldc.i4.s 65
IL_0026: ldc.i4.1
IL_0027: call ""bool C.Test(char, bool)""
IL_002c: brfalse.s IL_0042
IL_002e: ldc.i4.s 66
IL_0030: ldc.i4.1
IL_0031: call ""bool C.Test(char, bool)""
IL_0036: brfalse.s IL_0042
IL_0038: ldc.i4.s 67
IL_003a: ldc.i4.0
IL_003b: call ""bool C.Test(char, bool)""
IL_0040: br.s IL_0043
IL_0042: ldc.i4.0
IL_0043: call ""void System.Console.WriteLine(bool)""
IL_0048: ldc.i4.s 65
IL_004a: ldc.i4.1
IL_004b: call ""bool C.Test(char, bool)""
IL_0050: brfalse.s IL_0066
IL_0052: ldc.i4.s 66
IL_0054: ldc.i4.0
IL_0055: call ""bool C.Test(char, bool)""
IL_005a: brfalse.s IL_0066
IL_005c: ldc.i4.s 67
IL_005e: ldc.i4.1
IL_005f: call ""bool C.Test(char, bool)""
IL_0064: br.s IL_0067
IL_0066: ldc.i4.0
IL_0067: call ""void System.Console.WriteLine(bool)""
IL_006c: ldc.i4.s 65
IL_006e: ldc.i4.1
IL_006f: call ""bool C.Test(char, bool)""
IL_0074: brfalse.s IL_008a
IL_0076: ldc.i4.s 66
IL_0078: ldc.i4.0
IL_0079: call ""bool C.Test(char, bool)""
IL_007e: brfalse.s IL_008a
IL_0080: ldc.i4.s 67
IL_0082: ldc.i4.0
IL_0083: call ""bool C.Test(char, bool)""
IL_0088: br.s IL_008b
IL_008a: ldc.i4.0
IL_008b: call ""void System.Console.WriteLine(bool)""
IL_0090: ldc.i4.s 65
IL_0092: ldc.i4.0
IL_0093: call ""bool C.Test(char, bool)""
IL_0098: brfalse.s IL_00ae
IL_009a: ldc.i4.s 66
IL_009c: ldc.i4.1
IL_009d: call ""bool C.Test(char, bool)""
IL_00a2: brfalse.s IL_00ae
IL_00a4: ldc.i4.s 67
IL_00a6: ldc.i4.1
IL_00a7: call ""bool C.Test(char, bool)""
IL_00ac: br.s IL_00af
IL_00ae: ldc.i4.0
IL_00af: call ""void System.Console.WriteLine(bool)""
IL_00b4: ldc.i4.s 65
IL_00b6: ldc.i4.0
IL_00b7: call ""bool C.Test(char, bool)""
IL_00bc: brfalse.s IL_00d2
IL_00be: ldc.i4.s 66
IL_00c0: ldc.i4.1
IL_00c1: call ""bool C.Test(char, bool)""
IL_00c6: brfalse.s IL_00d2
IL_00c8: ldc.i4.s 67
IL_00ca: ldc.i4.0
IL_00cb: call ""bool C.Test(char, bool)""
IL_00d0: br.s IL_00d3
IL_00d2: ldc.i4.0
IL_00d3: call ""void System.Console.WriteLine(bool)""
IL_00d8: ldc.i4.s 65
IL_00da: ldc.i4.0
IL_00db: call ""bool C.Test(char, bool)""
IL_00e0: brfalse.s IL_00f6
IL_00e2: ldc.i4.s 66
IL_00e4: ldc.i4.0
IL_00e5: call ""bool C.Test(char, bool)""
IL_00ea: brfalse.s IL_00f6
IL_00ec: ldc.i4.s 67
IL_00ee: ldc.i4.1
IL_00ef: call ""bool C.Test(char, bool)""
IL_00f4: br.s IL_00f7
IL_00f6: ldc.i4.0
IL_00f7: call ""void System.Console.WriteLine(bool)""
IL_00fc: ldc.i4.s 65
IL_00fe: ldc.i4.0
IL_00ff: call ""bool C.Test(char, bool)""
IL_0104: brfalse.s IL_011a
IL_0106: ldc.i4.s 66
IL_0108: ldc.i4.0
IL_0109: call ""bool C.Test(char, bool)""
IL_010e: brfalse.s IL_011a
IL_0110: ldc.i4.s 67
IL_0112: ldc.i4.0
IL_0113: call ""bool C.Test(char, bool)""
IL_0118: br.s IL_011b
IL_011a: ldc.i4.0
IL_011b: call ""void System.Console.WriteLine(bool)""
IL_0120: ldc.i4.s 65
IL_0122: ldc.i4.1
IL_0123: call ""bool C.Test(char, bool)""
IL_0128: brfalse.s IL_0134
IL_012a: ldc.i4.s 66
IL_012c: ldc.i4.1
IL_012d: call ""bool C.Test(char, bool)""
IL_0132: brtrue.s IL_013e
IL_0134: ldc.i4.s 67
IL_0136: ldc.i4.1
IL_0137: call ""bool C.Test(char, bool)""
IL_013c: br.s IL_013f
IL_013e: ldc.i4.1
IL_013f: call ""void System.Console.WriteLine(bool)""
IL_0144: ldc.i4.s 65
IL_0146: ldc.i4.1
IL_0147: call ""bool C.Test(char, bool)""
IL_014c: brfalse.s IL_0158
IL_014e: ldc.i4.s 66
IL_0150: ldc.i4.1
IL_0151: call ""bool C.Test(char, bool)""
IL_0156: brtrue.s IL_0162
IL_0158: ldc.i4.s 67
IL_015a: ldc.i4.0
IL_015b: call ""bool C.Test(char, bool)""
IL_0160: br.s IL_0163
IL_0162: ldc.i4.1
IL_0163: call ""void System.Console.WriteLine(bool)""
IL_0168: ldc.i4.s 65
IL_016a: ldc.i4.1
IL_016b: call ""bool C.Test(char, bool)""
IL_0170: brfalse.s IL_017c
IL_0172: ldc.i4.s 66
IL_0174: ldc.i4.0
IL_0175: call ""bool C.Test(char, bool)""
IL_017a: brtrue.s IL_0186
IL_017c: ldc.i4.s 67
IL_017e: ldc.i4.1
IL_017f: call ""bool C.Test(char, bool)""
IL_0184: br.s IL_0187
IL_0186: ldc.i4.1
IL_0187: call ""void System.Console.WriteLine(bool)""
IL_018c: ldc.i4.s 65
IL_018e: ldc.i4.1
IL_018f: call ""bool C.Test(char, bool)""
IL_0194: brfalse.s IL_01a0
IL_0196: ldc.i4.s 66
IL_0198: ldc.i4.0
IL_0199: call ""bool C.Test(char, bool)""
IL_019e: brtrue.s IL_01aa
IL_01a0: ldc.i4.s 67
IL_01a2: ldc.i4.0
IL_01a3: call ""bool C.Test(char, bool)""
IL_01a8: br.s IL_01ab
IL_01aa: ldc.i4.1
IL_01ab: call ""void System.Console.WriteLine(bool)""
IL_01b0: ldc.i4.s 65
IL_01b2: ldc.i4.0
IL_01b3: call ""bool C.Test(char, bool)""
IL_01b8: brfalse.s IL_01c4
IL_01ba: ldc.i4.s 66
IL_01bc: ldc.i4.1
IL_01bd: call ""bool C.Test(char, bool)""
IL_01c2: brtrue.s IL_01ce
IL_01c4: ldc.i4.s 67
IL_01c6: ldc.i4.1
IL_01c7: call ""bool C.Test(char, bool)""
IL_01cc: br.s IL_01cf
IL_01ce: ldc.i4.1
IL_01cf: call ""void System.Console.WriteLine(bool)""
IL_01d4: ldc.i4.s 65
IL_01d6: ldc.i4.0
IL_01d7: call ""bool C.Test(char, bool)""
IL_01dc: brfalse.s IL_01e8
IL_01de: ldc.i4.s 66
IL_01e0: ldc.i4.1
IL_01e1: call ""bool C.Test(char, bool)""
IL_01e6: brtrue.s IL_01f2
IL_01e8: ldc.i4.s 67
IL_01ea: ldc.i4.0
IL_01eb: call ""bool C.Test(char, bool)""
IL_01f0: br.s IL_01f3
IL_01f2: ldc.i4.1
IL_01f3: call ""void System.Console.WriteLine(bool)""
IL_01f8: ldc.i4.s 65
IL_01fa: ldc.i4.0
IL_01fb: call ""bool C.Test(char, bool)""
IL_0200: brfalse.s IL_020c
IL_0202: ldc.i4.s 66
IL_0204: ldc.i4.0
IL_0205: call ""bool C.Test(char, bool)""
IL_020a: brtrue.s IL_0216
IL_020c: ldc.i4.s 67
IL_020e: ldc.i4.1
IL_020f: call ""bool C.Test(char, bool)""
IL_0214: br.s IL_0217
IL_0216: ldc.i4.1
IL_0217: call ""void System.Console.WriteLine(bool)""
IL_021c: ldc.i4.s 65
IL_021e: ldc.i4.0
IL_021f: call ""bool C.Test(char, bool)""
IL_0224: brfalse.s IL_0230
IL_0226: ldc.i4.s 66
IL_0228: ldc.i4.0
IL_0229: call ""bool C.Test(char, bool)""
IL_022e: brtrue.s IL_023a
IL_0230: ldc.i4.s 67
IL_0232: ldc.i4.0
IL_0233: call ""bool C.Test(char, bool)""
IL_0238: br.s IL_023b
IL_023a: ldc.i4.1
IL_023b: call ""void System.Console.WriteLine(bool)""
IL_0240: ldc.i4.s 65
IL_0242: ldc.i4.1
IL_0243: call ""bool C.Test(char, bool)""
IL_0248: brtrue.s IL_0261
IL_024a: ldc.i4.s 66
IL_024c: ldc.i4.1
IL_024d: call ""bool C.Test(char, bool)""
IL_0252: brfalse.s IL_025e
IL_0254: ldc.i4.s 67
IL_0256: ldc.i4.1
IL_0257: call ""bool C.Test(char, bool)""
IL_025c: br.s IL_0262
IL_025e: ldc.i4.0
IL_025f: br.s IL_0262
IL_0261: ldc.i4.1
IL_0262: call ""void System.Console.WriteLine(bool)""
IL_0267: ldc.i4.s 65
IL_0269: ldc.i4.1
IL_026a: call ""bool C.Test(char, bool)""
IL_026f: brtrue.s IL_0288
IL_0271: ldc.i4.s 66
IL_0273: ldc.i4.1
IL_0274: call ""bool C.Test(char, bool)""
IL_0279: brfalse.s IL_0285
IL_027b: ldc.i4.s 67
IL_027d: ldc.i4.0
IL_027e: call ""bool C.Test(char, bool)""
IL_0283: br.s IL_0289
IL_0285: ldc.i4.0
IL_0286: br.s IL_0289
IL_0288: ldc.i4.1
IL_0289: call ""void System.Console.WriteLine(bool)""
IL_028e: ldc.i4.s 65
IL_0290: ldc.i4.1
IL_0291: call ""bool C.Test(char, bool)""
IL_0296: brtrue.s IL_02af
IL_0298: ldc.i4.s 66
IL_029a: ldc.i4.0
IL_029b: call ""bool C.Test(char, bool)""
IL_02a0: brfalse.s IL_02ac
IL_02a2: ldc.i4.s 67
IL_02a4: ldc.i4.1
IL_02a5: call ""bool C.Test(char, bool)""
IL_02aa: br.s IL_02b0
IL_02ac: ldc.i4.0
IL_02ad: br.s IL_02b0
IL_02af: ldc.i4.1
IL_02b0: call ""void System.Console.WriteLine(bool)""
IL_02b5: ldc.i4.s 65
IL_02b7: ldc.i4.1
IL_02b8: call ""bool C.Test(char, bool)""
IL_02bd: brtrue.s IL_02d6
IL_02bf: ldc.i4.s 66
IL_02c1: ldc.i4.0
IL_02c2: call ""bool C.Test(char, bool)""
IL_02c7: brfalse.s IL_02d3
IL_02c9: ldc.i4.s 67
IL_02cb: ldc.i4.0
IL_02cc: call ""bool C.Test(char, bool)""
IL_02d1: br.s IL_02d7
IL_02d3: ldc.i4.0
IL_02d4: br.s IL_02d7
IL_02d6: ldc.i4.1
IL_02d7: call ""void System.Console.WriteLine(bool)""
IL_02dc: ldc.i4.s 65
IL_02de: ldc.i4.0
IL_02df: call ""bool C.Test(char, bool)""
IL_02e4: brtrue.s IL_02fd
IL_02e6: ldc.i4.s 66
IL_02e8: ldc.i4.1
IL_02e9: call ""bool C.Test(char, bool)""
IL_02ee: brfalse.s IL_02fa
IL_02f0: ldc.i4.s 67
IL_02f2: ldc.i4.1
IL_02f3: call ""bool C.Test(char, bool)""
IL_02f8: br.s IL_02fe
IL_02fa: ldc.i4.0
IL_02fb: br.s IL_02fe
IL_02fd: ldc.i4.1
IL_02fe: call ""void System.Console.WriteLine(bool)""
IL_0303: ldc.i4.s 65
IL_0305: ldc.i4.0
IL_0306: call ""bool C.Test(char, bool)""
IL_030b: brtrue.s IL_0324
IL_030d: ldc.i4.s 66
IL_030f: ldc.i4.1
IL_0310: call ""bool C.Test(char, bool)""
IL_0315: brfalse.s IL_0321
IL_0317: ldc.i4.s 67
IL_0319: ldc.i4.0
IL_031a: call ""bool C.Test(char, bool)""
IL_031f: br.s IL_0325
IL_0321: ldc.i4.0
IL_0322: br.s IL_0325
IL_0324: ldc.i4.1
IL_0325: call ""void System.Console.WriteLine(bool)""
IL_032a: ldc.i4.s 65
IL_032c: ldc.i4.0
IL_032d: call ""bool C.Test(char, bool)""
IL_0332: brtrue.s IL_034b
IL_0334: ldc.i4.s 66
IL_0336: ldc.i4.0
IL_0337: call ""bool C.Test(char, bool)""
IL_033c: brfalse.s IL_0348
IL_033e: ldc.i4.s 67
IL_0340: ldc.i4.1
IL_0341: call ""bool C.Test(char, bool)""
IL_0346: br.s IL_034c
IL_0348: ldc.i4.0
IL_0349: br.s IL_034c
IL_034b: ldc.i4.1
IL_034c: call ""void System.Console.WriteLine(bool)""
IL_0351: ldc.i4.s 65
IL_0353: ldc.i4.0
IL_0354: call ""bool C.Test(char, bool)""
IL_0359: brtrue.s IL_0372
IL_035b: ldc.i4.s 66
IL_035d: ldc.i4.0
IL_035e: call ""bool C.Test(char, bool)""
IL_0363: brfalse.s IL_036f
IL_0365: ldc.i4.s 67
IL_0367: ldc.i4.0
IL_0368: call ""bool C.Test(char, bool)""
IL_036d: br.s IL_0373
IL_036f: ldc.i4.0
IL_0370: br.s IL_0373
IL_0372: ldc.i4.1
IL_0373: call ""void System.Console.WriteLine(bool)""
IL_0378: ldc.i4.s 65
IL_037a: ldc.i4.1
IL_037b: call ""bool C.Test(char, bool)""
IL_0380: brtrue.s IL_0396
IL_0382: ldc.i4.s 66
IL_0384: ldc.i4.1
IL_0385: call ""bool C.Test(char, bool)""
IL_038a: brtrue.s IL_0396
IL_038c: ldc.i4.s 67
IL_038e: ldc.i4.1
IL_038f: call ""bool C.Test(char, bool)""
IL_0394: br.s IL_0397
IL_0396: ldc.i4.1
IL_0397: call ""void System.Console.WriteLine(bool)""
IL_039c: ldc.i4.s 65
IL_039e: ldc.i4.1
IL_039f: call ""bool C.Test(char, bool)""
IL_03a4: brtrue.s IL_03ba
IL_03a6: ldc.i4.s 66
IL_03a8: ldc.i4.1
IL_03a9: call ""bool C.Test(char, bool)""
IL_03ae: brtrue.s IL_03ba
IL_03b0: ldc.i4.s 67
IL_03b2: ldc.i4.0
IL_03b3: call ""bool C.Test(char, bool)""
IL_03b8: br.s IL_03bb
IL_03ba: ldc.i4.1
IL_03bb: call ""void System.Console.WriteLine(bool)""
IL_03c0: ldc.i4.s 65
IL_03c2: ldc.i4.1
IL_03c3: call ""bool C.Test(char, bool)""
IL_03c8: brtrue.s IL_03de
IL_03ca: ldc.i4.s 66
IL_03cc: ldc.i4.0
IL_03cd: call ""bool C.Test(char, bool)""
IL_03d2: brtrue.s IL_03de
IL_03d4: ldc.i4.s 67
IL_03d6: ldc.i4.1
IL_03d7: call ""bool C.Test(char, bool)""
IL_03dc: br.s IL_03df
IL_03de: ldc.i4.1
IL_03df: call ""void System.Console.WriteLine(bool)""
IL_03e4: ldc.i4.s 65
IL_03e6: ldc.i4.1
IL_03e7: call ""bool C.Test(char, bool)""
IL_03ec: brtrue.s IL_0402
IL_03ee: ldc.i4.s 66
IL_03f0: ldc.i4.0
IL_03f1: call ""bool C.Test(char, bool)""
IL_03f6: brtrue.s IL_0402
IL_03f8: ldc.i4.s 67
IL_03fa: ldc.i4.0
IL_03fb: call ""bool C.Test(char, bool)""
IL_0400: br.s IL_0403
IL_0402: ldc.i4.1
IL_0403: call ""void System.Console.WriteLine(bool)""
IL_0408: ldc.i4.s 65
IL_040a: ldc.i4.0
IL_040b: call ""bool C.Test(char, bool)""
IL_0410: brtrue.s IL_0426
IL_0412: ldc.i4.s 66
IL_0414: ldc.i4.1
IL_0415: call ""bool C.Test(char, bool)""
IL_041a: brtrue.s IL_0426
IL_041c: ldc.i4.s 67
IL_041e: ldc.i4.1
IL_041f: call ""bool C.Test(char, bool)""
IL_0424: br.s IL_0427
IL_0426: ldc.i4.1
IL_0427: call ""void System.Console.WriteLine(bool)""
IL_042c: ldc.i4.s 65
IL_042e: ldc.i4.0
IL_042f: call ""bool C.Test(char, bool)""
IL_0434: brtrue.s IL_044a
IL_0436: ldc.i4.s 66
IL_0438: ldc.i4.1
IL_0439: call ""bool C.Test(char, bool)""
IL_043e: brtrue.s IL_044a
IL_0440: ldc.i4.s 67
IL_0442: ldc.i4.0
IL_0443: call ""bool C.Test(char, bool)""
IL_0448: br.s IL_044b
IL_044a: ldc.i4.1
IL_044b: call ""void System.Console.WriteLine(bool)""
IL_0450: ldc.i4.s 65
IL_0452: ldc.i4.0
IL_0453: call ""bool C.Test(char, bool)""
IL_0458: brtrue.s IL_046e
IL_045a: ldc.i4.s 66
IL_045c: ldc.i4.0
IL_045d: call ""bool C.Test(char, bool)""
IL_0462: brtrue.s IL_046e
IL_0464: ldc.i4.s 67
IL_0466: ldc.i4.1
IL_0467: call ""bool C.Test(char, bool)""
IL_046c: br.s IL_046f
IL_046e: ldc.i4.1
IL_046f: call ""void System.Console.WriteLine(bool)""
IL_0474: ldc.i4.s 65
IL_0476: ldc.i4.0
IL_0477: call ""bool C.Test(char, bool)""
IL_047c: brtrue.s IL_0492
IL_047e: ldc.i4.s 66
IL_0480: ldc.i4.0
IL_0481: call ""bool C.Test(char, bool)""
IL_0486: brtrue.s IL_0492
IL_0488: ldc.i4.s 67
IL_048a: ldc.i4.0
IL_048b: call ""bool C.Test(char, bool)""
IL_0490: br.s IL_0493
IL_0492: ldc.i4.1
IL_0493: call ""void System.Console.WriteLine(bool)""
IL_0498: ret
}
");
}
[Fact]
public void TestConditionalMemberAccess001()
{
var source = @"
public class C
{
static void Main()
{
Test(null);
System.Console.Write('#');
int[] a = new int[] { };
Test(a);
}
static void Test(int[] x)
{
System.Console.Write(x?.ToString().ToString().ToString() ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, expectedOutput: "NULL#System.Int32[]");
comp.VerifyIL("C.Test", @"
{
// Code size 37 (0x25)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0006
IL_0003: ldnull
IL_0004: br.s IL_0016
IL_0006: ldarg.0
IL_0007: callvirt ""string object.ToString()""
IL_000c: callvirt ""string object.ToString()""
IL_0011: callvirt ""string object.ToString()""
IL_0016: dup
IL_0017: brtrue.s IL_001f
IL_0019: pop
IL_001a: ldstr ""NULL""
IL_001f: call ""void System.Console.Write(string)""
IL_0024: ret
}
");
}
[Fact]
public void TestConditionalMemberAccess001ext()
{
var source = @"
public static class C
{
static void Main()
{
Test(null);
System.Console.Write('#');
int[] a = new int[] { };
Test(a);
}
static void Test(int[] x)
{
System.Console.Write(x?.ToStr().ToStr().ToStr() ?? ""NULL"");
}
static string ToStr(this object arg)
{
return arg.ToString();
}
}";
var comp = CompileAndVerify(source, expectedOutput: "NULL#System.Int32[]");
comp.VerifyIL("C.Test", @"
{
// Code size 37 (0x25)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0006
IL_0003: ldnull
IL_0004: br.s IL_0016
IL_0006: ldarg.0
IL_0007: call ""string C.ToStr(object)""
IL_000c: call ""string C.ToStr(object)""
IL_0011: call ""string C.ToStr(object)""
IL_0016: dup
IL_0017: brtrue.s IL_001f
IL_0019: pop
IL_001a: ldstr ""NULL""
IL_001f: call ""void System.Console.Write(string)""
IL_0024: ret
}
");
}
[Fact]
public void TestConditionalMemberAccess001dyn()
{
var source = @"
public static class C
{
static void Main()
{
Test(null);
System.Console.Write('#');
int[] a = new int[] { };
Test(a);
}
static void Test(dynamic x)
{
System.Console.Write(x?.ToString().ToString()?.ToString() ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#System.Int32[]");
comp.VerifyIL("C.Test", @"
{
// Code size 355 (0x163)
.maxstack 14
.locals init (object V_0,
object V_1)
IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3""
IL_0005: brtrue.s IL_0046
IL_0007: ldc.i4 0x100
IL_000c: ldstr ""Write""
IL_0011: ldnull
IL_0012: ldtoken ""C""
IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001c: ldc.i4.2
IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0022: dup
IL_0023: ldc.i4.0
IL_0024: ldc.i4.s 33
IL_0026: ldnull
IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002c: stelem.ref
IL_002d: dup
IL_002e: ldc.i4.1
IL_002f: ldc.i4.0
IL_0030: ldnull
IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0036: stelem.ref
IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3""
IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3""
IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target""
IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3""
IL_0055: ldtoken ""System.Console""
IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_005f: ldarg.0
IL_0060: stloc.0
IL_0061: ldloc.0
IL_0062: brtrue.s IL_006a
IL_0064: ldnull
IL_0065: br IL_0154
IL_006a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1""
IL_006f: brtrue.s IL_00a1
IL_0071: ldc.i4.0
IL_0072: ldstr ""ToString""
IL_0077: ldnull
IL_0078: ldtoken ""C""
IL_007d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0082: ldc.i4.1
IL_0083: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0088: dup
IL_0089: ldc.i4.0
IL_008a: ldc.i4.0
IL_008b: ldnull
IL_008c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0091: stelem.ref
IL_0092: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0097: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_009c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1""
IL_00a1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1""
IL_00a6: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target""
IL_00ab: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1""
IL_00b0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0""
IL_00b5: brtrue.s IL_00e7
IL_00b7: ldc.i4.0
IL_00b8: ldstr ""ToString""
IL_00bd: ldnull
IL_00be: ldtoken ""C""
IL_00c3: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_00c8: ldc.i4.1
IL_00c9: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_00ce: dup
IL_00cf: ldc.i4.0
IL_00d0: ldc.i4.0
IL_00d1: ldnull
IL_00d2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_00d7: stelem.ref
IL_00d8: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_00dd: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_00e2: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0""
IL_00e7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0""
IL_00ec: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target""
IL_00f1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0""
IL_00f6: ldloc.0
IL_00f7: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_00fc: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_0101: stloc.1
IL_0102: ldloc.1
IL_0103: brtrue.s IL_0108
IL_0105: ldnull
IL_0106: br.s IL_0154
IL_0108: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2""
IL_010d: brtrue.s IL_013f
IL_010f: ldc.i4.0
IL_0110: ldstr ""ToString""
IL_0115: ldnull
IL_0116: ldtoken ""C""
IL_011b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0120: ldc.i4.1
IL_0121: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0126: dup
IL_0127: ldc.i4.0
IL_0128: ldc.i4.0
IL_0129: ldnull
IL_012a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_012f: stelem.ref
IL_0130: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0135: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_013a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2""
IL_013f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2""
IL_0144: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target""
IL_0149: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2""
IL_014e: ldloc.1
IL_014f: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_0154: dup
IL_0155: brtrue.s IL_015d
IL_0157: pop
IL_0158: ldstr ""NULL""
IL_015d: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)""
IL_0162: ret
}
");
}
[Fact]
public void TestConditionalMemberAccess001dyn1()
{
var source = @"
public static class C
{
static void Main()
{
Test(null);
System.Console.Write('#');
int[] a = new int[] { };
Test(a);
}
static void Test(dynamic x)
{
System.Console.Write(x?.ToString()?[1].ToString() ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#y");
}
[Fact]
public void TestConditionalMemberAccess001dyn2()
{
var source = @"
public static class C
{
static void Main()
{
Test(null, ""aa"");
System.Console.Write('#');
Test(""aa"", ""bb"");
}
static void Test(string s, dynamic ds)
{
System.Console.Write(s?.CompareTo(ds) ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#-1");
}
[Fact]
public void TestConditionalMemberAccess001dyn3()
{
var source = @"
public static class C
{
static void Main()
{
Test(null, 1);
System.Console.Write('#');
int[] a = new int[] { };
Test(a, 1);
}
static void Test(int[] x, dynamic i)
{
System.Console.Write(x?.ToString()?[i].ToString() ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#y");
}
[Fact]
public void TestConditionalMemberAccess001dyn4()
{
var source = @"
public static class C
{
static void Main()
{
Test(null);
System.Console.Write('#');
int[] a = new int[] {1,2,3};
Test(a);
}
static void Test(dynamic x)
{
System.Console.Write(x?.Length.ToString() ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#3");
}
[Fact]
public void TestConditionalMemberAccess001dyn5()
{
var source = @"
public static class C
{
static void Main()
{
Test(null);
System.Console.Write('#');
int[] a = new int[] {1,2,3};
Test(a);
}
static void Test(dynamic x)
{
System.Console.Write(x?.Length?.ToString() ?? ""NULL"");
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#3");
}
[Fact]
public void TestConditionalMemberAccessUnused()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString();
var dummy2 = ""qqq""?.ToString();
var dummy3 = 1.ToString()?.ToString();
}
}";
var comp = CompileAndVerify(source, expectedOutput: "");
comp.VerifyIL("C.Main", @"
{
// Code size 32 (0x20)
.maxstack 2
.locals init (int V_0)
IL_0000: ldstr ""qqq""
IL_0005: callvirt ""string object.ToString()""
IL_000a: pop
IL_000b: ldc.i4.1
IL_000c: stloc.0
IL_000d: ldloca.s V_0
IL_000f: call ""string int.ToString()""
IL_0014: dup
IL_0015: brtrue.s IL_0019
IL_0017: pop
IL_0018: ret
IL_0019: callvirt ""string object.ToString()""
IL_001e: pop
IL_001f: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUsed()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString();
var dummy2 = ""qqq""?.ToString();
var dummy3 = 1.ToString()?.ToString();
dummy1 += dummy2 += dummy3;
}
}";
var comp = CompileAndVerify(source, expectedOutput: "");
comp.VerifyIL("C.Main", @"
{
// Code size 50 (0x32)
.maxstack 3
.locals init (string V_0, //dummy2
string V_1, //dummy3
int V_2)
IL_0000: ldnull
IL_0001: ldstr ""qqq""
IL_0006: callvirt ""string object.ToString()""
IL_000b: stloc.0
IL_000c: ldc.i4.1
IL_000d: stloc.2
IL_000e: ldloca.s V_2
IL_0010: call ""string int.ToString()""
IL_0015: dup
IL_0016: brtrue.s IL_001c
IL_0018: pop
IL_0019: ldnull
IL_001a: br.s IL_0021
IL_001c: callvirt ""string object.ToString()""
IL_0021: stloc.1
IL_0022: ldloc.0
IL_0023: ldloc.1
IL_0024: call ""string string.Concat(string, string)""
IL_0029: dup
IL_002a: stloc.0
IL_002b: call ""string string.Concat(string, string)""
IL_0030: pop
IL_0031: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUnused1()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString().Length;
var dummy2 = ""qqq""?.ToString().Length;
var dummy3 = 1.ToString()?.ToString().Length;
}
}";
var comp = CompileAndVerify(source, expectedOutput: "");
comp.VerifyIL("C.Main", @"
{
// Code size 42 (0x2a)
.maxstack 2
.locals init (int V_0)
IL_0000: ldstr ""qqq""
IL_0005: callvirt ""string object.ToString()""
IL_000a: callvirt ""int string.Length.get""
IL_000f: pop
IL_0010: ldc.i4.1
IL_0011: stloc.0
IL_0012: ldloca.s V_0
IL_0014: call ""string int.ToString()""
IL_0019: dup
IL_001a: brtrue.s IL_001e
IL_001c: pop
IL_001d: ret
IL_001e: callvirt ""string object.ToString()""
IL_0023: callvirt ""int string.Length.get""
IL_0028: pop
IL_0029: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUsed1()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString().Length;
System.Console.WriteLine(dummy1);
var dummy2 = ""qqq""?.ToString().Length;
System.Console.WriteLine(dummy2);
var dummy3 = 1.ToString()?.ToString().Length;
System.Console.WriteLine(dummy3);
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"3
1");
comp.VerifyIL("C.Main", @"
{
// Code size 99 (0x63)
.maxstack 2
.locals init (int? V_0,
int V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""int?""
IL_0008: ldloc.0
IL_0009: box ""int?""
IL_000e: call ""void System.Console.WriteLine(object)""
IL_0013: ldstr ""qqq""
IL_0018: callvirt ""string object.ToString()""
IL_001d: callvirt ""int string.Length.get""
IL_0022: newobj ""int?..ctor(int)""
IL_0027: box ""int?""
IL_002c: call ""void System.Console.WriteLine(object)""
IL_0031: ldc.i4.1
IL_0032: stloc.1
IL_0033: ldloca.s V_1
IL_0035: call ""string int.ToString()""
IL_003a: dup
IL_003b: brtrue.s IL_0049
IL_003d: pop
IL_003e: ldloca.s V_0
IL_0040: initobj ""int?""
IL_0046: ldloc.0
IL_0047: br.s IL_0058
IL_0049: callvirt ""string object.ToString()""
IL_004e: callvirt ""int string.Length.get""
IL_0053: newobj ""int?..ctor(int)""
IL_0058: box ""int?""
IL_005d: call ""void System.Console.WriteLine(object)""
IL_0062: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUnused2()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString().NullableLength()?.ToString();
var dummy2 = ""qqq""?.ToString().NullableLength().ToString();
var dummy3 = 1.ToString()?.ToString().NullableLength()?.ToString();
}
}
public static class C1
{
public static int? NullableLength(this string self)
{
return self.Length;
}
}
";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "");
comp.VerifyIL("C.Main", @"
{
// Code size 82 (0x52)
.maxstack 2
.locals init (int? V_0,
int V_1)
IL_0000: ldstr ""qqq""
IL_0005: callvirt ""string object.ToString()""
IL_000a: call ""int? C1.NullableLength(string)""
IL_000f: stloc.0
IL_0010: ldloca.s V_0
IL_0012: constrained. ""int?""
IL_0018: callvirt ""string object.ToString()""
IL_001d: pop
IL_001e: ldc.i4.1
IL_001f: stloc.1
IL_0020: ldloca.s V_1
IL_0022: call ""string int.ToString()""
IL_0027: dup
IL_0028: brtrue.s IL_002c
IL_002a: pop
IL_002b: ret
IL_002c: callvirt ""string object.ToString()""
IL_0031: call ""int? C1.NullableLength(string)""
IL_0036: stloc.0
IL_0037: ldloca.s V_0
IL_0039: dup
IL_003a: call ""bool int?.HasValue.get""
IL_003f: brtrue.s IL_0043
IL_0041: pop
IL_0042: ret
IL_0043: call ""int int?.GetValueOrDefault()""
IL_0048: stloc.1
IL_0049: ldloca.s V_1
IL_004b: call ""string int.ToString()""
IL_0050: pop
IL_0051: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUnused2a()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString()?.Length.ToString();
var dummy2 = ""qqq""?.ToString().Length.ToString();
var dummy3 = 1.ToString()?.ToString().Length.ToString();
}
}";
var comp = CompileAndVerify(source, expectedOutput: "");
comp.VerifyIL("C.Main", @"
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (int V_0)
IL_0000: ldstr ""qqq""
IL_0005: callvirt ""string object.ToString()""
IL_000a: callvirt ""int string.Length.get""
IL_000f: stloc.0
IL_0010: ldloca.s V_0
IL_0012: call ""string int.ToString()""
IL_0017: pop
IL_0018: ldc.i4.1
IL_0019: stloc.0
IL_001a: ldloca.s V_0
IL_001c: call ""string int.ToString()""
IL_0021: dup
IL_0022: brtrue.s IL_0026
IL_0024: pop
IL_0025: ret
IL_0026: callvirt ""string object.ToString()""
IL_002b: callvirt ""int string.Length.get""
IL_0030: stloc.0
IL_0031: ldloca.s V_0
IL_0033: call ""string int.ToString()""
IL_0038: pop
IL_0039: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUsed2()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString().NullableLength()?.ToString();
System.Console.WriteLine(dummy1);
var dummy2 = ""qqq""?.ToString().NullableLength()?.ToString();
System.Console.WriteLine(dummy2);
var dummy3 = 1.ToString()?.ToString().NullableLength()?.ToString();
System.Console.WriteLine(dummy3);
}
}
public static class C1
{
public static int? NullableLength(this string self)
{
return self.Length;
}
}";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"3
1");
comp.VerifyIL("C.Main", @"
{
// Code size 114 (0x72)
.maxstack 2
.locals init (int? V_0,
int V_1)
IL_0000: ldnull
IL_0001: call ""void System.Console.WriteLine(string)""
IL_0006: ldstr ""qqq""
IL_000b: callvirt ""string object.ToString()""
IL_0010: call ""int? C1.NullableLength(string)""
IL_0015: stloc.0
IL_0016: ldloca.s V_0
IL_0018: dup
IL_0019: call ""bool int?.HasValue.get""
IL_001e: brtrue.s IL_0024
IL_0020: pop
IL_0021: ldnull
IL_0022: br.s IL_0031
IL_0024: call ""int int?.GetValueOrDefault()""
IL_0029: stloc.1
IL_002a: ldloca.s V_1
IL_002c: call ""string int.ToString()""
IL_0031: call ""void System.Console.WriteLine(string)""
IL_0036: ldc.i4.1
IL_0037: stloc.1
IL_0038: ldloca.s V_1
IL_003a: call ""string int.ToString()""
IL_003f: dup
IL_0040: brtrue.s IL_0046
IL_0042: pop
IL_0043: ldnull
IL_0044: br.s IL_006c
IL_0046: callvirt ""string object.ToString()""
IL_004b: call ""int? C1.NullableLength(string)""
IL_0050: stloc.0
IL_0051: ldloca.s V_0
IL_0053: dup
IL_0054: call ""bool int?.HasValue.get""
IL_0059: brtrue.s IL_005f
IL_005b: pop
IL_005c: ldnull
IL_005d: br.s IL_006c
IL_005f: call ""int int?.GetValueOrDefault()""
IL_0064: stloc.1
IL_0065: ldloca.s V_1
IL_0067: call ""string int.ToString()""
IL_006c: call ""void System.Console.WriteLine(string)""
IL_0071: ret
}
");
}
[Fact]
public void TestConditionalMemberAccessUsed2a()
{
var source = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString()?.Length.ToString();
System.Console.WriteLine(dummy1);
var dummy2 = ""qqq""?.ToString()?.Length.ToString();
System.Console.WriteLine(dummy2);
var dummy3 = 1.ToString()?.ToString()?.Length.ToString();
System.Console.WriteLine(dummy3);
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"3
1");
comp.VerifyIL("C.Main", @"
{
// Code size 88 (0x58)
.maxstack 2
.locals init (int V_0)
IL_0000: ldnull
IL_0001: call ""void System.Console.WriteLine(string)""
IL_0006: ldstr ""qqq""
IL_000b: callvirt ""string object.ToString()""
IL_0010: dup
IL_0011: brtrue.s IL_0017
IL_0013: pop
IL_0014: ldnull
IL_0015: br.s IL_0024
IL_0017: call ""int string.Length.get""
IL_001c: stloc.0
IL_001d: ldloca.s V_0
IL_001f: call ""string int.ToString()""
IL_0024: call ""void System.Console.WriteLine(string)""
IL_0029: ldc.i4.1
IL_002a: stloc.0
IL_002b: ldloca.s V_0
IL_002d: call ""string int.ToString()""
IL_0032: dup
IL_0033: brtrue.s IL_0039
IL_0035: pop
IL_0036: ldnull
IL_0037: br.s IL_0052
IL_0039: callvirt ""string object.ToString()""
IL_003e: dup
IL_003f: brtrue.s IL_0045
IL_0041: pop
IL_0042: ldnull
IL_0043: br.s IL_0052
IL_0045: call ""int string.Length.get""
IL_004a: stloc.0
IL_004b: ldloca.s V_0
IL_004d: call ""string int.ToString()""
IL_0052: call ""void System.Console.WriteLine(string)""
IL_0057: ret
}
");
}
[Fact]
[WorkItem(976765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/976765")]
public void ConditionalMemberAccessConstrained()
{
var source = @"
class Program
{
static void M<T>(T x) where T: System.Exception
{
object s = x?.ToString();
System.Console.WriteLine(s);
s = x?.GetType();
System.Console.WriteLine(s);
}
static void Main()
{
M(new System.Exception(""a""));
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"System.Exception: a
System.Exception");
comp.VerifyIL("Program.M<T>", @"
{
// Code size 47 (0x2f)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: dup
IL_0007: brtrue.s IL_000d
IL_0009: pop
IL_000a: ldnull
IL_000b: br.s IL_0012
IL_000d: callvirt ""string object.ToString()""
IL_0012: call ""void System.Console.WriteLine(object)""
IL_0017: ldarg.0
IL_0018: box ""T""
IL_001d: dup
IL_001e: brtrue.s IL_0024
IL_0020: pop
IL_0021: ldnull
IL_0022: br.s IL_0029
IL_0024: callvirt ""System.Type System.Exception.GetType()""
IL_0029: call ""void System.Console.WriteLine(object)""
IL_002e: ret
}
");
}
[Fact]
[WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")]
public void ConditionalMemberAccessStatement()
{
var source = @"
class Program
{
class C1
{
public void Print0()
{
System.Console.WriteLine(""print0"");
}
public int Print1()
{
System.Console.WriteLine(""print1"");
return 1;
}
public object Print2()
{
System.Console.WriteLine(""print2"");
return 1;
}
}
static void M(C1 x)
{
x?.Print0();
x?.Print1();
x?.Print2();
}
static void Main()
{
M(null);
M(new C1());
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"print0
print1
print2");
comp.VerifyIL("Program.M(Program.C1)", @"
{
// Code size 30 (0x1e)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0009
IL_0003: ldarg.0
IL_0004: call ""void Program.C1.Print0()""
IL_0009: ldarg.0
IL_000a: brfalse.s IL_0013
IL_000c: ldarg.0
IL_000d: call ""int Program.C1.Print1()""
IL_0012: pop
IL_0013: ldarg.0
IL_0014: brfalse.s IL_001d
IL_0016: ldarg.0
IL_0017: call ""object Program.C1.Print2()""
IL_001c: pop
IL_001d: ret
}
");
}
[Fact]
[WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")]
public void ConditionalMemberAccessStatement01()
{
var source = @"
class Program
{
struct S1
{
public void Print0()
{
System.Console.WriteLine(""print0"");
}
public int Print1()
{
System.Console.WriteLine(""print1"");
return 1;
}
public object Print2()
{
System.Console.WriteLine(""print2"");
return 1;
}
}
static void M(S1? x)
{
x?.Print0();
x?.Print1();
x?.Print2()?.ToString().ToString()?.ToString();
}
static void Main()
{
M(null);
M(new S1());
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"print0
print1
print2");
comp.VerifyIL("Program.M(Program.S1?)", @"
{
// Code size 100 (0x64)
.maxstack 2
.locals init (Program.S1 V_0)
IL_0000: ldarga.s V_0
IL_0002: call ""bool Program.S1?.HasValue.get""
IL_0007: brfalse.s IL_0018
IL_0009: ldarga.s V_0
IL_000b: call ""Program.S1 Program.S1?.GetValueOrDefault()""
IL_0010: stloc.0
IL_0011: ldloca.s V_0
IL_0013: call ""void Program.S1.Print0()""
IL_0018: ldarga.s V_0
IL_001a: call ""bool Program.S1?.HasValue.get""
IL_001f: brfalse.s IL_0031
IL_0021: ldarga.s V_0
IL_0023: call ""Program.S1 Program.S1?.GetValueOrDefault()""
IL_0028: stloc.0
IL_0029: ldloca.s V_0
IL_002b: call ""int Program.S1.Print1()""
IL_0030: pop
IL_0031: ldarga.s V_0
IL_0033: call ""bool Program.S1?.HasValue.get""
IL_0038: brfalse.s IL_0063
IL_003a: ldarga.s V_0
IL_003c: call ""Program.S1 Program.S1?.GetValueOrDefault()""
IL_0041: stloc.0
IL_0042: ldloca.s V_0
IL_0044: call ""object Program.S1.Print2()""
IL_0049: dup
IL_004a: brtrue.s IL_004e
IL_004c: pop
IL_004d: ret
IL_004e: callvirt ""string object.ToString()""
IL_0053: callvirt ""string object.ToString()""
IL_0058: dup
IL_0059: brtrue.s IL_005d
IL_005b: pop
IL_005c: ret
IL_005d: callvirt ""string object.ToString()""
IL_0062: pop
IL_0063: ret
}
");
}
[ConditionalFact(typeof(DesktopOnly))]
[WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")]
public void ConditionalMemberAccessStatement02()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
class C1
{
public void Print0(int i)
{
System.Console.WriteLine(""print0"");
}
public int Print1(int i)
{
System.Console.WriteLine(""print1"");
return 1;
}
public object Print2(int i)
{
System.Console.WriteLine(""print2"");
return 1;
}
}
static async Task<int> Val()
{
await Task.Yield();
return 1;
}
static async Task<int> M(C1 x)
{
x?.Print0(await Val());
x?.Print1(await Val());
x?.Print2(await Val());
return 1;
}
static void Main()
{
M(null).Wait();
M(new C1()).Wait();
}
}
";
var comp = CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: @"print0
print1
print2");
}
[ConditionalFact(typeof(DesktopOnly))]
[WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")]
public void ConditionalMemberAccessStatement03()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
struct C1
{
public void Print0(int i)
{
System.Console.WriteLine(""print0"");
}
public int Print1(int i)
{
System.Console.WriteLine(""print1"");
return 1;
}
public object Print2(int i)
{
System.Console.WriteLine(""print2"");
return 1;
}
}
static async Task<int> Val()
{
await Task.Yield();
return 1;
}
static async Task<int> M(C1? x)
{
x?.Print0(await Val());
x?.Print1(await Val());
x?.Print2(await Val());
return 1;
}
static void Main()
{
M(null).Wait();
M(new C1()).Wait();
}
}
";
var comp = CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: @"print0
print1
print2");
}
[Fact]
public void ConditionalMemberAccessUnConstrained()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
class C1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(ref c, ref c);
S1 s = new S1();
Test(ref s, ref s);
}
static void Test<T>(ref T x, ref T y) where T : IDisposable
{
x?.Dispose();
y?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True
False
True");
comp.VerifyIL("Program.Test<T>(ref T, ref T)", @"
{
// Code size 94 (0x5e)
.maxstack 2
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0024
IL_0011: ldobj ""T""
IL_0016: stloc.0
IL_0017: ldloca.s V_0
IL_0019: ldloc.0
IL_001a: box ""T""
IL_001f: brtrue.s IL_0024
IL_0021: pop
IL_0022: br.s IL_002f
IL_0024: constrained. ""T""
IL_002a: callvirt ""void System.IDisposable.Dispose()""
IL_002f: ldarg.1
IL_0030: ldloca.s V_0
IL_0032: initobj ""T""
IL_0038: ldloc.0
IL_0039: box ""T""
IL_003e: brtrue.s IL_0052
IL_0040: ldobj ""T""
IL_0045: stloc.0
IL_0046: ldloca.s V_0
IL_0048: ldloc.0
IL_0049: box ""T""
IL_004e: brtrue.s IL_0052
IL_0050: pop
IL_0051: ret
IL_0052: constrained. ""T""
IL_0058: callvirt ""void System.IDisposable.Dispose()""
IL_005d: ret
}");
}
[Fact]
public void ConditionalMemberAccessUnConstrained1()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
class C1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
var c = new C1[] {new C1()};
Test(c, c);
var s = new S1[] {new S1()};
Test(s, s);
}
static void Test<T>(T[] x, T[] y) where T : IDisposable
{
x[0]?.Dispose();
y[0]?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True
False
True");
comp.VerifyIL("Program.Test<T>(T[], T[])", @"
{
// Code size 110 (0x6e)
.maxstack 2
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: readonly.
IL_0004: ldelema ""T""
IL_0009: ldloca.s V_0
IL_000b: initobj ""T""
IL_0011: ldloc.0
IL_0012: box ""T""
IL_0017: brtrue.s IL_002c
IL_0019: ldobj ""T""
IL_001e: stloc.0
IL_001f: ldloca.s V_0
IL_0021: ldloc.0
IL_0022: box ""T""
IL_0027: brtrue.s IL_002c
IL_0029: pop
IL_002a: br.s IL_0037
IL_002c: constrained. ""T""
IL_0032: callvirt ""void System.IDisposable.Dispose()""
IL_0037: ldarg.1
IL_0038: ldc.i4.0
IL_0039: readonly.
IL_003b: ldelema ""T""
IL_0040: ldloca.s V_0
IL_0042: initobj ""T""
IL_0048: ldloc.0
IL_0049: box ""T""
IL_004e: brtrue.s IL_0062
IL_0050: ldobj ""T""
IL_0055: stloc.0
IL_0056: ldloca.s V_0
IL_0058: ldloc.0
IL_0059: box ""T""
IL_005e: brtrue.s IL_0062
IL_0060: pop
IL_0061: ret
IL_0062: constrained. ""T""
IL_0068: callvirt ""void System.IDisposable.Dispose()""
IL_006d: ret
}
");
}
[Fact]
public void ConditionalMemberAccessConstrained1()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
class C1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
var c = new C1[] {new C1()};
Test(c, c);
}
static void Test<T>(T[] x, T[] y) where T : class, IDisposable
{
x[0]?.Dispose();
y[0]?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True
");
comp.VerifyIL("Program.Test<T>(T[], T[])", @"
{
// Code size 46 (0x2e)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelem ""T""
IL_0007: box ""T""
IL_000c: dup
IL_000d: brtrue.s IL_0012
IL_000f: pop
IL_0010: br.s IL_0017
IL_0012: callvirt ""void System.IDisposable.Dispose()""
IL_0017: ldarg.1
IL_0018: ldc.i4.0
IL_0019: ldelem ""T""
IL_001e: box ""T""
IL_0023: dup
IL_0024: brtrue.s IL_0028
IL_0026: pop
IL_0027: ret
IL_0028: callvirt ""void System.IDisposable.Dispose()""
IL_002d: ret
}
");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedVal()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
class C1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(c);
S1 s = new S1();
Test(s);
}
static void Test<T>(T x) where T : IDisposable
{
x?.Dispose();
x?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True
False
True");
comp.VerifyIL("Program.Test<T>(T)", @"
{
// Code size 43 (0x2b)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: brfalse.s IL_0015
IL_0008: ldarga.s V_0
IL_000a: constrained. ""T""
IL_0010: callvirt ""void System.IDisposable.Dispose()""
IL_0015: ldarg.0
IL_0016: box ""T""
IL_001b: brfalse.s IL_002a
IL_001d: ldarga.s V_0
IL_001f: constrained. ""T""
IL_0025: callvirt ""void System.IDisposable.Dispose()""
IL_002a: ret
}
");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedVal001()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
class C1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(() => c);
S1 s = new S1();
Test(() => s);
}
static void Test<T>(Func<T> x) where T : IDisposable
{
x()?.Dispose();
x()?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True
False
False");
comp.VerifyIL("Program.Test<T>(System.Func<T>)", @"
{
// Code size 72 (0x48)
.maxstack 2
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: callvirt ""T System.Func<T>.Invoke()""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: dup
IL_000a: ldobj ""T""
IL_000f: box ""T""
IL_0014: brtrue.s IL_0019
IL_0016: pop
IL_0017: br.s IL_0024
IL_0019: constrained. ""T""
IL_001f: callvirt ""void System.IDisposable.Dispose()""
IL_0024: ldarg.0
IL_0025: callvirt ""T System.Func<T>.Invoke()""
IL_002a: stloc.0
IL_002b: ldloca.s V_0
IL_002d: dup
IL_002e: ldobj ""T""
IL_0033: box ""T""
IL_0038: brtrue.s IL_003c
IL_003a: pop
IL_003b: ret
IL_003c: constrained. ""T""
IL_0042: callvirt ""void System.IDisposable.Dispose()""
IL_0047: ret
}
");
}
[Fact]
public void ConditionalMemberAccessConstrainedVal001()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
class C1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable
{
private bool disposed;
public void Dispose()
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(() => c);
}
static void Test<T>(Func<T> x) where T : class, IDisposable
{
x()?.Dispose();
x()?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True");
comp.VerifyIL("Program.Test<T>(System.Func<T>)", @"
{
// Code size 44 (0x2c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: callvirt ""T System.Func<T>.Invoke()""
IL_0006: box ""T""
IL_000b: dup
IL_000c: brtrue.s IL_0011
IL_000e: pop
IL_000f: br.s IL_0016
IL_0011: callvirt ""void System.IDisposable.Dispose()""
IL_0016: ldarg.0
IL_0017: callvirt ""T System.Func<T>.Invoke()""
IL_001c: box ""T""
IL_0021: dup
IL_0022: brtrue.s IL_0026
IL_0024: pop
IL_0025: ret
IL_0026: callvirt ""void System.IDisposable.Dispose()""
IL_002b: ret
}
");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedDyn()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
interface IDisposable1
{
void Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public void Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable1
{
private bool disposed;
public void Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(ref c, ref c);
S1 s = new S1();
Test(ref s, ref s);
}
static void Test<T>(ref T x, ref T y) where T : IDisposable1
{
dynamic d = 1;
x?.Dispose(d);
y?.Dispose(d);
}
}
";
var comp = CompileAndVerify(source, references: new MetadataReference[] { CSharpRef }, expectedOutput: @"False
True
False
False");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedDynVal()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
interface IDisposable1
{
void Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public void Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable1
{
private bool disposed;
public void Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(c, c);
S1 s = new S1();
Test(s, s);
}
static void Test<T>(T x, T y) where T : IDisposable1
{
dynamic d = 1;
x?.Dispose(d);
y?.Dispose(d);
}
}
";
var comp = CompileAndVerify(source, references: new MetadataReference[] { CSharpRef }, expectedOutput: @"False
True
False
False");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedAsync()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
interface IDisposable1
{
void Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public void Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
struct S1 : IDisposable1
{
private bool disposed;
public void Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
}
}
static void Main(string[] args)
{
C1[] c = new C1[] { new C1() };
Test(c, c).Wait();
S1[] s = new S1[] { new S1() };
Test(s, s).Wait();
}
static async Task<int> Val()
{
await Task.Yield();
return 0;
}
static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1
{
x[0]?.Dispose(await Val());
y[0]?.Dispose(await Val());
return 1;
}
}";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True
False
True");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedAsyncVal()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
interface IDisposable1
{
int Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public int Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
return 1;
}
}
struct S1 : IDisposable1
{
private bool disposed;
public int Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
return 1;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(c, c).Wait();
S1 s = new S1();
Test(s, s).Wait();
}
static async Task<int> Val()
{
await Task.Yield();
return 0;
}
static async Task<int> Test<T>(T x, T y) where T : IDisposable1
{
x?.Dispose(await Val());
y?.Dispose(await Val());
return 1;
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True
False
False");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedAsyncValExt()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DE;
namespace DE
{
public static class IDispExt
{
public static void DisposeExt(this Program.IDisposable1 d, int i)
{
d.Dispose(i);
}
}
}
public class Program
{
public interface IDisposable1
{
int Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public int Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
return 1;
}
}
struct S1 : IDisposable1
{
private bool disposed;
public int Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed = true;
return 1;
}
}
static void Main(string[] args)
{
C1 c = new C1();
Test(c, c).Wait();
S1 s = new S1();
Test(s, s).Wait();
}
static async Task<int> Val()
{
await Task.Yield();
return 0;
}
static async Task<int> Test<T>(T x, T y) where T : IDisposable1
{
x?.DisposeExt(await Val());
y?.DisposeExt(await Val());
return 1;
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True
False
False");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedAsyncNested()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
interface IDisposable1
{
IDisposable1 Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public IDisposable1 Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed ^= true;
return this;
}
}
struct S1 : IDisposable1
{
private bool disposed;
public IDisposable1 Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed ^= true;
return this;
}
}
static void Main(string[] args)
{
C1[] c = new C1[] { new C1() };
Test(c, c).Wait();
System.Console.WriteLine();
S1[] s = new S1[] { new S1() };
Test(s, s).Wait();
}
static async Task<int> Val()
{
await Task.Yield();
return 0;
}
static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1
{
x[0]?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val());
y[0]?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val());
return 1;
}
}";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True
False
True
False
True
False
True
False
True
False
True
True
False
True
False");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedAsyncNestedArr()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
interface IDisposable1
{
IDisposable1[] Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public IDisposable1[] Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed ^= true;
return new IDisposable1[] { this };
}
}
struct S1 : IDisposable1
{
private bool disposed;
public IDisposable1[] Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed ^= true;
return new IDisposable1[]{this};
}
}
static void Main(string[] args)
{
C1[] c = new C1[] { new C1() };
Test(c, c).Wait();
System.Console.WriteLine();
S1[] s = new S1[] { new S1() };
Test(s, s).Wait();
}
static async Task<int> Val()
{
await Task.Yield();
return 0;
}
static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1
{
x[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val());
y[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val());
return 1;
}
}";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True
False
True
False
True
False
True
False
True
False
True
True
False
True
False");
}
[Fact]
public void ConditionalMemberAccessUnConstrainedAsyncSuperNested()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
interface IDisposable1
{
Task<int> Dispose(int i);
}
class C1 : IDisposable1
{
private bool disposed;
public Task<int> Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed ^= true;
return Task.FromResult(i);
}
}
struct S1 : IDisposable1
{
private bool disposed;
public Task<int> Dispose(int i)
{
System.Console.WriteLine(disposed);
disposed ^= true;
return Task.FromResult(i);
}
}
static void Main(string[] args)
{
C1[] c = new C1[] { new C1() };
Test(c, c).Wait();
System.Console.WriteLine();
S1[] s = new S1[] { new S1() };
Test(s, s).Wait();
}
static async Task<int> Val()
{
await Task.Yield();
return 0;
}
static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1
{
x[0]?.Dispose(await x[0]?.Dispose(await x[0]?.Dispose(await x[0]?.Dispose(await Val()))));
y[0]?.Dispose(await y[0]?.Dispose(await y[0]?.Dispose(await y[0]?.Dispose(await Val()))));
return 1;
}
}";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True
False
True
False
True
False
True
False
True
False
True
False
True
False
True");
}
[Fact]
public void ConditionalExtensionAccessGeneric001()
{
var source = @"
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
long? x = 1;
Test0(x);
return;
}
static void Test0<T>(T x)
{
x?.CheckT();
}
}
static class Ext
{
public static void CheckT<T>(this T x)
{
System.Console.WriteLine(typeof(T));
return;
}
}
";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"System.Nullable`1[System.Int64]");
comp.VerifyIL("Test.Test0<T>(T)", @"
{
// Code size 21 (0x15)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: brfalse.s IL_0014
IL_0008: ldarga.s V_0
IL_000a: ldobj ""T""
IL_000f: call ""void Ext.CheckT<T>(T)""
IL_0014: ret
}
");
}
[Fact]
public void ConditionalExtensionAccessGeneric002()
{
var source = @"
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
long? x = 1;
Test0(ref x);
return;
}
static void Test0<T>(ref T x)
{
x?.CheckT();
}
}
static class Ext
{
public static void CheckT<T>(this T x)
{
System.Console.WriteLine(typeof(T));
return;
}
}
";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"System.Nullable`1[System.Int64]");
comp.VerifyIL("Test.Test0<T>(ref T)", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0023
IL_0011: ldobj ""T""
IL_0016: stloc.0
IL_0017: ldloca.s V_0
IL_0019: ldloc.0
IL_001a: box ""T""
IL_001f: brtrue.s IL_0023
IL_0021: pop
IL_0022: ret
IL_0023: ldobj ""T""
IL_0028: call ""void Ext.CheckT<T>(T)""
IL_002d: ret
}
");
}
[Fact]
public void ConditionalExtensionAccessGeneric003()
{
var source = @"
using System;
using System.Linq;
using System.Collections.Generic;
class Test
{
static void Main()
{
Test0(""qqq"");
}
static void Test0<T>(T x) where T:IEnumerable<char>
{
x?.Count();
}
static void Test1<T>(ref T x) where T:IEnumerable<char>
{
x?.Count();
}
}
";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"");
comp.VerifyIL("Test.Test0<T>(T)", @"
{
// Code size 27 (0x1b)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: brfalse.s IL_001a
IL_0008: ldarga.s V_0
IL_000a: ldobj ""T""
IL_000f: box ""T""
IL_0014: call ""int System.Linq.Enumerable.Count<char>(System.Collections.Generic.IEnumerable<char>)""
IL_0019: pop
IL_001a: ret
}
").VerifyIL("Test.Test1<T>(ref T)", @"
{
// Code size 52 (0x34)
.maxstack 2
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0023
IL_0011: ldobj ""T""
IL_0016: stloc.0
IL_0017: ldloca.s V_0
IL_0019: ldloc.0
IL_001a: box ""T""
IL_001f: brtrue.s IL_0023
IL_0021: pop
IL_0022: ret
IL_0023: ldobj ""T""
IL_0028: box ""T""
IL_002d: call ""int System.Linq.Enumerable.Count<char>(System.Collections.Generic.IEnumerable<char>)""
IL_0032: pop
IL_0033: ret
}
");
}
[Fact]
public void ConditionalExtensionAccessGenericAsync001()
{
var source = @"
using System.Threading.Tasks;
class Test
{
static void Main()
{
}
async Task<int?> TestAsync<T>(T[] x) where T : I1
{
return x[0]?.CallAsync(await PassAsync());
}
static async Task<int> PassAsync()
{
await Task.Yield();
return 1;
}
}
interface I1
{
int CallAsync(int x);
}
";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { CSharpRef });
base.CompileAndVerify(comp);
}
[Fact]
public void ConditionalExtensionAccessGenericAsyncNullable001()
{
var source = @"
using System;
using System.Threading.Tasks;
class Test
{
static void Main()
{
var arr = new S1?[] { new S1(), new S1()};
TestAsync(arr).Wait();
System.Console.WriteLine(arr[1].Value.called);
}
static async Task<int?> TestAsync<T>(T?[] x)
where T : struct, I1
{
return x[await PassAsync()]?.CallAsync(await PassAsync());
}
static async Task<int> PassAsync()
{
await Task.Yield();
return 1;
}
}
struct S1 : I1
{
public int called;
public int CallAsync(int x)
{
called++;
System.Console.Write(called + 41);
return called;
}
}
interface I1
{
int CallAsync(int x);
}
";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { CSharpRef }, options: TestOptions.ReleaseExe);
base.CompileAndVerify(comp, expectedOutput: "420");
}
[Fact]
public void ConditionalMemberAccessCoalesce001()
{
var source = @"
class Program
{
class C1
{
public int x{get; set;}
public int? y{get; set;}
}
static void Main()
{
var c = new C1();
System.Console.WriteLine(Test1(c));
System.Console.WriteLine(Test1(null));
System.Console.WriteLine(Test2(c));
System.Console.WriteLine(Test2(null));
}
static int Test1(C1 c)
{
return c?.x ?? 42;
}
static int Test2(C1 c)
{
return c?.y ?? 42;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"0
42
42
42");
comp.VerifyIL("Program.Test1(Program.C1)", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0006
IL_0003: ldc.i4.s 42
IL_0005: ret
IL_0006: ldarg.0
IL_0007: call ""int Program.C1.x.get""
IL_000c: ret
}
").VerifyIL("Program.Test2(Program.C1)", @"
{
// Code size 41 (0x29)
.maxstack 1
.locals init (int? V_0,
int? V_1)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000e
IL_0003: ldloca.s V_1
IL_0005: initobj ""int?""
IL_000b: ldloc.1
IL_000c: br.s IL_0014
IL_000e: ldarg.0
IL_000f: call ""int? Program.C1.y.get""
IL_0014: stloc.0
IL_0015: ldloca.s V_0
IL_0017: call ""bool int?.HasValue.get""
IL_001c: brtrue.s IL_0021
IL_001e: ldc.i4.s 42
IL_0020: ret
IL_0021: ldloca.s V_0
IL_0023: call ""int int?.GetValueOrDefault()""
IL_0028: ret
}
");
}
[Fact]
public void ConditionalMemberAccessCoalesce001n()
{
var source = @"
class Program
{
class C1
{
public int x{get; set;}
public int? y{get; set;}
}
static void Main()
{
var c = new C1();
System.Console.WriteLine(Test1(c));
System.Console.WriteLine(Test1(null));
System.Console.WriteLine(Test2(c));
System.Console.WriteLine(Test2(null));
}
static int? Test1(C1 c)
{
return c?.x ?? (int?)42;
}
static int? Test2(C1 c)
{
return c?.y ?? (int?)42;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"0
42
42
42");
comp.VerifyIL("Program.Test1(Program.C1)", @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000b
IL_0003: ldc.i4.s 42
IL_0005: newobj ""int?..ctor(int)""
IL_000a: ret
IL_000b: ldarg.0
IL_000c: call ""int Program.C1.x.get""
IL_0011: newobj ""int?..ctor(int)""
IL_0016: ret
}
").VerifyIL("Program.Test2(Program.C1)", @"
{
// Code size 40 (0x28)
.maxstack 1
.locals init (int? V_0,
int? V_1)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000e
IL_0003: ldloca.s V_1
IL_0005: initobj ""int?""
IL_000b: ldloc.1
IL_000c: br.s IL_0014
IL_000e: ldarg.0
IL_000f: call ""int? Program.C1.y.get""
IL_0014: stloc.0
IL_0015: ldloca.s V_0
IL_0017: call ""bool int?.HasValue.get""
IL_001c: brtrue.s IL_0026
IL_001e: ldc.i4.s 42
IL_0020: newobj ""int?..ctor(int)""
IL_0025: ret
IL_0026: ldloc.0
IL_0027: ret
}");
}
[Fact]
public void ConditionalMemberAccessCoalesce001r()
{
var source = @"
class Program
{
class C1
{
public int x {get; set;}
public int? y {get; set;}
}
static void Main()
{
var c = new C1();
C1 n = null;
System.Console.WriteLine(Test1(ref c));
System.Console.WriteLine(Test1(ref n));
System.Console.WriteLine(Test2(ref c));
System.Console.WriteLine(Test2(ref n));
}
static int Test1(ref C1 c)
{
return c?.x ?? 42;
}
static int Test2(ref C1 c)
{
return c?.y ?? 42;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"0
42
42
42");
comp.VerifyIL("Program.Test1(ref Program.C1)", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: dup
IL_0003: brtrue.s IL_0009
IL_0005: pop
IL_0006: ldc.i4.s 42
IL_0008: ret
IL_0009: call ""int Program.C1.x.get""
IL_000e: ret
}
").VerifyIL("Program.Test2(ref Program.C1)", @"
{
// Code size 43 (0x2b)
.maxstack 2
.locals init (int? V_0,
int? V_1)
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: dup
IL_0003: brtrue.s IL_0011
IL_0005: pop
IL_0006: ldloca.s V_1
IL_0008: initobj ""int?""
IL_000e: ldloc.1
IL_000f: br.s IL_0016
IL_0011: call ""int? Program.C1.y.get""
IL_0016: stloc.0
IL_0017: ldloca.s V_0
IL_0019: call ""bool int?.HasValue.get""
IL_001e: brtrue.s IL_0023
IL_0020: ldc.i4.s 42
IL_0022: ret
IL_0023: ldloca.s V_0
IL_0025: call ""int int?.GetValueOrDefault()""
IL_002a: ret
}
");
}
[Fact]
public void ConditionalMemberAccessCoalesce002()
{
var source = @"
class Program
{
struct C1
{
public int x{get; set;}
public int? y{get; set;}
}
static void Main()
{
var c = new C1();
System.Console.WriteLine(Test1(c));
System.Console.WriteLine(Test1(null));
System.Console.WriteLine(Test2(c));
System.Console.WriteLine(Test2(null));
}
static int Test1(C1? c)
{
return c?.x ?? 42;
}
static int Test2(C1? c)
{
return c?.y ?? 42;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"0
42
42
42");
comp.VerifyIL("Program.Test1(Program.C1?)", @"
{
// Code size 28 (0x1c)
.maxstack 1
.locals init (Program.C1 V_0)
IL_0000: ldarga.s V_0
IL_0002: call ""bool Program.C1?.HasValue.get""
IL_0007: brtrue.s IL_000c
IL_0009: ldc.i4.s 42
IL_000b: ret
IL_000c: ldarga.s V_0
IL_000e: call ""Program.C1 Program.C1?.GetValueOrDefault()""
IL_0013: stloc.0
IL_0014: ldloca.s V_0
IL_0016: call ""readonly int Program.C1.x.get""
IL_001b: ret
}
").VerifyIL("Program.Test2(Program.C1?)", @"
{
// Code size 56 (0x38)
.maxstack 1
.locals init (int? V_0,
int? V_1,
Program.C1 V_2)
IL_0000: ldarga.s V_0
IL_0002: call ""bool Program.C1?.HasValue.get""
IL_0007: brtrue.s IL_0014
IL_0009: ldloca.s V_1
IL_000b: initobj ""int?""
IL_0011: ldloc.1
IL_0012: br.s IL_0023
IL_0014: ldarga.s V_0
IL_0016: call ""Program.C1 Program.C1?.GetValueOrDefault()""
IL_001b: stloc.2
IL_001c: ldloca.s V_2
IL_001e: call ""readonly int? Program.C1.y.get""
IL_0023: stloc.0
IL_0024: ldloca.s V_0
IL_0026: call ""bool int?.HasValue.get""
IL_002b: brtrue.s IL_0030
IL_002d: ldc.i4.s 42
IL_002f: ret
IL_0030: ldloca.s V_0
IL_0032: call ""int int?.GetValueOrDefault()""
IL_0037: ret
}
");
}
[Fact]
public void ConditionalMemberAccessCoalesce002r()
{
var source = @"
class Program
{
struct C1
{
public int x{get; set;}
public int? y{get; set;}
}
static void Main()
{
C1? c = new C1();
C1? n = null;
System.Console.WriteLine(Test1(ref c));
System.Console.WriteLine(Test1(ref n));
System.Console.WriteLine(Test2(ref c));
System.Console.WriteLine(Test2(ref n));
}
static int Test1(ref C1? c)
{
return c?.x ?? 42;
}
static int Test2(ref C1? c)
{
return c?.y ?? 42;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"0
42
42
42");
comp.VerifyIL("Program.Test1(ref Program.C1?)", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (Program.C1 V_0)
IL_0000: ldarg.0
IL_0001: dup
IL_0002: call ""bool Program.C1?.HasValue.get""
IL_0007: brtrue.s IL_000d
IL_0009: pop
IL_000a: ldc.i4.s 42
IL_000c: ret
IL_000d: call ""Program.C1 Program.C1?.GetValueOrDefault()""
IL_0012: stloc.0
IL_0013: ldloca.s V_0
IL_0015: call ""readonly int Program.C1.x.get""
IL_001a: ret
}
").VerifyIL("Program.Test2(ref Program.C1?)", @"
{
// Code size 55 (0x37)
.maxstack 2
.locals init (int? V_0,
int? V_1,
Program.C1 V_2)
IL_0000: ldarg.0
IL_0001: dup
IL_0002: call ""bool Program.C1?.HasValue.get""
IL_0007: brtrue.s IL_0015
IL_0009: pop
IL_000a: ldloca.s V_1
IL_000c: initobj ""int?""
IL_0012: ldloc.1
IL_0013: br.s IL_0022
IL_0015: call ""Program.C1 Program.C1?.GetValueOrDefault()""
IL_001a: stloc.2
IL_001b: ldloca.s V_2
IL_001d: call ""readonly int? Program.C1.y.get""
IL_0022: stloc.0
IL_0023: ldloca.s V_0
IL_0025: call ""bool int?.HasValue.get""
IL_002a: brtrue.s IL_002f
IL_002c: ldc.i4.s 42
IL_002e: ret
IL_002f: ldloca.s V_0
IL_0031: call ""int int?.GetValueOrDefault()""
IL_0036: ret
}
");
}
[Fact]
public void ConditionalMemberAccessCoalesceDefault()
{
var source = @"
class Program
{
class C1
{
public int x { get; set; }
}
static void Main()
{
var c = new C1() { x = 42 };
System.Console.WriteLine(Test(c));
System.Console.WriteLine(Test(null));
}
static int Test(C1 c)
{
return c?.x ?? 0;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"
42
0");
comp.VerifyIL("Program.Test(Program.C1)", @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int Program.C1.x.get""
IL_000b: ret
}
");
}
[Fact]
public void ConditionalMemberAccessNullCheck001()
{
var source = @"
class Program
{
class C1
{
public int x{get; set;}
}
static void Main()
{
var c = new C1();
System.Console.WriteLine(Test1(c));
System.Console.WriteLine(Test1(null));
System.Console.WriteLine(Test2(c));
System.Console.WriteLine(Test2(null));
System.Console.WriteLine(Test3(c));
System.Console.WriteLine(Test3(null));
}
static bool Test1(C1 c)
{
return c?.x == null;
}
static bool Test2(C1 c)
{
return c?.x != null;
}
static bool Test3(C1 c)
{
return c?.x > null;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
True
True
False
False
False");
comp.VerifyIL("Program.Test1(Program.C1)", @"
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.1
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int Program.C1.x.get""
IL_000b: pop
IL_000c: ldc.i4.0
IL_000d: ret
}
").VerifyIL("Program.Test2(Program.C1)", @"
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int Program.C1.x.get""
IL_000b: pop
IL_000c: ldc.i4.1
IL_000d: ret
}
").VerifyIL("Program.Test3(Program.C1)", @"
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int Program.C1.x.get""
IL_000b: pop
IL_000c: ldc.i4.0
IL_000d: ret
}
");
}
[Fact]
public void ConditionalMemberAccessBinary001()
{
var source = @"
public enum N
{
zero = 0,
one = 1,
mone = -1
}
class Program
{
class C1
{
public N x{get; set;}
}
static void Main()
{
var c = new C1();
System.Console.WriteLine(Test1(c));
System.Console.WriteLine(Test1(null));
System.Console.WriteLine(Test2(c));
System.Console.WriteLine(Test2(null));
System.Console.WriteLine(Test3(c));
System.Console.WriteLine(Test3(null));
}
static bool Test1(C1 c)
{
return c?.x == N.zero;
}
static bool Test2(C1 c)
{
return c?.x != N.one;
}
static bool Test3(C1 c)
{
return c?.x > N.mone;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"True
False
True
True
True
False");
comp.VerifyIL("Program.Test1(Program.C1)", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""N Program.C1.x.get""
IL_000b: ldc.i4.0
IL_000c: ceq
IL_000e: ret
}
").VerifyIL("Program.Test2(Program.C1)", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.1
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""N Program.C1.x.get""
IL_000b: ldc.i4.1
IL_000c: ceq
IL_000e: ldc.i4.0
IL_000f: ceq
IL_0011: ret
}
").VerifyIL("Program.Test3(Program.C1)", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""N Program.C1.x.get""
IL_000b: ldc.i4.m1
IL_000c: cgt
IL_000e: ret
}
");
}
[Fact]
public void ConditionalMemberAccessBinary002()
{
var source = @"
static class ext
{
public static Program.C1.S1 y(this Program.C1 self)
{
return self.x;
}
}
class Program
{
public class C1
{
public struct S1
{
public static bool operator <(S1 s1, int s2)
{
System.Console.WriteLine('<');
return true;
}
public static bool operator >(S1 s1, int s2)
{
System.Console.WriteLine('>');
return false;
}
}
public S1 x { get; set; }
}
static void Main()
{
C1 c = new C1();
C1 n = null;
System.Console.WriteLine(Test1(c));
System.Console.WriteLine(Test1(n));
System.Console.WriteLine(Test2(ref c));
System.Console.WriteLine(Test2(ref n));
System.Console.WriteLine(Test3(c));
System.Console.WriteLine(Test3(n));
System.Console.WriteLine(Test4(ref c));
System.Console.WriteLine(Test4(ref n));
}
static bool Test1(C1 c)
{
return c?.x > -1;
}
static bool Test2(ref C1 c)
{
return c?.x < -1;
}
static bool Test3(C1 c)
{
return c?.y() > -1;
}
static bool Test4(ref C1 c)
{
return c?.y() < -1;
}
}
";
var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @" >
False
False
<
True
False
>
False
False
<
True
False");
comp.VerifyIL("Program.Test1(Program.C1)", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""Program.C1.S1 Program.C1.x.get""
IL_000b: ldc.i4.m1
IL_000c: call ""bool Program.C1.S1.op_GreaterThan(Program.C1.S1, int)""
IL_0011: ret
}
").VerifyIL("Program.Test2(ref Program.C1)", @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: dup
IL_0003: brtrue.s IL_0008
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
IL_0008: call ""Program.C1.S1 Program.C1.x.get""
IL_000d: ldc.i4.m1
IL_000e: call ""bool Program.C1.S1.op_LessThan(Program.C1.S1, int)""
IL_0013: ret
}
").VerifyIL("Program.Test3(Program.C1)", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""Program.C1.S1 ext.y(Program.C1)""
IL_000b: ldc.i4.m1
IL_000c: call ""bool Program.C1.S1.op_GreaterThan(Program.C1.S1, int)""
IL_0011: ret
}
").VerifyIL("Program.Test4(ref Program.C1)", @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: dup
IL_0003: brtrue.s IL_0008
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
IL_0008: call ""Program.C1.S1 ext.y(Program.C1)""
IL_000d: ldc.i4.m1
IL_000e: call ""bool Program.C1.S1.op_LessThan(Program.C1.S1, int)""
IL_0013: ret
}
");
}
[Fact]
public void ConditionalMemberAccessOptimizedLocal001()
{
var source = @"
using System;
class Program
{
class C1 : System.IDisposable
{
public bool disposed;
public void Dispose()
{
disposed = true;
}
}
static void Main()
{
Test1();
Test2<C1>();
}
static void Test1()
{
var c = new C1();
c?.Dispose();
}
static void Test2<T>() where T : IDisposable, new()
{
var c = new T();
c?.Dispose();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"");
comp.VerifyIL("Program.Test1()", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: newobj ""Program.C1..ctor()""
IL_0005: dup
IL_0006: brtrue.s IL_000a
IL_0008: pop
IL_0009: ret
IL_000a: call ""void Program.C1.Dispose()""
IL_000f: ret
}
").VerifyIL("Program.Test2<T>()", @"
{
// Code size 28 (0x1c)
.maxstack 1
.locals init (T V_0) //c
IL_0000: call ""T System.Activator.CreateInstance<T>()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: box ""T""
IL_000c: brfalse.s IL_001b
IL_000e: ldloca.s V_0
IL_0010: constrained. ""T""
IL_0016: callvirt ""void System.IDisposable.Dispose()""
IL_001b: ret
}
");
}
[Fact]
public void ConditionalMemberAccessOptimizedLocal002()
{
var source = @"
using System;
class Program
{
interface I1
{
void Goo(I1 arg);
}
class C1 : I1
{
public void Goo(I1 arg)
{
}
}
static void Main()
{
Test1();
Test2<C1>();
}
static void Test1()
{
var c = new C1();
c?.Goo(c);
}
static void Test2<T>() where T : I1, new()
{
var c = new T();
c?.Goo(c);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"");
comp.VerifyIL("Program.Test1()", @"
{
// Code size 17 (0x11)
.maxstack 2
.locals init (Program.C1 V_0) //c
IL_0000: newobj ""Program.C1..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: brfalse.s IL_0010
IL_0009: ldloc.0
IL_000a: ldloc.0
IL_000b: call ""void Program.C1.Goo(Program.I1)""
IL_0010: ret
}
").VerifyIL("Program.Test2<T>()", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (T V_0) //c
IL_0000: call ""T System.Activator.CreateInstance<T>()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: box ""T""
IL_000c: brfalse.s IL_0021
IL_000e: ldloca.s V_0
IL_0010: ldloc.0
IL_0011: box ""T""
IL_0016: constrained. ""T""
IL_001c: callvirt ""void Program.I1.Goo(Program.I1)""
IL_0021: ret
}
");
}
[Fact]
public void ConditionalMemberAccessRace001()
{
var source = @"
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
string s = ""hello"";
System.Action a = () =>
{
for (int i = 0; i < 1000000; i++)
{
try
{
s = s?.Length.ToString();
s = null;
Thread.Yield();
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex);
}
finally
{
s = s ?? ""hello"";
}
}
};
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
Task.Factory.StartNew(a);
a();
System.Console.WriteLine(""Success"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"Success");
}
[Fact(), WorkItem(836, "GitHub")]
public void ConditionalMemberAccessRace002()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
string s = ""hello"";
Test(s);
}
private static void Test<T>(T s) where T : IEnumerable<char>
{
Action a = () =>
{
for (int i = 0; i < 1000000; i++)
{
var temp = s;
try
{
s?.GetEnumerator();
s = default(T);
Thread.Yield();
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex);
}
finally
{
s = temp;
}
}
};
var tasks = new List<Task>();
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
tasks.Add(Task.Factory.StartNew(a));
a();
// wait for all tasks to exit or we may have
// test issues when unloading ApDomain while threads still running in it
Task.WaitAll(tasks.ToArray());
System.Console.WriteLine(""Success"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"Success");
}
[Fact]
public void ConditionalMemberAccessConditional001()
{
var source = @"
using System;
class Program
{
static void Main()
{
Test1<string>(null);
Test2<string>(null);
}
static string Test1<T>(T[] arr)
{
if (arr != null && arr.Length > 0)
{
return arr[0].ToString();
}
return ""none"";
}
static string Test2<T>(T[] arr)
{
if (arr?.Length > 0)
{
return arr[0].ToString();
}
return ""none"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"");
comp.VerifyIL("Program.Test1<T>(T[])", @"
{
// Code size 34 (0x22)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_001c
IL_0003: ldarg.0
IL_0004: ldlen
IL_0005: brfalse.s IL_001c
IL_0007: ldarg.0
IL_0008: ldc.i4.0
IL_0009: readonly.
IL_000b: ldelema ""T""
IL_0010: constrained. ""T""
IL_0016: callvirt ""string object.ToString()""
IL_001b: ret
IL_001c: ldstr ""none""
IL_0021: ret
}
").VerifyIL("Program.Test2<T>(T[])", @"
{
// Code size 34 (0x22)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_001c
IL_0003: ldarg.0
IL_0004: ldlen
IL_0005: brfalse.s IL_001c
IL_0007: ldarg.0
IL_0008: ldc.i4.0
IL_0009: readonly.
IL_000b: ldelema ""T""
IL_0010: constrained. ""T""
IL_0016: callvirt ""string object.ToString()""
IL_001b: ret
IL_001c: ldstr ""none""
IL_0021: ret
}
");
}
[Fact]
public void ConditionalMemberAccessConditional002()
{
var source = @"
using System;
class Program
{
static void Main()
{
Test1<string>(null);
Test2<string>(null);
}
static string Test1<T>(T[] arr)
{
if (!(arr != null && arr.Length > 0))
{
return ""none"";
}
return arr[0].ToString();
}
static string Test2<T>(T[] arr)
{
if (!(arr?.Length > 0))
{
return ""none"";
}
return arr[0].ToString();
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"");
comp.VerifyIL("Program.Test1<T>(T[])", @"
{
// Code size 34 (0x22)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0007
IL_0003: ldarg.0
IL_0004: ldlen
IL_0005: brtrue.s IL_000d
IL_0007: ldstr ""none""
IL_000c: ret
IL_000d: ldarg.0
IL_000e: ldc.i4.0
IL_000f: readonly.
IL_0011: ldelema ""T""
IL_0016: constrained. ""T""
IL_001c: callvirt ""string object.ToString()""
IL_0021: ret
}
").VerifyIL("Program.Test2<T>(T[])", @"
{
// Code size 34 (0x22)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0007
IL_0003: ldarg.0
IL_0004: ldlen
IL_0005: brtrue.s IL_000d
IL_0007: ldstr ""none""
IL_000c: ret
IL_000d: ldarg.0
IL_000e: ldc.i4.0
IL_000f: readonly.
IL_0011: ldelema ""T""
IL_0016: constrained. ""T""
IL_001c: callvirt ""string object.ToString()""
IL_0021: ret
}
");
}
[Fact]
public void ConditionalMemberAccessConditional003()
{
var source = @"
using System;
class Program
{
static void Main()
{
System.Console.WriteLine(Test1<string>(null));
System.Console.WriteLine(Test2<string>(null));
System.Console.WriteLine(Test1<string>(new string[] {}));
System.Console.WriteLine(Test2<string>(new string[] {}));
System.Console.WriteLine(Test1<string>(new string[] { System.String.Empty }));
System.Console.WriteLine(Test2<string>(new string[] { System.String.Empty }));
}
static string Test1<T>(T[] arr1)
{
var arr = arr1;
if (arr != null && arr.Length == 0)
{
return ""empty"";
}
return ""not empty"";
}
static string Test2<T>(T[] arr1)
{
var arr = arr1;
if (!(arr?.Length != 0))
{
return ""empty"";
}
return ""not empty"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"not empty
not empty
empty
empty
not empty
not empty");
comp.VerifyIL("Program.Test1<T>(T[])", @"
{
// Code size 21 (0x15)
.maxstack 1
.locals init (T[] V_0) //arr
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brfalse.s IL_000f
IL_0005: ldloc.0
IL_0006: ldlen
IL_0007: brtrue.s IL_000f
IL_0009: ldstr ""empty""
IL_000e: ret
IL_000f: ldstr ""not empty""
IL_0014: ret
}
").VerifyIL("Program.Test2<T>(T[])", @"
{
// Code size 26 (0x1a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0008
IL_0004: pop
IL_0005: ldc.i4.1
IL_0006: br.s IL_000c
IL_0008: ldlen
IL_0009: ldc.i4.0
IL_000a: cgt.un
IL_000c: brtrue.s IL_0014
IL_000e: ldstr ""empty""
IL_0013: ret
IL_0014: ldstr ""not empty""
IL_0019: ret
}
");
}
[Fact]
public void ConditionalMemberAccessConditional004()
{
var source = @"
using System;
class Program
{
static void Main()
{
var w = new WeakReference<string>(null);
Test0(ref w);
Test1(ref w);
Test2(ref w);
Test3(ref w);
}
static string Test0(ref WeakReference<string> slot)
{
string value = null;
WeakReference<string> weak = slot;
if (weak != null && weak.TryGetTarget(out value))
{
return value;
}
return ""hello"";
}
static string Test1(ref WeakReference<string> slot)
{
string value = null;
WeakReference<string> weak = slot;
if (weak?.TryGetTarget(out value) == true)
{
return value;
}
return ""hello"";
}
static string Test2(ref WeakReference<string> slot)
{
string value = null;
if (slot?.TryGetTarget(out value) == true)
{
return value;
}
return ""hello"";
}
static string Test3(ref WeakReference<string> slot)
{
string value = null;
if (slot?.TryGetTarget(out value) ?? false)
{
return value;
}
return ""hello"";
}
}
";
var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "").
VerifyIL("Program.Test0(ref System.WeakReference<string>)", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (string V_0, //value
System.WeakReference<string> V_1) //weak
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldind.ref
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: brfalse.s IL_0014
IL_0008: ldloc.1
IL_0009: ldloca.s V_0
IL_000b: callvirt ""bool System.WeakReference<string>.TryGetTarget(out string)""
IL_0010: brfalse.s IL_0014
IL_0012: ldloc.0
IL_0013: ret
IL_0014: ldstr ""hello""
IL_0019: ret
}
").VerifyIL("Program.Test1(ref System.WeakReference<string>)", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (string V_0) //value
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldind.ref
IL_0004: dup
IL_0005: brtrue.s IL_000b
IL_0007: pop
IL_0008: ldc.i4.0
IL_0009: br.s IL_0012
IL_000b: ldloca.s V_0
IL_000d: call ""bool System.WeakReference<string>.TryGetTarget(out string)""
IL_0012: brfalse.s IL_0016
IL_0014: ldloc.0
IL_0015: ret
IL_0016: ldstr ""hello""
IL_001b: ret
}
").VerifyIL("Program.Test2(ref System.WeakReference<string>)", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (string V_0) //value
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldind.ref
IL_0004: dup
IL_0005: brtrue.s IL_000b
IL_0007: pop
IL_0008: ldc.i4.0
IL_0009: br.s IL_0012
IL_000b: ldloca.s V_0
IL_000d: call ""bool System.WeakReference<string>.TryGetTarget(out string)""
IL_0012: brfalse.s IL_0016
IL_0014: ldloc.0
IL_0015: ret
IL_0016: ldstr ""hello""
IL_001b: ret
}
").VerifyIL("Program.Test3(ref System.WeakReference<string>)", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (string V_0) //value
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldind.ref
IL_0004: dup
IL_0005: brtrue.s IL_000b
IL_0007: pop
IL_0008: ldc.i4.0
IL_0009: br.s IL_0012
IL_000b: ldloca.s V_0
IL_000d: call ""bool System.WeakReference<string>.TryGetTarget(out string)""
IL_0012: brfalse.s IL_0016
IL_0014: ldloc.0
IL_0015: ret
IL_0016: ldstr ""hello""
IL_001b: ret
}
");
}
[WorkItem(1042288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042288")]
[Fact]
public void Bug1042288()
{
var source = @"
using System;
class Test
{
static void Main()
{
var c1 = new C1();
System.Console.WriteLine(c1?.M1() ?? (long)1000);
return;
}
}
class C1
{
public int M1()
{
return 1;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"1");
comp.VerifyIL("Test.Main", @"
{
// Code size 62 (0x3e)
.maxstack 2
.locals init (int? V_0,
int? V_1)
IL_0000: newobj ""C1..ctor()""
IL_0005: dup
IL_0006: brtrue.s IL_0014
IL_0008: pop
IL_0009: ldloca.s V_1
IL_000b: initobj ""int?""
IL_0011: ldloc.1
IL_0012: br.s IL_001e
IL_0014: call ""int C1.M1()""
IL_0019: newobj ""int?..ctor(int)""
IL_001e: stloc.0
IL_001f: ldloca.s V_0
IL_0021: call ""bool int?.HasValue.get""
IL_0026: brtrue.s IL_0030
IL_0028: ldc.i4 0x3e8
IL_002d: conv.i8
IL_002e: br.s IL_0038
IL_0030: ldloca.s V_0
IL_0032: call ""int int?.GetValueOrDefault()""
IL_0037: conv.i8
IL_0038: call ""void System.Console.WriteLine(long)""
IL_003d: ret
}
");
}
[WorkItem(470, "CodPlex")]
[Fact]
public void CodPlexBug470_01()
{
var source = @"
class C
{
public static void Main()
{
System.Console.WriteLine(MyMethod(null));
System.Console.WriteLine(MyMethod(new MyType()));
}
public static decimal MyMethod(MyType myObject)
{
return myObject?.MyField ?? 0m;
}
}
public class MyType
{
public decimal MyField = 123;
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0
123");
verifier.VerifyIL("C.MyMethod", @"
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0009
IL_0003: ldsfld ""decimal decimal.Zero""
IL_0008: ret
IL_0009: ldarg.0
IL_000a: ldfld ""decimal MyType.MyField""
IL_000f: ret
}");
}
[WorkItem(470, "CodPlex")]
[Fact]
public void CodPlexBug470_02()
{
var source = @"
class C
{
public static void Main()
{
System.Console.WriteLine(MyMethod(null));
System.Console.WriteLine(MyMethod(new MyType()));
}
public static decimal MyMethod(MyType myObject)
{
return myObject?.MyField ?? default(decimal);
}
}
public class MyType
{
public decimal MyField = 123;
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0
123");
verifier.VerifyIL("C.MyMethod", @"
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0009
IL_0003: ldsfld ""decimal decimal.Zero""
IL_0008: ret
IL_0009: ldarg.0
IL_000a: ldfld ""decimal MyType.MyField""
IL_000f: ret
}");
}
[WorkItem(470, "CodPlex")]
[Fact]
public void CodPlexBug470_03()
{
var source = @"
using System;
class C
{
public static void Main()
{
System.Console.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, ""{0}"", MyMethod(null)));
System.Console.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, ""{0}"", MyMethod(new MyType())));
}
public static DateTime MyMethod(MyType myObject)
{
return myObject?.MyField ?? default(DateTime);
}
}
public class MyType
{
public DateTime MyField = new DateTime(100000000);
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"01/01/0001 00:00:00
01/01/0001 00:00:10");
verifier.VerifyIL("C.MyMethod", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (System.DateTime V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""System.DateTime""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldarg.0
IL_000e: ldfld ""System.DateTime MyType.MyField""
IL_0013: ret
}");
}
[WorkItem(470, "CodPlex")]
[Fact]
public void CodPlexBug470_04()
{
var source = @"
class C
{
public static void Main()
{
System.Console.WriteLine(MyMethod(null).F);
System.Console.WriteLine(MyMethod(new MyType()).F);
}
public static MyStruct MyMethod(MyType myObject)
{
return myObject?.MyField ?? default(MyStruct);
}
}
public class MyType
{
public MyStruct MyField = new MyStruct() {F = 123};
}
public struct MyStruct
{
public int F;
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0
123");
verifier.VerifyIL("C.MyMethod", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (MyStruct V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""MyStruct""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldarg.0
IL_000e: ldfld ""MyStruct MyType.MyField""
IL_0013: ret
}");
}
[WorkItem(1103294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103294")]
[Fact]
public void Bug1103294_01()
{
var source = @"
class C
{
static void Main()
{
System.Console.WriteLine(""---"");
Goo<int>(new C<int>());
System.Console.WriteLine(""---"");
Goo<int>(null);
System.Console.WriteLine(""---"");
}
static void Goo<T>(C<T> x)
{
x?.M();
}
}
class C<T>
{
public T M()
{
System.Console.WriteLine(""M"");
return default(T);
}
}";
var verifier = CompileAndVerify(source, expectedOutput: @"---
M
---
---");
verifier.VerifyIL("C.Goo<T>", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brfalse.s IL_000a
IL_0003: ldarg.0
IL_0004: call ""T C<T>.M()""
IL_0009: pop
IL_000a: ret
}");
}
[WorkItem(1103294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103294")]
[Fact]
public void Bug1103294_02()
{
var source = @"
unsafe class C
{
static void Main()
{
System.Console.WriteLine(""---"");
Goo(new C());
System.Console.WriteLine(""---"");
Goo(null);
System.Console.WriteLine(""---"");
}
static void Goo(C x)
{
x?.M();
}
public int* M()
{
System.Console.WriteLine(""M"");
return null;
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), verify: Verification.Fails, expectedOutput: @"---
M
---
---");
verifier.VerifyIL("C.Goo", @"
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: nop
IL_0001: ldarg.0
IL_0002: brtrue.s IL_0006
IL_0004: br.s IL_000d
IL_0006: ldarg.0
IL_0007: call ""int* C.M()""
IL_000c: pop
IL_000d: ret
}");
}
[WorkItem(23422, "https://github.com/dotnet/roslyn/issues/23422")]
[Fact]
public void ConditionalRefLike()
{
var source = @"
class C
{
static void Main()
{
System.Console.WriteLine(""---"");
Goo(new C());
System.Console.WriteLine(""---"");
Goo(null);
System.Console.WriteLine(""---"");
}
static void Goo(C x)
{
x?.M();
}
public RefLike M()
{
System.Console.WriteLine(""M"");
return default;
}
public ref struct RefLike{}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), expectedOutput: @"---
M
---
---");
verifier.VerifyIL("C.Goo", @"
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: nop
IL_0001: ldarg.0
IL_0002: brtrue.s IL_0006
IL_0004: br.s IL_000d
IL_0006: ldarg.0
IL_0007: call ""C.RefLike C.M()""
IL_000c: pop
IL_000d: ret
}");
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_01()
{
var source = @"
using System;
class Test
{
static void Main()
{
System.Console.WriteLine(""---"");
C.F1(null);
System.Console.WriteLine(""---"");
C.F1(new C());
System.Console.WriteLine(""---"");
C.F2(null);
System.Console.WriteLine(""---"");
C.F2(new C());
System.Console.WriteLine(""---"");
}
}
class C
{
static public void F1(C c)
{
System.Console.WriteLine(""F1"");
Action a = () => c?.M();
a();
}
static public void F2(C c) => c?.M();
void M() => System.Console.WriteLine(""M"");
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"---
F1
---
F1
M
---
---
M
---");
verifier.VerifyIL("C.<>c__DisplayClass0_0.<F1>b__0", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<>c__DisplayClass0_0.c""
IL_0006: dup
IL_0007: brtrue.s IL_000c
IL_0009: pop
IL_000a: br.s IL_0012
IL_000c: call ""void C.M()""
IL_0011: nop
IL_0012: ret
}");
verifier.VerifyIL("C.F2", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: br.s IL_000c
IL_0005: ldarg.0
IL_0006: call ""void C.M()""
IL_000b: nop
IL_000c: ret
}");
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_02()
{
var source = @"
using System;
class Test
{
static void Main()
{
}
}
class C
{
static public void F1(C c)
{
System.Console.WriteLine(""F1"");
Func<object> a = () => c?.M();
}
static public object F2(C c) => c?.M();
static public object P1 => (new C())?.M();
void M() => System.Console.WriteLine(""M"");
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (16,32): error CS0029: Cannot implicitly convert type 'void' to 'object'
// Func<object> a = () => c?.M();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c?.M()").WithArguments("void", "object").WithLocation(16, 32),
// (16,32): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// Func<object> a = () => c?.M();
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "c?.M()").WithArguments("lambda expression").WithLocation(16, 32),
// (19,37): error CS0029: Cannot implicitly convert type 'void' to 'object'
// static public object F2(C c) => c?.M();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c?.M()").WithArguments("void", "object").WithLocation(19, 37),
// (21,32): error CS0029: Cannot implicitly convert type 'void' to 'object'
// static public object P1 => (new C())?.M();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new C())?.M()").WithArguments("void", "object").WithLocation(21, 32)
);
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_03()
{
var source = @"
using System;
class Test
{
static void Main()
{
System.Console.WriteLine(""---"");
C<int>.F1(null);
System.Console.WriteLine(""---"");
C<int>.F1(new C<int>());
System.Console.WriteLine(""---"");
C<int>.F2(null);
System.Console.WriteLine(""---"");
C<int>.F2(new C<int>());
System.Console.WriteLine(""---"");
}
}
class C<T>
{
static public void F1(C<T> c)
{
System.Console.WriteLine(""F1"");
Action a = () => c?.M();
a();
}
static public void F2(C<T> c) => c?.M();
T M()
{
System.Console.WriteLine(""M"");
return default(T);
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"---
F1
---
F1
M
---
---
M
---");
verifier.VerifyIL("C<T>.<>c__DisplayClass0_0.<F1>b__0()", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C<T> C<T>.<>c__DisplayClass0_0.c""
IL_0006: dup
IL_0007: brtrue.s IL_000c
IL_0009: pop
IL_000a: br.s IL_0012
IL_000c: call ""T C<T>.M()""
IL_0011: pop
IL_0012: ret
}");
verifier.VerifyIL("C<T>.F2", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: br.s IL_000c
IL_0005: ldarg.0
IL_0006: call ""T C<T>.M()""
IL_000b: pop
IL_000c: ret
}");
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_04()
{
var source = @"
using System;
class Test
{
static void Main()
{
}
}
class C<T>
{
static public void F1(C<T> c)
{
Func<object> a = () => c?.M();
}
static public object F2(C<T> c) => c?.M();
static public object P1 => (new C<T>())?.M();
T M()
{
return default(T);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (15,33): error CS0023: Operator '?' cannot be applied to operand of type 'T'
// Func<object> a = () => c?.M();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(15, 33),
// (18,41): error CS0023: Operator '?' cannot be applied to operand of type 'T'
// static public object F2(C<T> c) => c?.M();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(18, 41),
// (20,44): error CS0023: Operator '?' cannot be applied to operand of type 'T'
// static public object P1 => (new C<T>())?.M();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(20, 44)
);
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_05()
{
var source = @"
using System;
class Test
{
static void Main()
{
System.Console.WriteLine(""---"");
C.F1(null);
System.Console.WriteLine(""---"");
C.F1(new C());
System.Console.WriteLine(""---"");
C.F2(null);
System.Console.WriteLine(""---"");
C.F2(new C());
System.Console.WriteLine(""---"");
}
}
unsafe class C
{
static public void F1(C c)
{
System.Console.WriteLine(""F1"");
Action<object> a = o => c?.M();
a(null);
}
static public void F2(C c) => c?.M();
void* M()
{
System.Console.WriteLine(""M"");
return null;
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), verify: Verification.Fails, expectedOutput: @"---
F1
---
F1
M
---
---
M
---");
verifier.VerifyIL("C.<>c__DisplayClass0_0.<F1>b__0", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<>c__DisplayClass0_0.c""
IL_0006: dup
IL_0007: brtrue.s IL_000c
IL_0009: pop
IL_000a: br.s IL_0012
IL_000c: call ""void* C.M()""
IL_0011: pop
IL_0012: ret
}");
verifier.VerifyIL("C.F2", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: br.s IL_000c
IL_0005: ldarg.0
IL_0006: call ""void* C.M()""
IL_000b: pop
IL_000c: ret
}");
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_06()
{
var source = @"
using System;
class Test
{
static void Main()
{
}
}
unsafe class C
{
static public void F1(C c)
{
System.Console.WriteLine(""F1"");
Func<object, object> a = o => c?.M();
}
static public object F2(C c) => c?.M();
static public object P1 => (new C())?.M();
void* M()
{
System.Console.WriteLine(""M"");
return null;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
// (16,40): error CS0023: Operator '?' cannot be applied to operand of type 'void*'
// Func<object, object> a = o => c?.M();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(16, 40),
// (19,38): error CS0023: Operator '?' cannot be applied to operand of type 'void*'
// static public object F2(C c) => c?.M();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(19, 38),
// (21,41): error CS0023: Operator '?' cannot be applied to operand of type 'void*'
// static public object P1 => (new C())?.M();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(21, 41)
);
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_07()
{
var source = @"
using System;
class Test
{
static void Main()
{
C<int>.Test();
}
}
class C<T>
{
public static void Test()
{
var x = new [] {null, new C<T>()};
for (int i = 0; i < 2; x[i-1]?.M())
{
System.Console.WriteLine(""---"");
System.Console.WriteLine(""Loop"");
i++;
}
System.Console.WriteLine(""---"");
}
public T M()
{
System.Console.WriteLine(""M"");
return default(T);
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @" ---
Loop
---
Loop
M
---");
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_08()
{
var source = @"
using System;
class Test
{
static void Main()
{
C<int>.Test();
}
}
class C<T>
{
public static void Test()
{
var x = new [] {null, new C<T>()};
System.Console.WriteLine(""---"");
for (x[0]?.M(); false;)
{
}
System.Console.WriteLine(""---"");
for (x[1]?.M(); false;)
{
}
System.Console.WriteLine(""---"");
}
public T M()
{
System.Console.WriteLine(""M"");
return default(T);
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"---
---
M
---");
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_09()
{
var source = @"
class Test
{
static void Main()
{
}
}
class C<T>
{
public static void Test()
{
C<T> x = null;
for (; x?.M();)
{
}
}
public T M()
{
return default(T);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (15,17): error CS0023: Operator '?' cannot be applied to operand of type 'T'
// for (; x?.M();)
Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(15, 17)
);
}
[WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")]
[Fact]
public void Bug1109164_10()
{
var source = @"
using System;
class Test
{
static void Main()
{
C<int>.Test();
}
}
class C<T>
{
public static void Test()
{
System.Console.WriteLine(""---"");
M1(a => a?.M(), null);
System.Console.WriteLine(""---"");
M1((a) => a?.M(), new C<T>());
System.Console.WriteLine(""---"");
}
static void M1(Action<C<T>> x, C<T> y)
{
System.Console.WriteLine(""M1(Action<C<T>> x)"");
x(y);
}
static void M1(Func<C<T>, object> x, C<T> y)
{
System.Console.WriteLine(""M1(Func<C<T>, object> x)"");
x(y);
}
public T M()
{
System.Console.WriteLine(""M"");
return default(T);
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"---
M1(Action<C<T>> x)
---
M1(Action<C<T>> x)
M
---");
}
[WorkItem(74, "https://github.com/dotnet/roslyn/issues/74")]
[Fact]
public void ConditionalInAsyncTask()
{
var source = @"
#pragma warning disable CS1998 // suppress 'no await in async' warning
using System;
using System.Threading.Tasks;
class Goo<T>
{
public T Method(int i)
{
Console.Write(i);
return default(T); // returns value of unconstrained type parameter type
}
public void M1(Goo<T> x) => x?.Method(4);
public async void M2(Goo<T> x) => x?.Method(5);
public async Task M3(Goo<T> x) => x?.Method(6);
public async Task M4() {
Goo<T> a = new Goo<T>();
Goo<T> b = null;
Action f1 = async () => a?.Method(1);
f1();
f1 = async () => b?.Method(0);
f1();
Func<Task> f2 = async () => a?.Method(2);
await f2();
Func<Task> f3 = async () => b?.Method(3);
await f3();
M1(a); M1(b);
M2(a); M2(b);
await M3(a);
await M3(b);
}
}
class Program
{
public static void Main()
{
// this will complete synchronously as there are no truly async ops.
new Goo<int>().M4();
}
}";
var compilation = CreateCompilationWithMscorlib45(
source, references: new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput: "12456");
}
[WorkItem(825, "https://github.com/dotnet/roslyn/issues/825")]
[Fact]
public void ConditionalBoolExpr01()
{
var source = @"
class C
{
public static void Main()
{
System.Console.WriteLine(HasLength(null, 0));
}
static bool HasLength(string s, int len)
{
return s?.Length == len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"False");
verifier.VerifyIL("C.HasLength", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int string.Length.get""
IL_000b: ldarg.1
IL_000c: ceq
IL_000e: ret
}");
}
[WorkItem(825, "https://github.com/dotnet/roslyn/issues/825")]
[Fact]
public void ConditionalBoolExpr01a()
{
var source = @"
class C
{
public static void Main()
{
System.Console.WriteLine(HasLength(null, 0));
}
static bool HasLength(string s, byte len)
{
return s?.Length == len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"False");
verifier.VerifyIL("C.HasLength", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int string.Length.get""
IL_000b: ldarg.1
IL_000c: ceq
IL_000e: ret
}");
}
[WorkItem(825, "https://github.com/dotnet/roslyn/issues/825")]
[WorkItem(5662, "https://github.com/dotnet/roslyn/issues/5662")]
[Fact]
public void ConditionalBoolExpr01b()
{
var source = @"
class C
{
public static void Main()
{
System.Console.WriteLine(HasLength(null, long.MaxValue));
try
{
System.Console.WriteLine(HasLengthChecked(null, long.MaxValue));
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.GetType().Name);
}
}
static bool HasLength(string s, long len)
{
return s?.Length == (int)(byte)len;
}
static bool HasLengthChecked(string s, long len)
{
checked
{
return s?.Length == (int)(byte)len;
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"False
OverflowException");
verifier.VerifyIL("C.HasLength", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.0
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int string.Length.get""
IL_000b: ldarg.1
IL_000c: conv.u1
IL_000d: ceq
IL_000f: ret
}").VerifyIL("C.HasLengthChecked", @"
{
// Code size 48 (0x30)
.maxstack 2
.locals init (int? V_0,
int V_1,
int? V_2)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000e
IL_0003: ldloca.s V_2
IL_0005: initobj ""int?""
IL_000b: ldloc.2
IL_000c: br.s IL_0019
IL_000e: ldarg.0
IL_000f: call ""int string.Length.get""
IL_0014: newobj ""int?..ctor(int)""
IL_0019: stloc.0
IL_001a: ldarg.1
IL_001b: conv.ovf.u1
IL_001c: stloc.1
IL_001d: ldloca.s V_0
IL_001f: call ""int int?.GetValueOrDefault()""
IL_0024: ldloc.1
IL_0025: ceq
IL_0027: ldloca.s V_0
IL_0029: call ""bool int?.HasValue.get""
IL_002e: and
IL_002f: ret
}");
}
[Fact]
public void ConditionalBoolExpr02()
{
var source = @"
class C
{
public static void Main()
{
System.Console.Write(HasLength(null, 0));
System.Console.Write(HasLength(null, 3));
System.Console.Write(HasLength(""q"", 2));
}
static bool HasLength(string s, int len)
{
return (s?.Length ?? 2) + 1 == len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"FalseTrueTrue");
verifier.VerifyIL("C.HasLength", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0006
IL_0003: ldc.i4.2
IL_0004: br.s IL_000c
IL_0006: ldarg.0
IL_0007: call ""int string.Length.get""
IL_000c: ldc.i4.1
IL_000d: add
IL_000e: ldarg.1
IL_000f: ceq
IL_0011: ret
}");
}
[Fact]
public void ConditionalBoolExpr02a()
{
var source = @"
class C
{
public static void Main()
{
System.Console.Write(NotHasLength(null, 0));
System.Console.Write(NotHasLength(null, 3));
System.Console.Write(NotHasLength(""q"", 2));
}
static bool NotHasLength(string s, int len)
{
return s?.Length + 1 != len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalse");
verifier.VerifyIL("C.NotHasLength", @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.1
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""int string.Length.get""
IL_000b: ldc.i4.1
IL_000c: add
IL_000d: ldarg.1
IL_000e: ceq
IL_0010: ldc.i4.0
IL_0011: ceq
IL_0013: ret
}");
}
[Fact]
public void ConditionalBoolExpr02b()
{
var source = @"
class C
{
public static void Main()
{
System.Console.Write(NotHasLength(null, 0));
System.Console.Write(NotHasLength(null, 3));
System.Console.Write(NotHasLength(""q"", 2));
System.Console.Write(NotHasLength(null, null));
}
static bool NotHasLength(string s, int? len)
{
return s?.Length + 1 != len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalseFalse");
verifier.VerifyIL("C.NotHasLength", @"
{
// Code size 42 (0x2a)
.maxstack 2
.locals init (int? V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000b
IL_0003: ldarga.s V_1
IL_0005: call ""bool int?.HasValue.get""
IL_000a: ret
IL_000b: ldarg.0
IL_000c: call ""int string.Length.get""
IL_0011: ldc.i4.1
IL_0012: add
IL_0013: ldarg.1
IL_0014: stloc.0
IL_0015: ldloca.s V_0
IL_0017: call ""int int?.GetValueOrDefault()""
IL_001c: ceq
IL_001e: ldloca.s V_0
IL_0020: call ""bool int?.HasValue.get""
IL_0025: and
IL_0026: ldc.i4.0
IL_0027: ceq
IL_0029: ret
}");
}
[Fact]
public void ConditionalBoolExpr03()
{
var source = @"
using System.Threading.Tasks;
static class C
{
public static void Main()
{
System.Console.Write(HasLength(null, 0).Result);
System.Console.Write(HasLength(null, 3).Result);
System.Console.Write(HasLength(""q"", 2).Result);
}
static async Task<bool> HasLength(string s, int len)
{
return (s?.Goo(await Bar()) ?? await Bar() + await Bar()) + 1 == len;
}
static int Goo(this string s, int arg)
{
return s.Length;
}
static async Task<int> Bar()
{
await Task.Yield();
return 1;
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"FalseTrueTrue");
}
[Fact]
public void ConditionalBoolExpr04()
{
var source = @"
using System.Threading.Tasks;
static class C
{
public static void Main()
{
System.Console.Write(HasLength((string)null, 0).Result);
System.Console.Write(HasLength((string)null, 3).Result);
System.Console.Write(HasLength(""q"", 2).Result);
}
static async Task<bool> HasLength<T>(T s, int len)
{
return (s?.Goo(await Bar()) ?? 2) + 1 == len;
}
static int Goo<T>(this T s, int arg)
{
return ((string)(object)s).Length;
}
static async Task<int> Bar()
{
await Task.Yield();
return 1;
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"FalseTrueTrue");
}
[Fact]
public void ConditionalBoolExpr05()
{
var source = @"
using System.Threading.Tasks;
static class C
{
public static void Main()
{
System.Console.Write(HasLength((string)null, 0).Result);
System.Console.Write(HasLength((string)null, 3).Result);
System.Console.Write(HasLength(""q"", 2).Result);
}
static async Task<bool> HasLength<T>(T s, int len)
{
return (s?.Goo(await Bar(await Bar())) ?? 2) + 1 == len;
}
static int Goo<T>(this T s, int arg)
{
return ((string)(object)s).Length;
}
static async Task<int> Bar()
{
await Task.Yield();
return 1;
}
static async Task<int> Bar(int arg)
{
await Task.Yield();
return arg;
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"FalseTrueTrue");
}
[Fact]
public void ConditionalBoolExpr06()
{
var source = @"
using System.Threading.Tasks;
static class C
{
public static void Main()
{
System.Console.Write(HasLength(null, 0).Result);
System.Console.Write(HasLength(null, 7).Result);
System.Console.Write(HasLength(""q"", 7).Result);
}
static async Task<bool> HasLength(string s, int len)
{
System.Console.WriteLine(s?.Goo(await Bar())?.Goo(await Bar()) + ""#"");
return s?.Goo(await Bar())?.Goo(await Bar()).Length == len;
}
static string Goo(this string s, string arg)
{
return s + arg;
}
static async Task<string> Bar()
{
await Task.Yield();
return ""Bar"";
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"#
False#
FalseqBarBar#
True");
}
[Fact]
public void ConditionalBoolExpr07()
{
var source = @"
using System.Threading.Tasks;
static class C
{
public static void Main()
{
System.Console.WriteLine(Test(null).Result);
System.Console.WriteLine(Test(""q"").Result);
}
static async Task<bool> Test(string s)
{
return (await Bar(s))?.Goo(await Bar())?.ToString()?.Length > 1;
}
static string Goo(this string s, string arg1)
{
return s + arg1;
}
static async Task<string> Bar()
{
await Task.Yield();
return ""Bar"";
}
static async Task<string> Bar(string arg)
{
await Task.Yield();
return arg;
}
}
";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True");
}
[Fact]
public void ConditionalBoolExpr08()
{
var source = @"
using System.Threading.Tasks;
static class C
{
public static void Main()
{
System.Console.WriteLine(Test(null).Result);
System.Console.WriteLine(Test(""q"").Result);
}
static async Task<bool> Test(string s)
{
return (await Bar(s))?.Insert(0, await Bar())?.ToString()?.Length > 1;
}
static async Task<string> Bar()
{
await Task.Yield();
return ""Bar"";
}
static async Task<dynamic> Bar(string arg)
{
await Task.Yield();
return arg;
}
}";
var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe);
var comp = CompileAndVerify(c, expectedOutput: @"False
True");
}
[Fact]
public void ConditionalUserDef01()
{
var source = @"
class C
{
struct S1
{
public static bool operator ==(S1? x, S1?y)
{
System.Console.Write(""=="");
return true;
}
public static bool operator !=(S1? x, S1? y)
{
System.Console.Write(""!="");
return false;
}
}
class C1
{
public S1 Goo()
{
return new S1();
}
}
public static void Main()
{
System.Console.WriteLine(TestEq(null, new S1()));
System.Console.WriteLine(TestEq(new C1(), new S1()));
System.Console.WriteLine(TestNeq(null, new S1()));
System.Console.WriteLine(TestNeq(new C1(), new S1()));
}
static bool TestEq(C1 c, S1 arg)
{
return c?.Goo() == arg;
}
static bool TestNeq(C1 c, S1 arg)
{
return c?.Goo() != arg;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"==True
==True
!=False
!=False");
verifier.VerifyIL("C.TestNeq", @"
{
// Code size 37 (0x25)
.maxstack 2
.locals init (C.S1? V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000e
IL_0003: ldloca.s V_0
IL_0005: initobj ""C.S1?""
IL_000b: ldloc.0
IL_000c: br.s IL_0019
IL_000e: ldarg.0
IL_000f: call ""C.S1 C.C1.Goo()""
IL_0014: newobj ""C.S1?..ctor(C.S1)""
IL_0019: ldarg.1
IL_001a: newobj ""C.S1?..ctor(C.S1)""
IL_001f: call ""bool C.S1.op_Inequality(C.S1?, C.S1?)""
IL_0024: ret
}");
}
[Fact]
public void ConditionalUserDef01n()
{
var source = @"
class C
{
struct S1
{
public static bool operator ==(S1? x, S1?y)
{
System.Console.Write(""=="");
return true;
}
public static bool operator !=(S1? x, S1? y)
{
System.Console.Write(""!="");
return false;
}
}
class C1
{
public S1 Goo()
{
return new S1();
}
}
public static void Main()
{
System.Console.WriteLine(TestEq(null, new S1()));
System.Console.WriteLine(TestEq(new C1(), new S1()));
System.Console.WriteLine(TestEq(new C1(), null));
System.Console.WriteLine(TestNeq(null, new S1()));
System.Console.WriteLine(TestNeq(new C1(), new S1()));
System.Console.WriteLine(TestNeq(new C1(), null));
}
static bool TestEq(C1 c, S1? arg)
{
return c?.Goo() == arg;
}
static bool TestNeq(C1 c, S1? arg)
{
return c?.Goo() != arg;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"==True
==True
==True
!=False
!=False
!=False");
verifier.VerifyIL("C.TestNeq", @"
{
// Code size 32 (0x20)
.maxstack 2
.locals init (C.S1? V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000e
IL_0003: ldloca.s V_0
IL_0005: initobj ""C.S1?""
IL_000b: ldloc.0
IL_000c: br.s IL_0019
IL_000e: ldarg.0
IL_000f: call ""C.S1 C.C1.Goo()""
IL_0014: newobj ""C.S1?..ctor(C.S1)""
IL_0019: ldarg.1
IL_001a: call ""bool C.S1.op_Inequality(C.S1?, C.S1?)""
IL_001f: ret
}");
}
[Fact]
public void ConditionalUserDef02()
{
var source = @"
class C
{
struct S1
{
public static bool operator ==(S1 x, S1 y)
{
System.Console.Write(""=="");
return true;
}
public static bool operator !=(S1 x, S1 y)
{
System.Console.Write(""!="");
return false;
}
}
class C1
{
public S1 Goo()
{
return new S1();
}
}
public static void Main()
{
System.Console.WriteLine(TestEq(null, new S1()));
System.Console.WriteLine(TestEq(new C1(), new S1()));
System.Console.WriteLine(TestNeq(null, new S1()));
System.Console.WriteLine(TestNeq(new C1(), new S1()));
}
static bool TestEq(C1 c, S1 arg)
{
return c?.Goo() == arg;
}
static bool TestNeq(C1 c, S1 arg)
{
return c?.Goo() != arg;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"False
==True
True
!=False");
verifier.VerifyIL("C.TestNeq", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldc.i4.1
IL_0004: ret
IL_0005: ldarg.0
IL_0006: call ""C.S1 C.C1.Goo()""
IL_000b: ldarg.1
IL_000c: call ""bool C.S1.op_Inequality(C.S1, C.S1)""
IL_0011: ret
}");
}
[Fact]
public void ConditionalUserDef02n()
{
var source = @"
class C
{
struct S1
{
public static bool operator ==(S1 x, S1 y)
{
System.Console.Write(""=="");
return true;
}
public static bool operator !=(S1 x, S1 y)
{
System.Console.Write(""!="");
return false;
}
}
class C1
{
public S1 Goo()
{
return new S1();
}
}
public static void Main()
{
System.Console.WriteLine(TestEq(null, new S1()));
System.Console.WriteLine(TestEq(new C1(), new S1()));
System.Console.WriteLine(TestEq(new C1(), null));
System.Console.WriteLine(TestNeq(null, new S1()));
System.Console.WriteLine(TestNeq(new C1(), new S1()));
System.Console.WriteLine(TestNeq(new C1(), null));
}
static bool TestEq(C1 c, S1? arg)
{
return c?.Goo() == arg;
}
static bool TestNeq(C1 c, S1? arg)
{
return c?.Goo() != arg;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"False
==True
False
True
!=False
True");
verifier.VerifyIL("C.TestNeq", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (C.S1 V_0,
C.S1? V_1)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000b
IL_0003: ldarga.s V_1
IL_0005: call ""bool C.S1?.HasValue.get""
IL_000a: ret
IL_000b: ldarg.0
IL_000c: call ""C.S1 C.C1.Goo()""
IL_0011: stloc.0
IL_0012: ldarg.1
IL_0013: stloc.1
IL_0014: ldloca.s V_1
IL_0016: call ""bool C.S1?.HasValue.get""
IL_001b: brtrue.s IL_001f
IL_001d: ldc.i4.1
IL_001e: ret
IL_001f: ldloc.0
IL_0020: ldloca.s V_1
IL_0022: call ""C.S1 C.S1?.GetValueOrDefault()""
IL_0027: call ""bool C.S1.op_Inequality(C.S1, C.S1)""
IL_002c: ret
}");
}
[Fact]
public void Bug1()
{
var source = @"
using System;
class Test
{
static void Main()
{
var c1 = new C1();
M1(c1);
M2(c1);
}
static void M1(C1 c1)
{
if (c1?.P == 1) Console.WriteLine(1);
}
static void M2(C1 c1)
{
if (c1 != null && c1.P == 1) Console.WriteLine(1);
}
}
class C1
{
public int P => 1;
}
";
var comp = CompileAndVerify(source, expectedOutput: @"1
1");
comp.VerifyIL("Test.M1", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0012
IL_0003: ldarg.0
IL_0004: call ""int C1.P.get""
IL_0009: ldc.i4.1
IL_000a: bne.un.s IL_0012
IL_000c: ldc.i4.1
IL_000d: call ""void System.Console.WriteLine(int)""
IL_0012: ret
}
");
comp.VerifyIL("Test.M2", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0012
IL_0003: ldarg.0
IL_0004: callvirt ""int C1.P.get""
IL_0009: ldc.i4.1
IL_000a: bne.un.s IL_0012
IL_000c: ldc.i4.1
IL_000d: call ""void System.Console.WriteLine(int)""
IL_0012: ret
}
");
}
[Fact]
public void ConditionalBoolExpr02ba()
{
var source = @"
class C
{
public static void Main()
{
System.Console.Write(NotHasLength(null, 0));
System.Console.Write(NotHasLength(null, 3));
System.Console.Write(NotHasLength(1, 2));
}
static bool NotHasLength(int? s, int len)
{
return s?.GetHashCode() + 1 != len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalse");
verifier.VerifyIL("C.NotHasLength", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brtrue.s IL_000b
IL_0009: ldc.i4.1
IL_000a: ret
IL_000b: ldarga.s V_0
IL_000d: call ""int int?.GetValueOrDefault()""
IL_0012: stloc.0
IL_0013: ldloca.s V_0
IL_0015: call ""int int.GetHashCode()""
IL_001a: ldc.i4.1
IL_001b: add
IL_001c: ldarg.1
IL_001d: ceq
IL_001f: ldc.i4.0
IL_0020: ceq
IL_0022: ret
}
");
}
[Fact]
public void ConditionalBoolExpr02bb()
{
var source = @"
class C
{
public static void Main()
{
System.Console.Write(NotHasLength(null, 0));
System.Console.Write(NotHasLength(null, 3));
System.Console.Write(NotHasLength(1, 2));
System.Console.Write(NotHasLength(null, null));
}
static bool NotHasLength(int? s, int? len)
{
return s?.GetHashCode() + 1 != len;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalseFalse");
verifier.VerifyIL("C.NotHasLength", @"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (int? V_0,
int V_1)
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brtrue.s IL_0011
IL_0009: ldarga.s V_1
IL_000b: call ""bool int?.HasValue.get""
IL_0010: ret
IL_0011: ldarga.s V_0
IL_0013: call ""int int?.GetValueOrDefault()""
IL_0018: stloc.1
IL_0019: ldloca.s V_1
IL_001b: call ""int int.GetHashCode()""
IL_0020: ldc.i4.1
IL_0021: add
IL_0022: ldarg.1
IL_0023: stloc.0
IL_0024: ldloca.s V_0
IL_0026: call ""int int?.GetValueOrDefault()""
IL_002b: ceq
IL_002d: ldloca.s V_0
IL_002f: call ""bool int?.HasValue.get""
IL_0034: and
IL_0035: ldc.i4.0
IL_0036: ceq
IL_0038: ret
}");
}
[Fact]
public void ConditionalUnary()
{
var source = @"
class C
{
public static void Main()
{
var x = - - -((string)null)?.Length ?? - - -string.Empty?.Length;
System.Console.WriteLine(x);
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0");
verifier.VerifyIL("C.Main", @"
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (int? V_0)
IL_0000: ldsfld ""string string.Empty""
IL_0005: dup
IL_0006: brtrue.s IL_0014
IL_0008: pop
IL_0009: ldloca.s V_0
IL_000b: initobj ""int?""
IL_0011: ldloc.0
IL_0012: br.s IL_0021
IL_0014: call ""int string.Length.get""
IL_0019: neg
IL_001a: neg
IL_001b: neg
IL_001c: newobj ""int?..ctor(int)""
IL_0021: box ""int?""
IL_0026: call ""void System.Console.WriteLine(object)""
IL_002b: ret
}
");
}
[WorkItem(7388, "https://github.com/dotnet/roslyn/issues/7388")]
[Fact]
public void ConditionalClassConstrained001()
{
var source = @"
using System;
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
var v = new A<object>();
System.Console.WriteLine(A<object>.Test(v));
}
public class A<T> : object where T : class
{
public T Value { get { return (T)(object)42; }}
public static T Test(A<T> val)
{
return val?.Value;
}
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"42");
verifier.VerifyIL("ConsoleApplication9.Program.A<T>.Test(ConsoleApplication9.Program.A<T>)", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""T""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldarg.0
IL_000e: call ""T ConsoleApplication9.Program.A<T>.Value.get""
IL_0013: ret
}");
}
[Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")]
public void ConditionalAccessOffOfUnconstrainedDefault1()
{
var source = @"
using System;
public class Test<T>
{
public string Run()
{
return default(T)?.ToString();
}
}
class Program
{
static void Main()
{
Console.WriteLine(""--"");
Console.WriteLine(new Test<string>().Run());
Console.WriteLine(""--"");
Console.WriteLine(new Test<int>().Run());
Console.WriteLine(""--"");
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput:
@"--
--
0
--");
verifier.VerifyIL("Test<T>.Run", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (T V_0,
string V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0014
IL_0011: ldnull
IL_0012: br.s IL_0028
IL_0014: ldloca.s V_0
IL_0016: dup
IL_0017: initobj ""T""
IL_001d: constrained. ""T""
IL_0023: callvirt ""string object.ToString()""
IL_0028: stloc.1
IL_0029: br.s IL_002b
IL_002b: ldloc.1
IL_002c: ret
}");
}
[Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")]
public void ConditionalAccessOffOfUnconstrainedDefault2()
{
var source = @"
using System;
public class Test<T>
{
public string Run()
{
var v = default(T);
return v?.ToString();
}
}
class Program
{
static void Main()
{
Console.WriteLine(""--"");
Console.WriteLine(new Test<string>().Run());
Console.WriteLine(""--"");
Console.WriteLine(new Test<int>().Run());
Console.WriteLine(""--"");
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput:
@"--
--
0
--");
verifier.VerifyIL("Test<T>.Run", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init (T V_0, //v
string V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0014
IL_0011: ldnull
IL_0012: br.s IL_0021
IL_0014: ldloca.s V_0
IL_0016: constrained. ""T""
IL_001c: callvirt ""string object.ToString()""
IL_0021: stloc.1
IL_0022: br.s IL_0024
IL_0024: ldloc.1
IL_0025: ret
}");
}
[Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")]
public void ConditionalAccessOffOfInterfaceConstrainedDefault1()
{
var source = @"
using System;
public class Test<T> where T : IComparable
{
public string Run()
{
return default(T)?.ToString();
}
}
class Program
{
static void Main()
{
Console.WriteLine(""--"");
Console.WriteLine(new Test<string>().Run());
Console.WriteLine(""--"");
Console.WriteLine(new Test<int>().Run());
Console.WriteLine(""--"");
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput:
@"--
--
0
--");
verifier.VerifyIL("Test<T>.Run", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (T V_0,
string V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0014
IL_0011: ldnull
IL_0012: br.s IL_0028
IL_0014: ldloca.s V_0
IL_0016: dup
IL_0017: initobj ""T""
IL_001d: constrained. ""T""
IL_0023: callvirt ""string object.ToString()""
IL_0028: stloc.1
IL_0029: br.s IL_002b
IL_002b: ldloc.1
IL_002c: ret
}");
}
[Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")]
public void ConditionalAccessOffOfInterfaceConstrainedDefault2()
{
var source = @"
using System;
public class Test<T> where T : IComparable
{
public string Run()
{
var v = default(T);
return v?.ToString();
}
}
class Program
{
static void Main()
{
Console.WriteLine(""--"");
Console.WriteLine(new Test<string>().Run());
Console.WriteLine(""--"");
Console.WriteLine(new Test<int>().Run());
Console.WriteLine(""--"");
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput:
@"--
--
0
--");
verifier.VerifyIL("Test<T>.Run", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init (T V_0, //v
string V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: brtrue.s IL_0014
IL_0011: ldnull
IL_0012: br.s IL_0021
IL_0014: ldloca.s V_0
IL_0016: constrained. ""T""
IL_001c: callvirt ""string object.ToString()""
IL_0021: stloc.1
IL_0022: br.s IL_0024
IL_0024: ldloc.1
IL_0025: ret
}");
}
[Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")]
public void ConditionalAccessOffOfClassConstrainedDefault1()
{
var source = @"
using System;
public class Test<T> where T : class
{
public string Run()
{
return default(T)?.ToString();
}
}
class Program
{
static void Main()
{
Console.WriteLine(""--"");
Console.WriteLine(new Test<string>().Run());
Console.WriteLine(""--"");
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput:
@"--
--");
verifier.VerifyIL("Test<T>.Run", @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (string V_0)
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.0
IL_0003: br.s IL_0005
IL_0005: ldloc.0
IL_0006: ret
}");
}
[Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")]
public void ConditionalAccessOffOfClassConstrainedDefault2()
{
var source = @"
using System;
public class Test<T> where T : class
{
public string Run()
{
var v = default(T);
return v?.ToString();
}
}
class Program
{
static void Main()
{
Console.WriteLine(""--"");
Console.WriteLine(new Test<string>().Run());
Console.WriteLine(""--"");
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput:
@"--
--");
verifier.VerifyIL("Test<T>.Run", @"
{
// Code size 32 (0x20)
.maxstack 2
.locals init (T V_0, //v
string V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj ""T""
IL_0009: ldloc.0
IL_000a: box ""T""
IL_000f: dup
IL_0010: brtrue.s IL_0016
IL_0012: pop
IL_0013: ldnull
IL_0014: br.s IL_001b
IL_0016: callvirt ""string object.ToString()""
IL_001b: stloc.1
IL_001c: br.s IL_001e
IL_001e: ldloc.1
IL_001f: ret
}");
}
[Fact]
[CompilerTrait(CompilerFeature.PEVerifyCompat)]
public void ConditionalAccessOffReadOnlyNullable1()
{
var source = @"
using System;
class Program
{
private static readonly Guid? g = null;
static void Main()
{
Console.WriteLine(g?.ToString());
}
}
";
var comp = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"", verify: Verification.Fails);
comp.VerifyIL("Program.Main", @"
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (System.Guid V_0)
IL_0000: nop
IL_0001: ldsflda ""System.Guid? Program.g""
IL_0006: dup
IL_0007: call ""bool System.Guid?.HasValue.get""
IL_000c: brtrue.s IL_0012
IL_000e: pop
IL_000f: ldnull
IL_0010: br.s IL_0025
IL_0012: call ""System.Guid System.Guid?.GetValueOrDefault()""
IL_0017: stloc.0
IL_0018: ldloca.s V_0
IL_001a: constrained. ""System.Guid""
IL_0020: callvirt ""string object.ToString()""
IL_0025: call ""void System.Console.WriteLine(string)""
IL_002a: nop
IL_002b: ret
}");
comp = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes);
comp.VerifyIL("Program.Main", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (System.Guid? V_0,
System.Guid V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Guid? Program.g""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: dup
IL_000a: call ""bool System.Guid?.HasValue.get""
IL_000f: brtrue.s IL_0015
IL_0011: pop
IL_0012: ldnull
IL_0013: br.s IL_0028
IL_0015: call ""System.Guid System.Guid?.GetValueOrDefault()""
IL_001a: stloc.1
IL_001b: ldloca.s V_1
IL_001d: constrained. ""System.Guid""
IL_0023: callvirt ""string object.ToString()""
IL_0028: call ""void System.Console.WriteLine(string)""
IL_002d: nop
IL_002e: ret
}");
}
[Fact]
public void ConditionalAccessOffReadOnlyNullable2()
{
var source = @"
using System;
class Program
{
static void Main()
{
Console.WriteLine(default(Guid?)?.ToString());
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"");
verifier.VerifyIL("Program.Main", @"
{
// Code size 55 (0x37)
.maxstack 2
.locals init (System.Guid? V_0,
System.Guid V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: dup
IL_0004: initobj ""System.Guid?""
IL_000a: call ""bool System.Guid?.HasValue.get""
IL_000f: brtrue.s IL_0014
IL_0011: ldnull
IL_0012: br.s IL_0030
IL_0014: ldloca.s V_0
IL_0016: dup
IL_0017: initobj ""System.Guid?""
IL_001d: call ""System.Guid System.Guid?.GetValueOrDefault()""
IL_0022: stloc.1
IL_0023: ldloca.s V_1
IL_0025: constrained. ""System.Guid""
IL_002b: callvirt ""string object.ToString()""
IL_0030: call ""void System.Console.WriteLine(string)""
IL_0035: nop
IL_0036: ret
}");
}
[Fact]
[WorkItem(23351, "https://github.com/dotnet/roslyn/issues/23351")]
public void ConditionalAccessOffConstrainedTypeParameter_Property()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
var obj1 = new MyObject1 { MyDate = new DateTime(636461511000000000L) };
var obj2 = new MyObject2<MyObject1>(obj1);
System.Console.WriteLine(obj1.MyDate.Ticks);
System.Console.WriteLine(obj2.CurrentDate.Value.Ticks);
System.Console.WriteLine(new MyObject2<MyObject1>(null).CurrentDate.HasValue);
}
}
abstract class MyBaseObject1
{
public DateTime MyDate { get; set; }
}
class MyObject1 : MyBaseObject1
{ }
class MyObject2<MyObjectType> where MyObjectType : MyBaseObject1, new()
{
public MyObject2(MyObjectType obj)
{
m_CurrentObject1 = obj;
}
private MyObjectType m_CurrentObject1 = null;
public MyObjectType CurrentObject1 => m_CurrentObject1;
public DateTime? CurrentDate => CurrentObject1?.MyDate;
}
";
var expectedOutput =
@"
636461511000000000
636461511000000000
False
";
CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: expectedOutput);
CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(23351, "https://github.com/dotnet/roslyn/issues/23351")]
public void ConditionalAccessOffConstrainedTypeParameter_Field()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
var obj1 = new MyObject1 { MyDate = new DateTime(636461511000000000L) };
var obj2 = new MyObject2<MyObject1>(obj1);
System.Console.WriteLine(obj1.MyDate.Ticks);
System.Console.WriteLine(obj2.CurrentDate.Value.Ticks);
System.Console.WriteLine(new MyObject2<MyObject1>(null).CurrentDate.HasValue);
}
}
abstract class MyBaseObject1
{
public DateTime MyDate;
}
class MyObject1 : MyBaseObject1
{ }
class MyObject2<MyObjectType> where MyObjectType : MyBaseObject1, new()
{
public MyObject2(MyObjectType obj)
{
m_CurrentObject1 = obj;
}
private MyObjectType m_CurrentObject1 = null;
public MyObjectType CurrentObject1 => m_CurrentObject1;
public DateTime? CurrentDate => CurrentObject1?.MyDate;
}
";
var expectedOutput =
@"
636461511000000000
636461511000000000
False
";
CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: expectedOutput);
CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput);
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/Core/Portable/Text/TextChange.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Runtime.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// Describes a single change when a particular span is replaced with a new text.
/// </summary>
[DataContract]
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public readonly struct TextChange : IEquatable<TextChange>
{
/// <summary>
/// The original span of the changed text.
/// </summary>
[DataMember(Order = 0)]
public TextSpan Span { get; }
/// <summary>
/// The new text.
/// </summary>
[DataMember(Order = 1)]
public string? NewText { get; }
/// <summary>
/// Initializes a new instance of <see cref="TextChange"/>
/// </summary>
/// <param name="span">The original span of the changed text.</param>
/// <param name="newText">The new text.</param>
public TextChange(TextSpan span, string newText)
: this()
{
if (newText == null)
{
throw new ArgumentNullException(nameof(newText));
}
this.Span = span;
this.NewText = newText;
}
/// <summary>
/// Provides a string representation for <see cref="TextChange"/>.
/// </summary>
public override string ToString()
{
return string.Format("{0}: {{ {1}, \"{2}\" }}", this.GetType().Name, Span, NewText);
}
public override bool Equals(object? obj)
{
return obj is TextChange && this.Equals((TextChange)obj);
}
public bool Equals(TextChange other)
{
return
EqualityComparer<TextSpan>.Default.Equals(this.Span, other.Span) &&
EqualityComparer<string>.Default.Equals(this.NewText, other.NewText);
}
public override int GetHashCode()
{
return Hash.Combine(this.Span.GetHashCode(), this.NewText?.GetHashCode() ?? 0);
}
public static bool operator ==(TextChange left, TextChange right)
{
return left.Equals(right);
}
public static bool operator !=(TextChange left, TextChange right)
{
return !(left == right);
}
/// <summary>
/// Converts a <see cref="TextChange"/> to a <see cref="TextChangeRange"/>.
/// </summary>
/// <param name="change"></param>
public static implicit operator TextChangeRange(TextChange change)
{
Debug.Assert(change.NewText is object);
return new TextChangeRange(change.Span, change.NewText.Length);
}
/// <summary>
/// An empty set of changes.
/// </summary>
public static IReadOnlyList<TextChange> NoChanges => SpecializedCollections.EmptyReadOnlyList<TextChange>();
internal string GetDebuggerDisplay()
{
var newTextDisplay = NewText switch
{
null => "null",
{ Length: < 10 } => $"\"{NewText}\"",
{ Length: var length } => $"(NewLength = {length})"
};
return $"new TextChange(new TextSpan({Span.Start}, {Span.Length}), {newTextDisplay})";
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Runtime.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// Describes a single change when a particular span is replaced with a new text.
/// </summary>
[DataContract]
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public readonly struct TextChange : IEquatable<TextChange>
{
/// <summary>
/// The original span of the changed text.
/// </summary>
[DataMember(Order = 0)]
public TextSpan Span { get; }
/// <summary>
/// The new text.
/// </summary>
[DataMember(Order = 1)]
public string? NewText { get; }
/// <summary>
/// Initializes a new instance of <see cref="TextChange"/>
/// </summary>
/// <param name="span">The original span of the changed text.</param>
/// <param name="newText">The new text.</param>
public TextChange(TextSpan span, string newText)
: this()
{
if (newText == null)
{
throw new ArgumentNullException(nameof(newText));
}
this.Span = span;
this.NewText = newText;
}
/// <summary>
/// Provides a string representation for <see cref="TextChange"/>.
/// </summary>
public override string ToString()
{
return string.Format("{0}: {{ {1}, \"{2}\" }}", this.GetType().Name, Span, NewText);
}
public override bool Equals(object? obj)
{
return obj is TextChange && this.Equals((TextChange)obj);
}
public bool Equals(TextChange other)
{
return
EqualityComparer<TextSpan>.Default.Equals(this.Span, other.Span) &&
EqualityComparer<string>.Default.Equals(this.NewText, other.NewText);
}
public override int GetHashCode()
{
return Hash.Combine(this.Span.GetHashCode(), this.NewText?.GetHashCode() ?? 0);
}
public static bool operator ==(TextChange left, TextChange right)
{
return left.Equals(right);
}
public static bool operator !=(TextChange left, TextChange right)
{
return !(left == right);
}
/// <summary>
/// Converts a <see cref="TextChange"/> to a <see cref="TextChangeRange"/>.
/// </summary>
/// <param name="change"></param>
public static implicit operator TextChangeRange(TextChange change)
{
Debug.Assert(change.NewText is object);
return new TextChangeRange(change.Span, change.NewText.Length);
}
/// <summary>
/// An empty set of changes.
/// </summary>
public static IReadOnlyList<TextChange> NoChanges => SpecializedCollections.EmptyReadOnlyList<TextChange>();
internal string GetDebuggerDisplay()
{
var newTextDisplay = NewText switch
{
null => "null",
{ Length: < 10 } => $"\"{NewText}\"",
{ Length: var length } => $"(NewLength = {length})"
};
return $"new TextChange(new TextSpan({Span.Start}, {Span.Length}), {newTextDisplay})";
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Workspaces/Core/Portable/ExtensionManager/IInfoBarService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Extensions
{
internal interface IInfoBarService : IWorkspaceService
{
/// <summary>
/// Show global info bar
/// </summary>
void ShowInfoBar(string message, params InfoBarUI[] items);
}
internal struct InfoBarUI
{
public readonly string? Title;
public readonly UIKind Kind;
public readonly Action Action;
public readonly bool CloseAfterAction;
public InfoBarUI(string title, UIKind kind, Action action, bool closeAfterAction = true)
{
Contract.ThrowIfNull(title);
Title = title;
Kind = kind;
Action = action;
CloseAfterAction = closeAfterAction;
}
[MemberNotNullWhen(false, nameof(Title))]
public bool IsDefault => Title == null;
internal enum UIKind
{
Button,
HyperLink,
Close
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Extensions
{
internal interface IInfoBarService : IWorkspaceService
{
/// <summary>
/// Show global info bar
/// </summary>
void ShowInfoBar(string message, params InfoBarUI[] items);
}
internal struct InfoBarUI
{
public readonly string? Title;
public readonly UIKind Kind;
public readonly Action Action;
public readonly bool CloseAfterAction;
public InfoBarUI(string title, UIKind kind, Action action, bool closeAfterAction = true)
{
Contract.ThrowIfNull(title);
Title = title;
Kind = kind;
Action = action;
CloseAfterAction = closeAfterAction;
}
[MemberNotNullWhen(false, nameof(Title))]
public bool IsDefault => Title == null;
internal enum UIKind
{
Button,
HyperLink,
Close
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/Core/CodeAnalysisTest/Collections/List/ICollection.NonGeneric.Tests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Collections/ICollection.NonGeneric.Tests.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
/// <summary>
/// Contains tests that ensure the correctness of any class that implements the nongeneric
/// ICollection interface
/// </summary>
public abstract class ICollection_NonGeneric_Tests : IEnumerable_NonGeneric_Tests
{
#region Helper methods
/// <summary>
/// Creates an instance of an ICollection that can be used for testing.
/// </summary>
/// <returns>An instance of an ICollection that can be used for testing.</returns>
protected abstract ICollection NonGenericICollectionFactory();
/// <summary>
/// Creates an instance of an ICollection that can be used for testing.
/// </summary>
/// <param name="count">The number of unique items that the returned ICollection contains.</param>
/// <returns>An instance of an ICollection that can be used for testing.</returns>
protected virtual ICollection NonGenericICollectionFactory(int count)
{
ICollection collection = NonGenericICollectionFactory();
AddToCollection(collection, count);
return collection;
}
protected virtual bool DuplicateValuesAllowed => true;
protected virtual bool IsReadOnly => false;
protected virtual bool NullAllowed => true;
protected virtual bool ExpectedIsSynchronized => false;
protected virtual IEnumerable<object?> InvalidValues => new object?[0];
protected abstract void AddToCollection(ICollection collection, int numberOfItemsToAdd);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_ArrayOfEnumType test where we try to call CopyTo
/// on an Array of Enum values. Some implementations special-case for this and throw an ArgumentException,
/// while others just throw an InvalidCastExcepton.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType => typeof(InvalidCastException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType test where we try to call CopyTo
/// on an Array of different reference values. Some implementations special-case for this and throw an ArgumentException,
/// while others just throw an InvalidCastExcepton or an ArrayTypeMismatchException.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType test where we try to call CopyTo
/// on an Array of different value values. Some implementations special-case for this and throw an ArgumentException,
/// while others just throw an InvalidCastExcepton.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_NonZeroLowerBound test where we try to call CopyTo
/// on an Array of with a non-zero lower bound.
/// Most implementations throw an ArgumentException, but others (e.g. SortedList) throw
/// an ArgumentOutOfRangeException.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_NonZeroLowerBound_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for ICollection_NonGeneric_SyncRoot tests. Some implementations (e.g. ConcurrentDictionary)
/// don't support the SyncRoot property of an ICollection and throw a NotSupportedException.
/// </summary>
protected virtual bool ICollection_NonGeneric_SupportsSyncRoot => true;
/// <summary>
/// Used for ICollection_NonGeneric_SyncRoot tests. Some implementations (e.g. TempFileCollection)
/// return null for the SyncRoot property of an ICollection.
/// </summary>
protected virtual bool ICollection_NonGeneric_HasNullSyncRoot => false;
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowsArgumentException tests. Some
/// implementations throw a different exception type (e.g. ArgumentOutOfRangeException).
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowsException test. Some implementations
/// throw a different exception type (e.g. RankException by ImmutableArray)
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowType => typeof(ArgumentException);
#endregion
#region IEnumerable Helper Methods
protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new List<ModifyEnumerable>();
protected override IEnumerable NonGenericIEnumerableFactory(int count) => NonGenericICollectionFactory(count);
#endregion
#region Count
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_Count_Validity(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Equal(count, collection.Count);
}
#endregion
#region IsSynchronized
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_IsSynchronized(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Equal(ExpectedIsSynchronized, collection.IsSynchronized);
}
#endregion
#region SyncRoot
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_SyncRoot(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
if (ICollection_NonGeneric_SupportsSyncRoot)
{
Assert.Equal(ICollection_NonGeneric_HasNullSyncRoot, collection.SyncRoot == null);
Assert.Same(collection.SyncRoot, collection.SyncRoot);
}
else
{
Assert.Throws<NotSupportedException>(() => collection.SyncRoot);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_SyncRootUnique(int count)
{
if (ICollection_NonGeneric_SupportsSyncRoot && !ICollection_NonGeneric_HasNullSyncRoot)
{
ICollection collection1 = NonGenericICollectionFactory(count);
ICollection collection2 = NonGenericICollectionFactory(count);
Assert.NotSame(collection1.SyncRoot, collection2.SyncRoot);
}
}
#endregion
#region CopyTo
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_NullArray_ThrowsArgumentNullException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null!, 0));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowsException(int count)
{
if (count > 0)
{
ICollection collection = NonGenericICollectionFactory(count);
Array arr = new object[count, count];
Assert.Equal(2, arr.Rank);
Assert.Throws(ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowType, () => collection.CopyTo(arr, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_NonZeroLowerBound(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Array arr = Array.CreateInstance(typeof(object), new int[1] { count }, new int[1] { 2 });
Assert.Equal(1, arr.Rank);
Assert.Equal(2, arr.GetLowerBound(0));
Assert.Throws(ICollection_NonGeneric_CopyTo_NonZeroLowerBound_ThrowType, () => collection.CopyTo(arr, 0));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType(int count)
{
if (count > 0)
{
ICollection collection = NonGenericICollectionFactory(count);
float[] array = new float[count * 3 / 2];
Assert.Throws(ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType_ThrowType, () => collection.CopyTo(array, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType(int count)
{
if (count > 0)
{
ICollection collection = NonGenericICollectionFactory(count);
StringBuilder[] array = new StringBuilder[count * 3 / 2];
Assert.Throws(ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType, () => collection.CopyTo(array, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_ArrayOfEnumType(int count)
{
Array enumArr = Enum.GetValues(typeof(EnumerableType));
if (count > 0 && count < enumArr.Length)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Throws(ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType, () => collection.CopyTo(enumArr, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_NegativeIndex_ThrowsArgumentOutOfRangeException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(array, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(array, int.MinValue));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_IndexEqualToArrayCount_ThrowsArgumentException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
if (count > 0)
Assert.Throws<ArgumentException>(() => collection.CopyTo(array, count));
else
collection.CopyTo(array, count); // does nothing since the array is empty
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowsAnyArgumentException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
Assert.Throws(ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType, () => collection.CopyTo(array, count + 1));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_NotEnoughSpaceInOffsettedArray_ThrowsArgumentException(int count)
{
if (count > 0) // Want the T array to have at least 1 element
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
Assert.Throws<ArgumentException>(() => collection.CopyTo(array, 1));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ExactlyEnoughSpaceInArray(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.Equal(array[i++], obj);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ArrayIsLargerThanCollection(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count * 3 / 2];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.Equal(array[i++], obj);
}
#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.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Collections/ICollection.NonGeneric.Tests.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
/// <summary>
/// Contains tests that ensure the correctness of any class that implements the nongeneric
/// ICollection interface
/// </summary>
public abstract class ICollection_NonGeneric_Tests : IEnumerable_NonGeneric_Tests
{
#region Helper methods
/// <summary>
/// Creates an instance of an ICollection that can be used for testing.
/// </summary>
/// <returns>An instance of an ICollection that can be used for testing.</returns>
protected abstract ICollection NonGenericICollectionFactory();
/// <summary>
/// Creates an instance of an ICollection that can be used for testing.
/// </summary>
/// <param name="count">The number of unique items that the returned ICollection contains.</param>
/// <returns>An instance of an ICollection that can be used for testing.</returns>
protected virtual ICollection NonGenericICollectionFactory(int count)
{
ICollection collection = NonGenericICollectionFactory();
AddToCollection(collection, count);
return collection;
}
protected virtual bool DuplicateValuesAllowed => true;
protected virtual bool IsReadOnly => false;
protected virtual bool NullAllowed => true;
protected virtual bool ExpectedIsSynchronized => false;
protected virtual IEnumerable<object?> InvalidValues => new object?[0];
protected abstract void AddToCollection(ICollection collection, int numberOfItemsToAdd);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_ArrayOfEnumType test where we try to call CopyTo
/// on an Array of Enum values. Some implementations special-case for this and throw an ArgumentException,
/// while others just throw an InvalidCastExcepton.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType => typeof(InvalidCastException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType test where we try to call CopyTo
/// on an Array of different reference values. Some implementations special-case for this and throw an ArgumentException,
/// while others just throw an InvalidCastExcepton or an ArrayTypeMismatchException.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType test where we try to call CopyTo
/// on an Array of different value values. Some implementations special-case for this and throw an ArgumentException,
/// while others just throw an InvalidCastExcepton.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_NonZeroLowerBound test where we try to call CopyTo
/// on an Array of with a non-zero lower bound.
/// Most implementations throw an ArgumentException, but others (e.g. SortedList) throw
/// an ArgumentOutOfRangeException.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_NonZeroLowerBound_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for ICollection_NonGeneric_SyncRoot tests. Some implementations (e.g. ConcurrentDictionary)
/// don't support the SyncRoot property of an ICollection and throw a NotSupportedException.
/// </summary>
protected virtual bool ICollection_NonGeneric_SupportsSyncRoot => true;
/// <summary>
/// Used for ICollection_NonGeneric_SyncRoot tests. Some implementations (e.g. TempFileCollection)
/// return null for the SyncRoot property of an ICollection.
/// </summary>
protected virtual bool ICollection_NonGeneric_HasNullSyncRoot => false;
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowsArgumentException tests. Some
/// implementations throw a different exception type (e.g. ArgumentOutOfRangeException).
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowsException test. Some implementations
/// throw a different exception type (e.g. RankException by ImmutableArray)
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowType => typeof(ArgumentException);
#endregion
#region IEnumerable Helper Methods
protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new List<ModifyEnumerable>();
protected override IEnumerable NonGenericIEnumerableFactory(int count) => NonGenericICollectionFactory(count);
#endregion
#region Count
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_Count_Validity(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Equal(count, collection.Count);
}
#endregion
#region IsSynchronized
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_IsSynchronized(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Equal(ExpectedIsSynchronized, collection.IsSynchronized);
}
#endregion
#region SyncRoot
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_SyncRoot(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
if (ICollection_NonGeneric_SupportsSyncRoot)
{
Assert.Equal(ICollection_NonGeneric_HasNullSyncRoot, collection.SyncRoot == null);
Assert.Same(collection.SyncRoot, collection.SyncRoot);
}
else
{
Assert.Throws<NotSupportedException>(() => collection.SyncRoot);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_SyncRootUnique(int count)
{
if (ICollection_NonGeneric_SupportsSyncRoot && !ICollection_NonGeneric_HasNullSyncRoot)
{
ICollection collection1 = NonGenericICollectionFactory(count);
ICollection collection2 = NonGenericICollectionFactory(count);
Assert.NotSame(collection1.SyncRoot, collection2.SyncRoot);
}
}
#endregion
#region CopyTo
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_NullArray_ThrowsArgumentNullException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null!, 0));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowsException(int count)
{
if (count > 0)
{
ICollection collection = NonGenericICollectionFactory(count);
Array arr = new object[count, count];
Assert.Equal(2, arr.Rank);
Assert.Throws(ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowType, () => collection.CopyTo(arr, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_NonZeroLowerBound(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Array arr = Array.CreateInstance(typeof(object), new int[1] { count }, new int[1] { 2 });
Assert.Equal(1, arr.Rank);
Assert.Equal(2, arr.GetLowerBound(0));
Assert.Throws(ICollection_NonGeneric_CopyTo_NonZeroLowerBound_ThrowType, () => collection.CopyTo(arr, 0));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType(int count)
{
if (count > 0)
{
ICollection collection = NonGenericICollectionFactory(count);
float[] array = new float[count * 3 / 2];
Assert.Throws(ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType_ThrowType, () => collection.CopyTo(array, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType(int count)
{
if (count > 0)
{
ICollection collection = NonGenericICollectionFactory(count);
StringBuilder[] array = new StringBuilder[count * 3 / 2];
Assert.Throws(ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType, () => collection.CopyTo(array, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_ArrayOfEnumType(int count)
{
Array enumArr = Enum.GetValues(typeof(EnumerableType));
if (count > 0 && count < enumArr.Length)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Throws(ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType, () => collection.CopyTo(enumArr, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_NegativeIndex_ThrowsArgumentOutOfRangeException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(array, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(array, int.MinValue));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_IndexEqualToArrayCount_ThrowsArgumentException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
if (count > 0)
Assert.Throws<ArgumentException>(() => collection.CopyTo(array, count));
else
collection.CopyTo(array, count); // does nothing since the array is empty
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowsAnyArgumentException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
Assert.Throws(ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType, () => collection.CopyTo(array, count + 1));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_NotEnoughSpaceInOffsettedArray_ThrowsArgumentException(int count)
{
if (count > 0) // Want the T array to have at least 1 element
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
Assert.Throws<ArgumentException>(() => collection.CopyTo(array, 1));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ExactlyEnoughSpaceInArray(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.Equal(array[i++], obj);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ArrayIsLargerThanCollection(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count * 3 / 2];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.Equal(array[i++], obj);
}
#endregion
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActions/SuggestedAction.CaretPositionRestorer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal partial class SuggestedAction
{
internal class CaretPositionRestorer : IDisposable
{
// Bug 5535: By default the standard editor caret is set to have positive affinity. This
// means that if text is added right at the caret then the caret moves to the right and
// is placed after the added text. However, we don't want that. Instead, we want the
// caret to stay where it started at. So we store the caret position here and
// restore it afterwards.
private readonly EventHandler<CaretPositionChangedEventArgs> _caretPositionChangedHandler;
private readonly IList<Tuple<ITextView, IMappingPoint>> _caretPositions;
private readonly ITextBuffer _subjectBuffer;
private readonly ITextBufferAssociatedViewService _associatedViewService;
private bool _caretChanged;
public CaretPositionRestorer(ITextBuffer subjectBuffer, ITextBufferAssociatedViewService associatedViewService)
{
Contract.ThrowIfNull(associatedViewService);
_subjectBuffer = subjectBuffer;
_caretPositionChangedHandler = (s, e) => _caretChanged = true;
_associatedViewService = associatedViewService;
_caretPositions = GetCaretPositions();
}
private IList<Tuple<ITextView, IMappingPoint>> GetCaretPositions()
{
// Currently, only do this if there's a single view
var views = _associatedViewService.GetAssociatedTextViews(_subjectBuffer);
var result = new List<Tuple<ITextView, IMappingPoint>>();
foreach (var view in views)
{
view.Caret.PositionChanged += _caretPositionChangedHandler;
var point = view.GetCaretPoint(_subjectBuffer);
if (point != null)
{
result.Add(Tuple.Create(view, view.BufferGraph.CreateMappingPoint(point.Value, PointTrackingMode.Negative)));
}
}
return result;
}
private void RestoreCaretPositions()
{
if (_caretChanged)
{
return;
}
foreach (var tuple in _caretPositions)
{
var position = tuple.Item1.GetCaretPoint(_subjectBuffer);
if (position != null)
{
var view = tuple.Item1;
if (!view.IsClosed)
{
view.TryMoveCaretToAndEnsureVisible(position.Value);
}
}
}
}
public void Dispose()
{
RestoreCaretPositions();
foreach (var tuple in _caretPositions)
{
tuple.Item1.Caret.PositionChanged -= _caretPositionChangedHandler;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal partial class SuggestedAction
{
internal class CaretPositionRestorer : IDisposable
{
// Bug 5535: By default the standard editor caret is set to have positive affinity. This
// means that if text is added right at the caret then the caret moves to the right and
// is placed after the added text. However, we don't want that. Instead, we want the
// caret to stay where it started at. So we store the caret position here and
// restore it afterwards.
private readonly EventHandler<CaretPositionChangedEventArgs> _caretPositionChangedHandler;
private readonly IList<Tuple<ITextView, IMappingPoint>> _caretPositions;
private readonly ITextBuffer _subjectBuffer;
private readonly ITextBufferAssociatedViewService _associatedViewService;
private bool _caretChanged;
public CaretPositionRestorer(ITextBuffer subjectBuffer, ITextBufferAssociatedViewService associatedViewService)
{
Contract.ThrowIfNull(associatedViewService);
_subjectBuffer = subjectBuffer;
_caretPositionChangedHandler = (s, e) => _caretChanged = true;
_associatedViewService = associatedViewService;
_caretPositions = GetCaretPositions();
}
private IList<Tuple<ITextView, IMappingPoint>> GetCaretPositions()
{
// Currently, only do this if there's a single view
var views = _associatedViewService.GetAssociatedTextViews(_subjectBuffer);
var result = new List<Tuple<ITextView, IMappingPoint>>();
foreach (var view in views)
{
view.Caret.PositionChanged += _caretPositionChangedHandler;
var point = view.GetCaretPoint(_subjectBuffer);
if (point != null)
{
result.Add(Tuple.Create(view, view.BufferGraph.CreateMappingPoint(point.Value, PointTrackingMode.Negative)));
}
}
return result;
}
private void RestoreCaretPositions()
{
if (_caretChanged)
{
return;
}
foreach (var tuple in _caretPositions)
{
var position = tuple.Item1.GetCaretPoint(_subjectBuffer);
if (position != null)
{
var view = tuple.Item1;
if (!view.IsClosed)
{
view.TryMoveCaretToAndEnsureVisible(position.Value);
}
}
}
}
public void Dispose()
{
RestoreCaretPositions();
foreach (var tuple in _caretPositions)
{
tuple.Item1.Caret.PositionChanged -= _caretPositionChangedHandler;
}
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Features/CSharp/Portable/Debugging/BreakpointResolver.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Debugging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Debugging
{
internal class BreakpointResolver : AbstractBreakpointResolver
{
public BreakpointResolver(Solution solution, string text)
: base(solution, text, LanguageNames.CSharp, EqualityComparer<string>.Default)
{
}
protected override IEnumerable<ISymbol> GetMembers(INamedTypeSymbol type, string name)
{
var members = type.GetMembers()
.Where(m => m.Name == name ||
m.ExplicitInterfaceImplementations()
.Where(i => i.Name == name)
.Any());
return (type.Name == name) ? members.Concat(type.Constructors) : members;
}
protected override bool HasMethodBody(IMethodSymbol method, CancellationToken cancellationToken)
{
var location = method.Locations.First(loc => loc.IsInSource);
var tree = location.SourceTree;
var token = tree.GetRoot(cancellationToken).FindToken(location.SourceSpan.Start);
return token.GetAncestor<MemberDeclarationSyntax>().GetBody() != null;
}
protected override void ParseText(
out IList<NameAndArity> nameParts,
out int? parameterCount)
{
var text = Text;
Debug.Assert(text != null);
var name = SyntaxFactory.ParseName(text, consumeFullText: false);
var lengthOfParsedText = name.FullSpan.End;
var parameterList = SyntaxFactory.ParseParameterList(text, lengthOfParsedText, consumeFullText: false);
var foundIncompleteParameterList = false;
parameterCount = null;
if (!parameterList.IsMissing)
{
if (parameterList.OpenParenToken.IsMissing || parameterList.CloseParenToken.IsMissing)
{
foundIncompleteParameterList = true;
}
else
{
lengthOfParsedText += parameterList.FullSpan.End;
parameterCount = parameterList.Parameters.Count;
}
}
// If there is remaining text to parse, attempt to eat a trailing semicolon.
if (lengthOfParsedText < text.Length)
{
var token = SyntaxFactory.ParseToken(text, lengthOfParsedText);
if (token.IsKind(SyntaxKind.SemicolonToken))
{
lengthOfParsedText += token.FullSpan.End;
}
}
// It's not obvious, but this method can handle the case where name "IsMissing" (no suitable name was be parsed).
var parts = name.GetNameParts();
// If we could not parse a valid parameter list or there was additional trailing text that could not be
// interpreted, don't return any names or parameters.
// Also, "Break at Function" doesn't seem to support alias qualified names with the old language service,
// and aliases don't seem meaningful for the purposes of resolving symbols from source. Since we don't
// have precedent or a clear user scenario, we won't resolve any alias qualified names (alias qualified
// parameters are accepted, but we still only validate parameter count, similar to the old implementation).
if (!foundIncompleteParameterList && (lengthOfParsedText == text.Length) &&
!parts.Any(p => p.IsKind(SyntaxKind.AliasQualifiedName)))
{
nameParts = parts.Cast<SimpleNameSyntax>().Select(p => new NameAndArity(p.Identifier.ValueText, p.Arity)).ToList();
}
else
{
nameParts = SpecializedCollections.EmptyList<NameAndArity>();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Debugging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Debugging
{
internal class BreakpointResolver : AbstractBreakpointResolver
{
public BreakpointResolver(Solution solution, string text)
: base(solution, text, LanguageNames.CSharp, EqualityComparer<string>.Default)
{
}
protected override IEnumerable<ISymbol> GetMembers(INamedTypeSymbol type, string name)
{
var members = type.GetMembers()
.Where(m => m.Name == name ||
m.ExplicitInterfaceImplementations()
.Where(i => i.Name == name)
.Any());
return (type.Name == name) ? members.Concat(type.Constructors) : members;
}
protected override bool HasMethodBody(IMethodSymbol method, CancellationToken cancellationToken)
{
var location = method.Locations.First(loc => loc.IsInSource);
var tree = location.SourceTree;
var token = tree.GetRoot(cancellationToken).FindToken(location.SourceSpan.Start);
return token.GetAncestor<MemberDeclarationSyntax>().GetBody() != null;
}
protected override void ParseText(
out IList<NameAndArity> nameParts,
out int? parameterCount)
{
var text = Text;
Debug.Assert(text != null);
var name = SyntaxFactory.ParseName(text, consumeFullText: false);
var lengthOfParsedText = name.FullSpan.End;
var parameterList = SyntaxFactory.ParseParameterList(text, lengthOfParsedText, consumeFullText: false);
var foundIncompleteParameterList = false;
parameterCount = null;
if (!parameterList.IsMissing)
{
if (parameterList.OpenParenToken.IsMissing || parameterList.CloseParenToken.IsMissing)
{
foundIncompleteParameterList = true;
}
else
{
lengthOfParsedText += parameterList.FullSpan.End;
parameterCount = parameterList.Parameters.Count;
}
}
// If there is remaining text to parse, attempt to eat a trailing semicolon.
if (lengthOfParsedText < text.Length)
{
var token = SyntaxFactory.ParseToken(text, lengthOfParsedText);
if (token.IsKind(SyntaxKind.SemicolonToken))
{
lengthOfParsedText += token.FullSpan.End;
}
}
// It's not obvious, but this method can handle the case where name "IsMissing" (no suitable name was be parsed).
var parts = name.GetNameParts();
// If we could not parse a valid parameter list or there was additional trailing text that could not be
// interpreted, don't return any names or parameters.
// Also, "Break at Function" doesn't seem to support alias qualified names with the old language service,
// and aliases don't seem meaningful for the purposes of resolving symbols from source. Since we don't
// have precedent or a clear user scenario, we won't resolve any alias qualified names (alias qualified
// parameters are accepted, but we still only validate parameter count, similar to the old implementation).
if (!foundIncompleteParameterList && (lengthOfParsedText == text.Length) &&
!parts.Any(p => p.IsKind(SyntaxKind.AliasQualifiedName)))
{
nameParts = parts.Cast<SimpleNameSyntax>().Select(p => new NameAndArity(p.Identifier.ValueText, p.Arity)).ToList();
}
else
{
nameParts = SpecializedCollections.EmptyList<NameAndArity>();
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/CSharp/Portable/Symbols/Metadata/PE/MemberRefMetadataDecoder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection.Metadata;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE
{
/// <summary>
/// This subclass of MetadataDecoder is specifically for finding
/// method symbols corresponding to method MemberRefs. The parent
/// implementation is unsuitable because it requires a PEMethodSymbol
/// for context when decoding method type parameters and no such
/// context is available because it is precisely what we are trying
/// to find. Since we know in advance that there will be no context
/// and that signatures decoded with this class will only be used
/// for comparison (when searching through the methods of a known
/// TypeSymbol), we can return indexed type parameters instead.
/// </summary>
internal sealed class MemberRefMetadataDecoder : MetadataDecoder
{
/// <summary>
/// Type context for resolving generic type parameters.
/// </summary>
private readonly TypeSymbol _containingType;
public MemberRefMetadataDecoder(
PEModuleSymbol moduleSymbol,
TypeSymbol containingType) :
base(moduleSymbol, containingType as PENamedTypeSymbol)
{
Debug.Assert((object)containingType != null);
_containingType = containingType;
}
/// <summary>
/// We know that we'll never have a method context because that's what we're
/// trying to find. Instead, just return an indexed type parameter that will
/// make comparison easier.
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
protected override TypeSymbol GetGenericMethodTypeParamSymbol(int position)
{
// Note: technically this is a source symbol, but we only care about the position
return IndexedTypeParameterSymbol.GetTypeParameter(position);
}
/// <summary>
/// This override can handle non-PE types.
/// </summary>
protected override TypeSymbol GetGenericTypeParamSymbol(int position)
{
PENamedTypeSymbol peType = _containingType as PENamedTypeSymbol;
if ((object)peType != null)
{
return base.GetGenericTypeParamSymbol(position);
}
NamedTypeSymbol namedType = _containingType as NamedTypeSymbol;
if ((object)namedType != null)
{
int cumulativeArity;
TypeParameterSymbol typeParameter;
GetGenericTypeParameterSymbol(position, namedType, out cumulativeArity, out typeParameter);
if ((object)typeParameter != null)
{
return typeParameter;
}
else
{
Debug.Assert(cumulativeArity <= position);
return new UnsupportedMetadataTypeSymbol(); // position of type parameter too large
}
}
return new UnsupportedMetadataTypeSymbol(); // associated type does not have type parameters
}
private static void GetGenericTypeParameterSymbol(int position, NamedTypeSymbol namedType, out int cumulativeArity, out TypeParameterSymbol typeArgument)
{
cumulativeArity = namedType.Arity;
typeArgument = null;
int arityOffset = 0;
var containingType = namedType.ContainingType;
if ((object)containingType != null)
{
int containingTypeCumulativeArity;
GetGenericTypeParameterSymbol(position, containingType, out containingTypeCumulativeArity, out typeArgument);
cumulativeArity += containingTypeCumulativeArity;
arityOffset = containingTypeCumulativeArity;
}
if (arityOffset <= position && position < cumulativeArity)
{
Debug.Assert((object)typeArgument == null);
typeArgument = namedType.TypeParameters[position - arityOffset];
}
}
/// <summary>
/// Search through the members of the <see cref="_containingType"/> type symbol to find the method that matches a particular
/// signature.
/// </summary>
/// <param name="memberRef">A MemberRef handle that can be used to obtain the name and signature of the method</param>
/// <param name="methodsOnly">True to only return a method.</param>
/// <returns>The matching method symbol, or null if the inputs do not correspond to a valid method.</returns>
internal Symbol FindMember(MemberReferenceHandle memberRef, bool methodsOnly)
{
try
{
string memberName = Module.GetMemberRefNameOrThrow(memberRef);
BlobHandle signatureHandle = Module.GetSignatureOrThrow(memberRef);
SignatureHeader signatureHeader;
BlobReader signaturePointer = this.DecodeSignatureHeaderOrThrow(signatureHandle, out signatureHeader);
switch (signatureHeader.RawValue & SignatureHeader.CallingConventionOrKindMask)
{
case (byte)SignatureCallingConvention.Default:
case (byte)SignatureCallingConvention.VarArgs:
int typeParamCount;
ParamInfo<TypeSymbol>[] targetParamInfo = this.DecodeSignatureParametersOrThrow(ref signaturePointer, signatureHeader, out typeParamCount);
return FindMethodBySignature(_containingType, memberName, signatureHeader, typeParamCount, targetParamInfo);
case (byte)SignatureKind.Field:
if (methodsOnly)
{
// skip:
return null;
}
ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers;
TypeSymbol type = this.DecodeFieldSignature(ref signaturePointer, out customModifiers);
return FindFieldBySignature(_containingType, memberName, customModifiers, type);
default:
// error: unexpected calling convention
return null;
}
}
catch (BadImageFormatException)
{
return null;
}
}
private static FieldSymbol FindFieldBySignature(TypeSymbol targetTypeSymbol, string targetMemberName, ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers, TypeSymbol type)
{
foreach (Symbol member in targetTypeSymbol.GetMembers(targetMemberName))
{
var field = member as FieldSymbol;
TypeWithAnnotations fieldType;
if ((object)field != null &&
TypeSymbol.Equals((fieldType = field.TypeWithAnnotations).Type, type, TypeCompareKind.CLRSignatureCompareOptions) &&
CustomModifiersMatch(fieldType.CustomModifiers, customModifiers))
{
// Behavior in the face of multiple matching signatures is
// implementation defined - we'll just pick the first one.
return field;
}
}
return null;
}
private static MethodSymbol FindMethodBySignature(TypeSymbol targetTypeSymbol, string targetMemberName, SignatureHeader targetMemberSignatureHeader, int targetMemberTypeParamCount, ParamInfo<TypeSymbol>[] targetParamInfo)
{
foreach (Symbol member in targetTypeSymbol.GetMembers(targetMemberName))
{
var method = member as MethodSymbol;
if ((object)method != null &&
((byte)method.CallingConvention == targetMemberSignatureHeader.RawValue) &&
(targetMemberTypeParamCount == method.Arity) &&
MethodSymbolMatchesParamInfo(method, targetParamInfo))
{
// Behavior in the face of multiple matching signatures is
// implementation defined - we'll just pick the first one.
return method;
}
}
return null;
}
private static bool MethodSymbolMatchesParamInfo(MethodSymbol candidateMethod, ParamInfo<TypeSymbol>[] targetParamInfo)
{
int numParams = targetParamInfo.Length - 1; //don't count return type
if (candidateMethod.ParameterCount != numParams)
{
return false;
}
// IndexedTypeParameterSymbol is not going to be exposed anywhere,
// so we'll cheat and use it here for comparison purposes.
TypeMap candidateMethodTypeMap = new TypeMap(
candidateMethod.TypeParameters,
IndexedTypeParameterSymbol.Take(candidateMethod.Arity), true);
if (!ReturnTypesMatch(candidateMethod, candidateMethodTypeMap, ref targetParamInfo[0]))
{
return false;
}
for (int i = 0; i < numParams; i++)
{
if (!ParametersMatch(candidateMethod.Parameters[i], candidateMethodTypeMap, ref targetParamInfo[i + 1 /*for return type*/]))
{
return false;
}
}
return true;
}
private static bool ParametersMatch(ParameterSymbol candidateParam, TypeMap candidateMethodTypeMap, ref ParamInfo<TypeSymbol> targetParam)
{
Debug.Assert(candidateMethodTypeMap != null);
// This could be combined into a single return statement with a more complicated expression, but that would
// be harder to debug.
if ((candidateParam.RefKind != RefKind.None) != targetParam.IsByRef)
{
return false;
}
// CONSIDER: Do we want to add special handling for error types? Right now, we expect they'll just fail to match.
var substituted = candidateParam.TypeWithAnnotations.SubstituteType(candidateMethodTypeMap);
if (!TypeSymbol.Equals(substituted.Type, targetParam.Type, TypeCompareKind.CLRSignatureCompareOptions))
{
return false;
}
if (!CustomModifiersMatch(substituted.CustomModifiers, targetParam.CustomModifiers) ||
!CustomModifiersMatch(candidateMethodTypeMap.SubstituteCustomModifiers(candidateParam.RefCustomModifiers), targetParam.RefCustomModifiers))
{
return false;
}
return true;
}
private static bool ReturnTypesMatch(MethodSymbol candidateMethod, TypeMap candidateMethodTypeMap, ref ParamInfo<TypeSymbol> targetReturnParam)
{
Debug.Assert(candidateMethodTypeMap != null);
if (candidateMethod.ReturnsByRef != targetReturnParam.IsByRef)
{
return false;
}
TypeWithAnnotations candidateMethodType = candidateMethod.ReturnTypeWithAnnotations;
TypeSymbol targetReturnType = targetReturnParam.Type;
// CONSIDER: Do we want to add special handling for error types? Right now, we expect they'll just fail to match.
var substituted = candidateMethodType.SubstituteType(candidateMethodTypeMap);
if (!TypeSymbol.Equals(substituted.Type, targetReturnType, TypeCompareKind.CLRSignatureCompareOptions))
{
return false;
}
if (!CustomModifiersMatch(substituted.CustomModifiers, targetReturnParam.CustomModifiers) ||
!CustomModifiersMatch(candidateMethodTypeMap.SubstituteCustomModifiers(candidateMethod.RefCustomModifiers), targetReturnParam.RefCustomModifiers))
{
return false;
}
return true;
}
private static bool CustomModifiersMatch(ImmutableArray<CustomModifier> candidateCustomModifiers, ImmutableArray<ModifierInfo<TypeSymbol>> targetCustomModifiers)
{
if (targetCustomModifiers.IsDefault || targetCustomModifiers.IsEmpty)
{
return candidateCustomModifiers.IsDefault || candidateCustomModifiers.IsEmpty;
}
else if (candidateCustomModifiers.IsDefault)
{
return false;
}
var n = candidateCustomModifiers.Length;
if (targetCustomModifiers.Length != n)
{
return false;
}
for (int i = 0; i < n; i++)
{
var targetCustomModifier = targetCustomModifiers[i];
CustomModifier candidateCustomModifier = candidateCustomModifiers[i];
if (targetCustomModifier.IsOptional != candidateCustomModifier.IsOptional ||
!object.Equals(targetCustomModifier.Modifier, ((CSharpCustomModifier)candidateCustomModifier).ModifierSymbol))
{
return false;
}
}
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE
{
/// <summary>
/// This subclass of MetadataDecoder is specifically for finding
/// method symbols corresponding to method MemberRefs. The parent
/// implementation is unsuitable because it requires a PEMethodSymbol
/// for context when decoding method type parameters and no such
/// context is available because it is precisely what we are trying
/// to find. Since we know in advance that there will be no context
/// and that signatures decoded with this class will only be used
/// for comparison (when searching through the methods of a known
/// TypeSymbol), we can return indexed type parameters instead.
/// </summary>
internal sealed class MemberRefMetadataDecoder : MetadataDecoder
{
/// <summary>
/// Type context for resolving generic type parameters.
/// </summary>
private readonly TypeSymbol _containingType;
public MemberRefMetadataDecoder(
PEModuleSymbol moduleSymbol,
TypeSymbol containingType) :
base(moduleSymbol, containingType as PENamedTypeSymbol)
{
Debug.Assert((object)containingType != null);
_containingType = containingType;
}
/// <summary>
/// We know that we'll never have a method context because that's what we're
/// trying to find. Instead, just return an indexed type parameter that will
/// make comparison easier.
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
protected override TypeSymbol GetGenericMethodTypeParamSymbol(int position)
{
// Note: technically this is a source symbol, but we only care about the position
return IndexedTypeParameterSymbol.GetTypeParameter(position);
}
/// <summary>
/// This override can handle non-PE types.
/// </summary>
protected override TypeSymbol GetGenericTypeParamSymbol(int position)
{
PENamedTypeSymbol peType = _containingType as PENamedTypeSymbol;
if ((object)peType != null)
{
return base.GetGenericTypeParamSymbol(position);
}
NamedTypeSymbol namedType = _containingType as NamedTypeSymbol;
if ((object)namedType != null)
{
int cumulativeArity;
TypeParameterSymbol typeParameter;
GetGenericTypeParameterSymbol(position, namedType, out cumulativeArity, out typeParameter);
if ((object)typeParameter != null)
{
return typeParameter;
}
else
{
Debug.Assert(cumulativeArity <= position);
return new UnsupportedMetadataTypeSymbol(); // position of type parameter too large
}
}
return new UnsupportedMetadataTypeSymbol(); // associated type does not have type parameters
}
private static void GetGenericTypeParameterSymbol(int position, NamedTypeSymbol namedType, out int cumulativeArity, out TypeParameterSymbol typeArgument)
{
cumulativeArity = namedType.Arity;
typeArgument = null;
int arityOffset = 0;
var containingType = namedType.ContainingType;
if ((object)containingType != null)
{
int containingTypeCumulativeArity;
GetGenericTypeParameterSymbol(position, containingType, out containingTypeCumulativeArity, out typeArgument);
cumulativeArity += containingTypeCumulativeArity;
arityOffset = containingTypeCumulativeArity;
}
if (arityOffset <= position && position < cumulativeArity)
{
Debug.Assert((object)typeArgument == null);
typeArgument = namedType.TypeParameters[position - arityOffset];
}
}
/// <summary>
/// Search through the members of the <see cref="_containingType"/> type symbol to find the method that matches a particular
/// signature.
/// </summary>
/// <param name="memberRef">A MemberRef handle that can be used to obtain the name and signature of the method</param>
/// <param name="methodsOnly">True to only return a method.</param>
/// <returns>The matching method symbol, or null if the inputs do not correspond to a valid method.</returns>
internal Symbol FindMember(MemberReferenceHandle memberRef, bool methodsOnly)
{
try
{
string memberName = Module.GetMemberRefNameOrThrow(memberRef);
BlobHandle signatureHandle = Module.GetSignatureOrThrow(memberRef);
SignatureHeader signatureHeader;
BlobReader signaturePointer = this.DecodeSignatureHeaderOrThrow(signatureHandle, out signatureHeader);
switch (signatureHeader.RawValue & SignatureHeader.CallingConventionOrKindMask)
{
case (byte)SignatureCallingConvention.Default:
case (byte)SignatureCallingConvention.VarArgs:
int typeParamCount;
ParamInfo<TypeSymbol>[] targetParamInfo = this.DecodeSignatureParametersOrThrow(ref signaturePointer, signatureHeader, out typeParamCount);
return FindMethodBySignature(_containingType, memberName, signatureHeader, typeParamCount, targetParamInfo);
case (byte)SignatureKind.Field:
if (methodsOnly)
{
// skip:
return null;
}
ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers;
TypeSymbol type = this.DecodeFieldSignature(ref signaturePointer, out customModifiers);
return FindFieldBySignature(_containingType, memberName, customModifiers, type);
default:
// error: unexpected calling convention
return null;
}
}
catch (BadImageFormatException)
{
return null;
}
}
private static FieldSymbol FindFieldBySignature(TypeSymbol targetTypeSymbol, string targetMemberName, ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers, TypeSymbol type)
{
foreach (Symbol member in targetTypeSymbol.GetMembers(targetMemberName))
{
var field = member as FieldSymbol;
TypeWithAnnotations fieldType;
if ((object)field != null &&
TypeSymbol.Equals((fieldType = field.TypeWithAnnotations).Type, type, TypeCompareKind.CLRSignatureCompareOptions) &&
CustomModifiersMatch(fieldType.CustomModifiers, customModifiers))
{
// Behavior in the face of multiple matching signatures is
// implementation defined - we'll just pick the first one.
return field;
}
}
return null;
}
private static MethodSymbol FindMethodBySignature(TypeSymbol targetTypeSymbol, string targetMemberName, SignatureHeader targetMemberSignatureHeader, int targetMemberTypeParamCount, ParamInfo<TypeSymbol>[] targetParamInfo)
{
foreach (Symbol member in targetTypeSymbol.GetMembers(targetMemberName))
{
var method = member as MethodSymbol;
if ((object)method != null &&
((byte)method.CallingConvention == targetMemberSignatureHeader.RawValue) &&
(targetMemberTypeParamCount == method.Arity) &&
MethodSymbolMatchesParamInfo(method, targetParamInfo))
{
// Behavior in the face of multiple matching signatures is
// implementation defined - we'll just pick the first one.
return method;
}
}
return null;
}
private static bool MethodSymbolMatchesParamInfo(MethodSymbol candidateMethod, ParamInfo<TypeSymbol>[] targetParamInfo)
{
int numParams = targetParamInfo.Length - 1; //don't count return type
if (candidateMethod.ParameterCount != numParams)
{
return false;
}
// IndexedTypeParameterSymbol is not going to be exposed anywhere,
// so we'll cheat and use it here for comparison purposes.
TypeMap candidateMethodTypeMap = new TypeMap(
candidateMethod.TypeParameters,
IndexedTypeParameterSymbol.Take(candidateMethod.Arity), true);
if (!ReturnTypesMatch(candidateMethod, candidateMethodTypeMap, ref targetParamInfo[0]))
{
return false;
}
for (int i = 0; i < numParams; i++)
{
if (!ParametersMatch(candidateMethod.Parameters[i], candidateMethodTypeMap, ref targetParamInfo[i + 1 /*for return type*/]))
{
return false;
}
}
return true;
}
private static bool ParametersMatch(ParameterSymbol candidateParam, TypeMap candidateMethodTypeMap, ref ParamInfo<TypeSymbol> targetParam)
{
Debug.Assert(candidateMethodTypeMap != null);
// This could be combined into a single return statement with a more complicated expression, but that would
// be harder to debug.
if ((candidateParam.RefKind != RefKind.None) != targetParam.IsByRef)
{
return false;
}
// CONSIDER: Do we want to add special handling for error types? Right now, we expect they'll just fail to match.
var substituted = candidateParam.TypeWithAnnotations.SubstituteType(candidateMethodTypeMap);
if (!TypeSymbol.Equals(substituted.Type, targetParam.Type, TypeCompareKind.CLRSignatureCompareOptions))
{
return false;
}
if (!CustomModifiersMatch(substituted.CustomModifiers, targetParam.CustomModifiers) ||
!CustomModifiersMatch(candidateMethodTypeMap.SubstituteCustomModifiers(candidateParam.RefCustomModifiers), targetParam.RefCustomModifiers))
{
return false;
}
return true;
}
private static bool ReturnTypesMatch(MethodSymbol candidateMethod, TypeMap candidateMethodTypeMap, ref ParamInfo<TypeSymbol> targetReturnParam)
{
Debug.Assert(candidateMethodTypeMap != null);
if (candidateMethod.ReturnsByRef != targetReturnParam.IsByRef)
{
return false;
}
TypeWithAnnotations candidateMethodType = candidateMethod.ReturnTypeWithAnnotations;
TypeSymbol targetReturnType = targetReturnParam.Type;
// CONSIDER: Do we want to add special handling for error types? Right now, we expect they'll just fail to match.
var substituted = candidateMethodType.SubstituteType(candidateMethodTypeMap);
if (!TypeSymbol.Equals(substituted.Type, targetReturnType, TypeCompareKind.CLRSignatureCompareOptions))
{
return false;
}
if (!CustomModifiersMatch(substituted.CustomModifiers, targetReturnParam.CustomModifiers) ||
!CustomModifiersMatch(candidateMethodTypeMap.SubstituteCustomModifiers(candidateMethod.RefCustomModifiers), targetReturnParam.RefCustomModifiers))
{
return false;
}
return true;
}
private static bool CustomModifiersMatch(ImmutableArray<CustomModifier> candidateCustomModifiers, ImmutableArray<ModifierInfo<TypeSymbol>> targetCustomModifiers)
{
if (targetCustomModifiers.IsDefault || targetCustomModifiers.IsEmpty)
{
return candidateCustomModifiers.IsDefault || candidateCustomModifiers.IsEmpty;
}
else if (candidateCustomModifiers.IsDefault)
{
return false;
}
var n = candidateCustomModifiers.Length;
if (targetCustomModifiers.Length != n)
{
return false;
}
for (int i = 0; i < n; i++)
{
var targetCustomModifier = targetCustomModifiers[i];
CustomModifier candidateCustomModifier = candidateCustomModifiers[i];
if (targetCustomModifier.IsOptional != candidateCustomModifier.IsOptional ||
!object.Equals(targetCustomModifier.Modifier, ((CSharpCustomModifier)candidateCustomModifier).ModifierSymbol))
{
return false;
}
}
return true;
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/Core/MSBuildTask/MvidReader.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
namespace Microsoft.CodeAnalysis.BuildTasks
{
public static class MvidReader
{
private static readonly Guid s_empty = Guid.Empty;
public static Guid ReadAssemblyMvidOrEmpty(Stream stream)
{
return ReadAssemblyMvidOrEmpty(new BinaryReader(stream));
}
private static Guid ReadAssemblyMvidOrEmpty(BinaryReader reader)
{
// DOS Header: Magic number (2)
if (!ReadUInt16(reader, out ushort magicNumber) || magicNumber != 0x5a4d) // "MZ"
{
return s_empty;
}
// DOS Header: Address of PE Signature (at 0x3C)
if (!MoveTo(0x3C, reader))
{
return s_empty;
}
if (!ReadUInt32(reader, out uint pointerToPeSignature))
{
return s_empty;
}
// jump over the MS DOS Stub to the PE Signature
if (!MoveTo(pointerToPeSignature, reader))
{
return s_empty;
}
// PE Signature ('P' 'E' null null)
if (!ReadUInt32(reader, out uint peSig) || peSig != 0x00004550)
{
return s_empty;
}
// COFF Header: Machine (2)
if (!Skip(2, reader))
{
return s_empty;
}
// COFF Header: NumberOfSections (2)
if (!ReadUInt16(reader, out ushort sections))
{
return s_empty;
}
// COFF Header: TimeDateStamp (4), PointerToSymbolTable (4), NumberOfSymbols (4)
if (!Skip(12, reader))
{
return s_empty;
}
// COFF Header: OptionalHeaderSize (2)
if (!ReadUInt16(reader, out ushort optionalHeaderSize))
{
return s_empty;
}
// COFF Header: Characteristics (2)
if (!Skip(2, reader))
{
return s_empty;
}
// Optional header
if (!Skip(optionalHeaderSize, reader))
{
return s_empty;
}
// Section headers
return FindMvidInSections(sections, reader);
}
private static Guid FindMvidInSections(ushort count, BinaryReader reader)
{
for (int i = 0; i < count; i++)
{
// Section: Name (8)
if (!ReadBytes(reader, 8, out byte[]? name))
{
return s_empty;
}
if (name!.Length == 8 && name[0] == '.' &&
name[1] == 'm' && name[2] == 'v' && name[3] == 'i' && name[4] == 'd' && name[5] == '\0')
{
// Section: VirtualSize (4)
if (!ReadUInt32(reader, out uint virtualSize) || virtualSize != 16)
{
// The .mvid section only stores a Guid
return s_empty;
}
// Section: VirtualAddress (4), SizeOfRawData (4)
if (!Skip(8, reader))
{
return s_empty;
}
// Section: PointerToRawData (4)
if (!ReadUInt32(reader, out uint pointerToRawData))
{
return s_empty;
}
return ReadMvidSection(reader, pointerToRawData);
}
else
{
// Section: VirtualSize (4), VirtualAddress (4), SizeOfRawData (4),
// PointerToRawData (4), PointerToRelocations (4), PointerToLineNumbers (4),
// NumberOfRelocations (2), NumberOfLineNumbers (2), Characteristics (4)
if (!Skip(4 + 4 + 4 + 4 + 4 + 4 + 2 + 2 + 4, reader))
{
return s_empty;
}
}
}
return s_empty;
}
private static Guid ReadMvidSection(BinaryReader reader, uint pointerToMvidSection)
{
if (!MoveTo(pointerToMvidSection, reader))
{
return s_empty;
}
if (!ReadBytes(reader, 16, out byte[]? guidBytes))
{
return s_empty;
}
return new Guid(guidBytes!);
}
private static bool ReadUInt16(BinaryReader reader, out ushort output)
{
if (reader.BaseStream.Position + 2 >= reader.BaseStream.Length)
{
output = 0;
return false;
}
output = reader.ReadUInt16();
return true;
}
private static bool ReadUInt32(BinaryReader reader, out uint output)
{
if (reader.BaseStream.Position + 4 >= reader.BaseStream.Length)
{
output = 0;
return false;
}
output = reader.ReadUInt32();
return true;
}
private static bool ReadBytes(BinaryReader reader, int count, out byte[]? output)
{
if (reader.BaseStream.Position + count >= reader.BaseStream.Length)
{
output = null;
return false;
}
output = reader.ReadBytes(count);
return true;
}
private static bool Skip(int bytes, BinaryReader reader)
{
if (reader.BaseStream.Position + bytes >= reader.BaseStream.Length)
{
return false;
}
reader.BaseStream.Seek(bytes, SeekOrigin.Current);
return true;
}
private static bool MoveTo(uint position, BinaryReader reader)
{
if (position >= reader.BaseStream.Length)
{
return false;
}
reader.BaseStream.Seek(position, SeekOrigin.Begin);
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
namespace Microsoft.CodeAnalysis.BuildTasks
{
public static class MvidReader
{
private static readonly Guid s_empty = Guid.Empty;
public static Guid ReadAssemblyMvidOrEmpty(Stream stream)
{
return ReadAssemblyMvidOrEmpty(new BinaryReader(stream));
}
private static Guid ReadAssemblyMvidOrEmpty(BinaryReader reader)
{
// DOS Header: Magic number (2)
if (!ReadUInt16(reader, out ushort magicNumber) || magicNumber != 0x5a4d) // "MZ"
{
return s_empty;
}
// DOS Header: Address of PE Signature (at 0x3C)
if (!MoveTo(0x3C, reader))
{
return s_empty;
}
if (!ReadUInt32(reader, out uint pointerToPeSignature))
{
return s_empty;
}
// jump over the MS DOS Stub to the PE Signature
if (!MoveTo(pointerToPeSignature, reader))
{
return s_empty;
}
// PE Signature ('P' 'E' null null)
if (!ReadUInt32(reader, out uint peSig) || peSig != 0x00004550)
{
return s_empty;
}
// COFF Header: Machine (2)
if (!Skip(2, reader))
{
return s_empty;
}
// COFF Header: NumberOfSections (2)
if (!ReadUInt16(reader, out ushort sections))
{
return s_empty;
}
// COFF Header: TimeDateStamp (4), PointerToSymbolTable (4), NumberOfSymbols (4)
if (!Skip(12, reader))
{
return s_empty;
}
// COFF Header: OptionalHeaderSize (2)
if (!ReadUInt16(reader, out ushort optionalHeaderSize))
{
return s_empty;
}
// COFF Header: Characteristics (2)
if (!Skip(2, reader))
{
return s_empty;
}
// Optional header
if (!Skip(optionalHeaderSize, reader))
{
return s_empty;
}
// Section headers
return FindMvidInSections(sections, reader);
}
private static Guid FindMvidInSections(ushort count, BinaryReader reader)
{
for (int i = 0; i < count; i++)
{
// Section: Name (8)
if (!ReadBytes(reader, 8, out byte[]? name))
{
return s_empty;
}
if (name!.Length == 8 && name[0] == '.' &&
name[1] == 'm' && name[2] == 'v' && name[3] == 'i' && name[4] == 'd' && name[5] == '\0')
{
// Section: VirtualSize (4)
if (!ReadUInt32(reader, out uint virtualSize) || virtualSize != 16)
{
// The .mvid section only stores a Guid
return s_empty;
}
// Section: VirtualAddress (4), SizeOfRawData (4)
if (!Skip(8, reader))
{
return s_empty;
}
// Section: PointerToRawData (4)
if (!ReadUInt32(reader, out uint pointerToRawData))
{
return s_empty;
}
return ReadMvidSection(reader, pointerToRawData);
}
else
{
// Section: VirtualSize (4), VirtualAddress (4), SizeOfRawData (4),
// PointerToRawData (4), PointerToRelocations (4), PointerToLineNumbers (4),
// NumberOfRelocations (2), NumberOfLineNumbers (2), Characteristics (4)
if (!Skip(4 + 4 + 4 + 4 + 4 + 4 + 2 + 2 + 4, reader))
{
return s_empty;
}
}
}
return s_empty;
}
private static Guid ReadMvidSection(BinaryReader reader, uint pointerToMvidSection)
{
if (!MoveTo(pointerToMvidSection, reader))
{
return s_empty;
}
if (!ReadBytes(reader, 16, out byte[]? guidBytes))
{
return s_empty;
}
return new Guid(guidBytes!);
}
private static bool ReadUInt16(BinaryReader reader, out ushort output)
{
if (reader.BaseStream.Position + 2 >= reader.BaseStream.Length)
{
output = 0;
return false;
}
output = reader.ReadUInt16();
return true;
}
private static bool ReadUInt32(BinaryReader reader, out uint output)
{
if (reader.BaseStream.Position + 4 >= reader.BaseStream.Length)
{
output = 0;
return false;
}
output = reader.ReadUInt32();
return true;
}
private static bool ReadBytes(BinaryReader reader, int count, out byte[]? output)
{
if (reader.BaseStream.Position + count >= reader.BaseStream.Length)
{
output = null;
return false;
}
output = reader.ReadBytes(count);
return true;
}
private static bool Skip(int bytes, BinaryReader reader)
{
if (reader.BaseStream.Position + bytes >= reader.BaseStream.Length)
{
return false;
}
reader.BaseStream.Seek(bytes, SeekOrigin.Current);
return true;
}
private static bool MoveTo(uint position, BinaryReader reader)
{
if (position >= reader.BaseStream.Length)
{
return false;
}
reader.BaseStream.Seek(position, SeekOrigin.Begin);
return true;
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Workspaces/Core/Portable/Editing/ImportAdder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editing
{
public static class ImportAdder
{
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document.
/// </summary>
public static Task<Document> AddImportsAsync(Document document, OptionSet? options = null, CancellationToken cancellationToken = default)
=> AddImportsFromSyntaxesAsync(document, options, cancellationToken);
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the span specified.
/// </summary>
public static Task<Document> AddImportsAsync(Document document, TextSpan span, OptionSet? options = null, CancellationToken cancellationToken = default)
=> AddImportsFromSyntaxesAsync(document, new[] { span }, options, cancellationToken);
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the sub-trees annotated with the <see cref="SyntaxAnnotation"/>.
/// </summary>
public static Task<Document> AddImportsAsync(Document document, SyntaxAnnotation annotation, OptionSet? options = null, CancellationToken cancellationToken = default)
=> AddImportsFromSyntaxesAsync(document, annotation, options, cancellationToken);
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the spans specified.
/// </summary>
public static Task<Document> AddImportsAsync(Document document, IEnumerable<TextSpan> spans, OptionSet? options = null, CancellationToken cancellationToken = default)
=> AddImportsFromSyntaxesAsync(document, spans, options, cancellationToken);
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document.
/// </summary>
internal static async Task<Document> AddImportsFromSyntaxesAsync(Document document, OptionSet? options = null, CancellationToken cancellationToken = default)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(root);
return await AddImportsFromSyntaxesAsync(document, root.FullSpan, options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the span specified.
/// </summary>
internal static Task<Document> AddImportsFromSyntaxesAsync(Document document, TextSpan span, OptionSet? options = null, CancellationToken cancellationToken = default)
=> AddImportsFromSyntaxesAsync(document, new[] { span }, options, cancellationToken);
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the sub-trees annotated with the <see cref="SyntaxAnnotation"/>.
/// </summary>
internal static async Task<Document> AddImportsFromSyntaxesAsync(Document document, SyntaxAnnotation annotation, OptionSet? options = null, CancellationToken cancellationToken = default)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(root);
return await AddImportsFromSyntaxesAsync(document, root.GetAnnotatedNodesAndTokens(annotation).Select(t => t.FullSpan), options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the spans specified.
/// </summary>
internal static Task<Document> AddImportsFromSyntaxesAsync(Document document, IEnumerable<TextSpan> spans, OptionSet? options = null, CancellationToken cancellationToken = default)
{
var service = document.GetLanguageService<ImportAdderService>();
if (service != null)
{
return service.AddImportsAsync(document, spans, ImportAdderService.Strategy.AddImportsFromSyntaxes, options, cancellationToken);
}
else
{
return Task.FromResult(document);
}
}
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document.
/// </summary>
internal static async Task<Document> AddImportsFromSymbolAnnotationAsync(Document document, OptionSet? options = null, CancellationToken cancellationToken = default)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(root);
return await AddImportsFromSymbolAnnotationAsync(document, root.FullSpan, options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the span specified.
/// </summary>
internal static Task<Document> AddImportsFromSymbolAnnotationAsync(Document document, TextSpan span, OptionSet? options = null, CancellationToken cancellationToken = default)
=> AddImportsFromSymbolAnnotationAsync(document, new[] { span }, options, cancellationToken);
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the sub-trees annotated with the <see cref="SyntaxAnnotation"/>.
/// </summary>
internal static async Task<Document> AddImportsFromSymbolAnnotationAsync(Document document, SyntaxAnnotation annotation, OptionSet? options = null, CancellationToken cancellationToken = default)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(root);
return await AddImportsFromSymbolAnnotationAsync(document, root.GetAnnotatedNodesAndTokens(annotation).Select(t => t.FullSpan), options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the spans specified.
/// </summary>
internal static Task<Document> AddImportsFromSymbolAnnotationAsync(Document document, IEnumerable<TextSpan> spans, OptionSet? options = null, CancellationToken cancellationToken = default)
{
var service = document.GetLanguageService<ImportAdderService>();
if (service != null)
{
return service.AddImportsAsync(document, spans, ImportAdderService.Strategy.AddImportsFromSymbolAnnotations, options, cancellationToken);
}
else
{
return Task.FromResult(document);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editing
{
public static class ImportAdder
{
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document.
/// </summary>
public static Task<Document> AddImportsAsync(Document document, OptionSet? options = null, CancellationToken cancellationToken = default)
=> AddImportsFromSyntaxesAsync(document, options, cancellationToken);
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the span specified.
/// </summary>
public static Task<Document> AddImportsAsync(Document document, TextSpan span, OptionSet? options = null, CancellationToken cancellationToken = default)
=> AddImportsFromSyntaxesAsync(document, new[] { span }, options, cancellationToken);
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the sub-trees annotated with the <see cref="SyntaxAnnotation"/>.
/// </summary>
public static Task<Document> AddImportsAsync(Document document, SyntaxAnnotation annotation, OptionSet? options = null, CancellationToken cancellationToken = default)
=> AddImportsFromSyntaxesAsync(document, annotation, options, cancellationToken);
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the spans specified.
/// </summary>
public static Task<Document> AddImportsAsync(Document document, IEnumerable<TextSpan> spans, OptionSet? options = null, CancellationToken cancellationToken = default)
=> AddImportsFromSyntaxesAsync(document, spans, options, cancellationToken);
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document.
/// </summary>
internal static async Task<Document> AddImportsFromSyntaxesAsync(Document document, OptionSet? options = null, CancellationToken cancellationToken = default)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(root);
return await AddImportsFromSyntaxesAsync(document, root.FullSpan, options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the span specified.
/// </summary>
internal static Task<Document> AddImportsFromSyntaxesAsync(Document document, TextSpan span, OptionSet? options = null, CancellationToken cancellationToken = default)
=> AddImportsFromSyntaxesAsync(document, new[] { span }, options, cancellationToken);
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the sub-trees annotated with the <see cref="SyntaxAnnotation"/>.
/// </summary>
internal static async Task<Document> AddImportsFromSyntaxesAsync(Document document, SyntaxAnnotation annotation, OptionSet? options = null, CancellationToken cancellationToken = default)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(root);
return await AddImportsFromSyntaxesAsync(document, root.GetAnnotatedNodesAndTokens(annotation).Select(t => t.FullSpan), options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the spans specified.
/// </summary>
internal static Task<Document> AddImportsFromSyntaxesAsync(Document document, IEnumerable<TextSpan> spans, OptionSet? options = null, CancellationToken cancellationToken = default)
{
var service = document.GetLanguageService<ImportAdderService>();
if (service != null)
{
return service.AddImportsAsync(document, spans, ImportAdderService.Strategy.AddImportsFromSyntaxes, options, cancellationToken);
}
else
{
return Task.FromResult(document);
}
}
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document.
/// </summary>
internal static async Task<Document> AddImportsFromSymbolAnnotationAsync(Document document, OptionSet? options = null, CancellationToken cancellationToken = default)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(root);
return await AddImportsFromSymbolAnnotationAsync(document, root.FullSpan, options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the span specified.
/// </summary>
internal static Task<Document> AddImportsFromSymbolAnnotationAsync(Document document, TextSpan span, OptionSet? options = null, CancellationToken cancellationToken = default)
=> AddImportsFromSymbolAnnotationAsync(document, new[] { span }, options, cancellationToken);
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the sub-trees annotated with the <see cref="SyntaxAnnotation"/>.
/// </summary>
internal static async Task<Document> AddImportsFromSymbolAnnotationAsync(Document document, SyntaxAnnotation annotation, OptionSet? options = null, CancellationToken cancellationToken = default)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(root);
return await AddImportsFromSymbolAnnotationAsync(document, root.GetAnnotatedNodesAndTokens(annotation).Select(t => t.FullSpan), options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds namespace imports / using directives for namespace references found in the document within the spans specified.
/// </summary>
internal static Task<Document> AddImportsFromSymbolAnnotationAsync(Document document, IEnumerable<TextSpan> spans, OptionSet? options = null, CancellationToken cancellationToken = default)
{
var service = document.GetLanguageService<ImportAdderService>();
if (service != null)
{
return service.AddImportsAsync(document, spans, ImportAdderService.Strategy.AddImportsFromSymbolAnnotations, options, cancellationToken);
}
else
{
return Task.FromResult(document);
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Features/LanguageServer/Protocol/LspOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Composition;
using System.Text;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.LanguageServer
{
internal static class LspOptions
{
private const string LocalRegistryPath = @"Roslyn\Internal\Lsp\";
/// <summary>
/// This sets the max list size we will return in response to a completion request.
/// If there are more than this many items, we will set the isIncomplete flag on the returned completion list.
/// </summary>
public static readonly Option2<int> MaxCompletionListSize = new(nameof(LspOptions), nameof(MaxCompletionListSize), defaultValue: 1000,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(MaxCompletionListSize)));
}
[ExportOptionProvider, Shared]
internal class LspOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LspOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(LspOptions.MaxCompletionListSize);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Composition;
using System.Text;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.LanguageServer
{
internal static class LspOptions
{
private const string LocalRegistryPath = @"Roslyn\Internal\Lsp\";
/// <summary>
/// This sets the max list size we will return in response to a completion request.
/// If there are more than this many items, we will set the isIncomplete flag on the returned completion list.
/// </summary>
public static readonly Option2<int> MaxCompletionListSize = new(nameof(LspOptions), nameof(MaxCompletionListSize), defaultValue: 1000,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(MaxCompletionListSize)));
}
[ExportOptionProvider, Shared]
internal class LspOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LspOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(LspOptions.MaxCompletionListSize);
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Workspaces/Core/Portable/Shared/Utilities/XmlFragmentParser.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.IO;
using System.Xml;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
/// <summary>
/// An XML parser that is designed to parse small fragments of XML such as those that appear in documentation comments.
/// PERF: We try to re-use the same underlying <see cref="XmlReader"/> to reduce the allocation costs of multiple parses.
/// </summary>
internal sealed class XmlFragmentParser
{
private XmlReader _xmlReader;
private readonly Reader _textReader = new();
private static readonly ObjectPool<XmlFragmentParser> s_pool = SharedPools.Default<XmlFragmentParser>();
/// <summary>
/// Parse the given XML fragment. The given callback is executed until either the end of the fragment
/// is reached or an exception occurs.
/// </summary>
/// <typeparam name="TArg">Type of an additional argument passed to the <paramref name="callback"/> delegate.</typeparam>
/// <param name="xmlFragment">The fragment to parse.</param>
/// <param name="callback">Action to execute while there is still more to read.</param>
/// <param name="arg">Additional argument passed to the callback.</param>
/// <remarks>
/// It is important that the <paramref name="callback"/> action advances the <see cref="XmlReader"/>,
/// otherwise parsing will never complete.
/// </remarks>
public static void ParseFragment<TArg>(string xmlFragment, Action<XmlReader, TArg> callback, TArg arg)
{
var instance = s_pool.Allocate();
try
{
instance.ParseInternal(xmlFragment, callback, arg);
}
finally
{
s_pool.Free(instance);
}
}
private static readonly XmlReaderSettings s_xmlSettings = new()
{
DtdProcessing = DtdProcessing.Prohibit,
};
private void ParseInternal<TArg>(string text, Action<XmlReader, TArg> callback, TArg arg)
{
_textReader.SetText(text);
if (_xmlReader == null)
{
_xmlReader = XmlReader.Create(_textReader, s_xmlSettings);
}
try
{
while (!ReachedEnd)
{
if (BeforeStart)
{
// Skip over the synthetic root element and first node
_xmlReader.Read();
}
else
{
callback(_xmlReader, arg);
}
}
// Read the final EndElement to reset things for the next user.
_xmlReader.ReadEndElement();
}
catch
{
// The reader is in a bad state, so dispose of it and recreate a new one next time we get called.
_xmlReader.Dispose();
_xmlReader = null;
_textReader.Reset();
throw;
}
}
private bool BeforeStart
{
get
{
// Depth 0 = Document root
// Depth 1 = Synthetic wrapper, "CurrentElement"
// Depth 2 = Start of user's fragment.
return _xmlReader.Depth < 2;
}
}
private bool ReachedEnd
{
get
{
return _xmlReader.Depth == 1
&& _xmlReader.NodeType == XmlNodeType.EndElement
&& _xmlReader.LocalName == Reader.CurrentElementName;
}
}
/// <summary>
/// A text reader over a synthesized XML stream consisting of a single root element followed by a potentially
/// infinite stream of fragments. Each time "SetText" is called the stream is rewound to the element immediately
/// following the synthetic root node.
/// </summary>
private sealed class Reader : TextReader
{
/// <summary>
/// Current text to validate.
/// </summary>
private string _text;
private int _position;
// Base the root element name on a GUID to avoid accidental (or intentional) collisions. An underscore is
// prefixed because element names must not start with a number.
private static readonly string s_rootElementName = "_" + Guid.NewGuid().ToString("N");
// We insert an extra synthetic element name to allow for raw text at the root
internal static readonly string CurrentElementName = "_" + Guid.NewGuid().ToString("N");
private static readonly string s_rootStart = "<" + s_rootElementName + ">";
private static readonly string s_currentStart = "<" + CurrentElementName + ">";
private static readonly string s_currentEnd = "</" + CurrentElementName + ">";
public void Reset()
{
_text = null;
_position = 0;
}
public void SetText(string text)
{
_text = text;
// The first read shall read the <root>,
// the subsequents reads shall start with <current> element
if (_position > 0)
{
_position = s_rootStart.Length;
}
}
public override int Read(char[] buffer, int index, int count)
{
if (count == 0)
{
return 0;
}
// The stream synthesizes an XML document with:
// 1. A root element start tag
// 2. Current element start tag
// 3. The user text (xml fragments)
// 4. Current element end tag
var initialCount = count;
// <root>
_position += EncodeAndAdvance(s_rootStart, _position, buffer, ref index, ref count);
// <current>
_position += EncodeAndAdvance(s_currentStart, _position - s_rootStart.Length, buffer, ref index, ref count);
// text
_position += EncodeAndAdvance(_text, _position - s_rootStart.Length - s_currentStart.Length, buffer, ref index, ref count);
// </current>
_position += EncodeAndAdvance(s_currentEnd, _position - s_rootStart.Length - s_currentStart.Length - _text.Length, buffer, ref index, ref count);
// Pretend that the stream is infinite, i.e. never return 0 characters read.
if (initialCount == count)
{
buffer[index++] = ' ';
count--;
}
return initialCount - count;
}
private static int EncodeAndAdvance(string src, int srcIndex, char[] dest, ref int destIndex, ref int destCount)
{
if (destCount == 0 || srcIndex < 0 || srcIndex >= src.Length)
{
return 0;
}
var charCount = Math.Min(src.Length - srcIndex, destCount);
Debug.Assert(charCount > 0);
src.CopyTo(srcIndex, dest, destIndex, charCount);
destIndex += charCount;
destCount -= charCount;
Debug.Assert(destCount >= 0);
return charCount;
}
public override int Read()
{
// XmlReader does not call this API
throw ExceptionUtilities.Unreachable;
}
public override int Peek()
{
// XmlReader does not call this API
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.
#nullable disable
using System;
using System.Diagnostics;
using System.IO;
using System.Xml;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
/// <summary>
/// An XML parser that is designed to parse small fragments of XML such as those that appear in documentation comments.
/// PERF: We try to re-use the same underlying <see cref="XmlReader"/> to reduce the allocation costs of multiple parses.
/// </summary>
internal sealed class XmlFragmentParser
{
private XmlReader _xmlReader;
private readonly Reader _textReader = new();
private static readonly ObjectPool<XmlFragmentParser> s_pool = SharedPools.Default<XmlFragmentParser>();
/// <summary>
/// Parse the given XML fragment. The given callback is executed until either the end of the fragment
/// is reached or an exception occurs.
/// </summary>
/// <typeparam name="TArg">Type of an additional argument passed to the <paramref name="callback"/> delegate.</typeparam>
/// <param name="xmlFragment">The fragment to parse.</param>
/// <param name="callback">Action to execute while there is still more to read.</param>
/// <param name="arg">Additional argument passed to the callback.</param>
/// <remarks>
/// It is important that the <paramref name="callback"/> action advances the <see cref="XmlReader"/>,
/// otherwise parsing will never complete.
/// </remarks>
public static void ParseFragment<TArg>(string xmlFragment, Action<XmlReader, TArg> callback, TArg arg)
{
var instance = s_pool.Allocate();
try
{
instance.ParseInternal(xmlFragment, callback, arg);
}
finally
{
s_pool.Free(instance);
}
}
private static readonly XmlReaderSettings s_xmlSettings = new()
{
DtdProcessing = DtdProcessing.Prohibit,
};
private void ParseInternal<TArg>(string text, Action<XmlReader, TArg> callback, TArg arg)
{
_textReader.SetText(text);
if (_xmlReader == null)
{
_xmlReader = XmlReader.Create(_textReader, s_xmlSettings);
}
try
{
while (!ReachedEnd)
{
if (BeforeStart)
{
// Skip over the synthetic root element and first node
_xmlReader.Read();
}
else
{
callback(_xmlReader, arg);
}
}
// Read the final EndElement to reset things for the next user.
_xmlReader.ReadEndElement();
}
catch
{
// The reader is in a bad state, so dispose of it and recreate a new one next time we get called.
_xmlReader.Dispose();
_xmlReader = null;
_textReader.Reset();
throw;
}
}
private bool BeforeStart
{
get
{
// Depth 0 = Document root
// Depth 1 = Synthetic wrapper, "CurrentElement"
// Depth 2 = Start of user's fragment.
return _xmlReader.Depth < 2;
}
}
private bool ReachedEnd
{
get
{
return _xmlReader.Depth == 1
&& _xmlReader.NodeType == XmlNodeType.EndElement
&& _xmlReader.LocalName == Reader.CurrentElementName;
}
}
/// <summary>
/// A text reader over a synthesized XML stream consisting of a single root element followed by a potentially
/// infinite stream of fragments. Each time "SetText" is called the stream is rewound to the element immediately
/// following the synthetic root node.
/// </summary>
private sealed class Reader : TextReader
{
/// <summary>
/// Current text to validate.
/// </summary>
private string _text;
private int _position;
// Base the root element name on a GUID to avoid accidental (or intentional) collisions. An underscore is
// prefixed because element names must not start with a number.
private static readonly string s_rootElementName = "_" + Guid.NewGuid().ToString("N");
// We insert an extra synthetic element name to allow for raw text at the root
internal static readonly string CurrentElementName = "_" + Guid.NewGuid().ToString("N");
private static readonly string s_rootStart = "<" + s_rootElementName + ">";
private static readonly string s_currentStart = "<" + CurrentElementName + ">";
private static readonly string s_currentEnd = "</" + CurrentElementName + ">";
public void Reset()
{
_text = null;
_position = 0;
}
public void SetText(string text)
{
_text = text;
// The first read shall read the <root>,
// the subsequents reads shall start with <current> element
if (_position > 0)
{
_position = s_rootStart.Length;
}
}
public override int Read(char[] buffer, int index, int count)
{
if (count == 0)
{
return 0;
}
// The stream synthesizes an XML document with:
// 1. A root element start tag
// 2. Current element start tag
// 3. The user text (xml fragments)
// 4. Current element end tag
var initialCount = count;
// <root>
_position += EncodeAndAdvance(s_rootStart, _position, buffer, ref index, ref count);
// <current>
_position += EncodeAndAdvance(s_currentStart, _position - s_rootStart.Length, buffer, ref index, ref count);
// text
_position += EncodeAndAdvance(_text, _position - s_rootStart.Length - s_currentStart.Length, buffer, ref index, ref count);
// </current>
_position += EncodeAndAdvance(s_currentEnd, _position - s_rootStart.Length - s_currentStart.Length - _text.Length, buffer, ref index, ref count);
// Pretend that the stream is infinite, i.e. never return 0 characters read.
if (initialCount == count)
{
buffer[index++] = ' ';
count--;
}
return initialCount - count;
}
private static int EncodeAndAdvance(string src, int srcIndex, char[] dest, ref int destIndex, ref int destCount)
{
if (destCount == 0 || srcIndex < 0 || srcIndex >= src.Length)
{
return 0;
}
var charCount = Math.Min(src.Length - srcIndex, destCount);
Debug.Assert(charCount > 0);
src.CopyTo(srcIndex, dest, destIndex, charCount);
destIndex += charCount;
destCount -= charCount;
Debug.Assert(destCount >= 0);
return charCount;
}
public override int Read()
{
// XmlReader does not call this API
throw ExceptionUtilities.Unreachable;
}
public override int Peek()
{
// XmlReader does not call this API
throw ExceptionUtilities.Unreachable;
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/CSharp/Portable/Symbols/Source/SynthesizedAttributeData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Class to represent a synthesized attribute
/// </summary>
internal sealed class SynthesizedAttributeData : SourceAttributeData
{
internal SynthesizedAttributeData(MethodSymbol wellKnownMember, ImmutableArray<TypedConstant> arguments, ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments)
: base(
applicationNode: null,
attributeClass: wellKnownMember.ContainingType,
attributeConstructor: wellKnownMember,
constructorArguments: arguments,
constructorArgumentsSourceIndices: default,
namedArguments: namedArguments,
hasErrors: false,
isConditionallyOmitted: false)
{
Debug.Assert((object)wellKnownMember != null);
Debug.Assert(!arguments.IsDefault);
Debug.Assert(!namedArguments.IsDefault); // Frequently empty though.
}
internal SynthesizedAttributeData(SourceAttributeData original)
: base(
applicationNode: original.ApplicationSyntaxReference,
attributeClass: original.AttributeClass,
attributeConstructor: original.AttributeConstructor,
constructorArguments: original.CommonConstructorArguments,
constructorArgumentsSourceIndices: original.ConstructorArgumentsSourceIndices,
namedArguments: original.CommonNamedArguments,
hasErrors: original.HasErrors,
isConditionallyOmitted: original.IsConditionallyOmitted)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Class to represent a synthesized attribute
/// </summary>
internal sealed class SynthesizedAttributeData : SourceAttributeData
{
internal SynthesizedAttributeData(MethodSymbol wellKnownMember, ImmutableArray<TypedConstant> arguments, ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments)
: base(
applicationNode: null,
attributeClass: wellKnownMember.ContainingType,
attributeConstructor: wellKnownMember,
constructorArguments: arguments,
constructorArgumentsSourceIndices: default,
namedArguments: namedArguments,
hasErrors: false,
isConditionallyOmitted: false)
{
Debug.Assert((object)wellKnownMember != null);
Debug.Assert(!arguments.IsDefault);
Debug.Assert(!namedArguments.IsDefault); // Frequently empty though.
}
internal SynthesizedAttributeData(SourceAttributeData original)
: base(
applicationNode: original.ApplicationSyntaxReference,
attributeClass: original.AttributeClass,
attributeConstructor: original.AttributeConstructor,
constructorArguments: original.CommonConstructorArguments,
constructorArgumentsSourceIndices: original.ConstructorArgumentsSourceIndices,
namedArguments: original.CommonNamedArguments,
hasErrors: original.HasErrors,
isConditionallyOmitted: original.IsConditionallyOmitted)
{
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/EditorFeatures/Core.Wpf/NavigateTo/NavigateToItemDisplayFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.NavigateTo;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo
{
internal sealed class NavigateToItemDisplayFactory : INavigateToItemDisplayFactory
{
public INavigateToItemDisplay CreateItemDisplay(NavigateToItem item)
{
var searchResult = (INavigateToSearchResult)item.Tag;
return new NavigateToItemDisplay(searchResult);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.NavigateTo;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo
{
internal sealed class NavigateToItemDisplayFactory : INavigateToItemDisplayFactory
{
public INavigateToItemDisplay CreateItemDisplay(NavigateToItem item)
{
var searchResult = (INavigateToSearchResult)item.Tag;
return new NavigateToItemDisplay(searchResult);
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ShortKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 ShortKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public ShortKeywordRecommender()
: base(SyntaxKind.ShortKeyword)
{
}
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_Int16;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 ShortKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public ShortKeywordRecommender()
: base(SyntaxKind.ShortKeyword)
{
}
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_Int16;
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Workspaces/MSBuildTest/Resources/SourceFiles/CSharp/CSharpClass_WithConditionalAttributes.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using System.Text;
[assembly: MyAttr()]
namespace CSharpProject
{
/// <summary>
/// This is a C# class
/// </summary>
public class CSharpClass
{
}
}
[System.Diagnostics.Conditional("EnableMyAttribute")]
public class MyAttr : Attribute
{
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using System.Text;
[assembly: MyAttr()]
namespace CSharpProject
{
/// <summary>
/// This is a C# class
/// </summary>
public class CSharpClass
{
}
}
[System.Diagnostics.Conditional("EnableMyAttribute")]
public class MyAttr : Attribute
{
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractSyncNamespaceCodeRefactoringProvider.MoveFileCodeAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace
{
internal abstract partial class AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax>
: CodeRefactoringProvider
where TNamespaceDeclarationSyntax : SyntaxNode
where TCompilationUnitSyntax : SyntaxNode
where TMemberDeclarationSyntax : SyntaxNode
{
private class MoveFileCodeAction : CodeAction
{
private readonly State _state;
private readonly ImmutableArray<string> _newfolders;
public override string Title
=> _newfolders.Length > 0
? string.Format(FeaturesResources.Move_file_to_0, string.Join(PathUtilities.DirectorySeparatorStr, _newfolders))
: FeaturesResources.Move_file_to_project_root_folder;
public MoveFileCodeAction(State state, ImmutableArray<string> newFolders)
{
_state = state;
_newfolders = newFolders;
}
protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
{
var id = _state.Document.Id;
var solution = _state.Document.Project.Solution;
var document = solution.GetDocument(id);
var newDocumentId = DocumentId.CreateNewId(document.Project.Id, document.Name);
solution = solution.RemoveDocument(id);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
solution = solution.AddDocument(newDocumentId, document.Name, text, folders: _newfolders);
return ImmutableArray.Create<CodeActionOperation>(
new ApplyChangesOperation(solution),
new OpenDocumentOperation(newDocumentId, activateIfAlreadyOpen: true));
}
public static ImmutableArray<MoveFileCodeAction> Create(State state)
{
Debug.Assert(state.RelativeDeclaredNamespace != null);
// Since all documents have identical folder structure, we can do the computation on any of them.
var document = state.Document;
// In case the relative namespace is "", the file should be moved to project root,
// set `parts` to empty to indicate that.
var parts = state.RelativeDeclaredNamespace.Length == 0
? ImmutableArray<string>.Empty
: state.RelativeDeclaredNamespace.Split(new[] { '.' }).ToImmutableArray();
// Invalid char can only appear in namespace name when there's error,
// which we have checked before creating any code actions.
Debug.Assert(parts.IsEmpty || parts.Any(s => s.IndexOfAny(Path.GetInvalidPathChars()) < 0));
var projectRootFolder = FolderInfo.CreateFolderHierarchyForProject(document.Project);
var candidateFolders = FindCandidateFolders(projectRootFolder, parts, ImmutableArray<string>.Empty);
return candidateFolders.SelectAsArray(folders => new MoveFileCodeAction(state, folders));
}
/// <summary>
/// We try to provide additional "move file" options if we can find existing folders that matches target namespace.
/// For example, if the target namespace is 'DefaultNamesapce.A.B.C', and there's a folder 'ProjectRoot\A.B\' already
/// exists, then will provide two actions, "move file to ProjectRoot\A.B\C\" and "move file to ProjectRoot\A\B\C\".
/// </summary>
private static ImmutableArray<ImmutableArray<string>> FindCandidateFolders(
FolderInfo currentFolderInfo,
ImmutableArray<string> parts,
ImmutableArray<string> currentFolder)
{
if (parts.IsEmpty)
{
return ImmutableArray.Create(currentFolder);
}
// Try to figure out all possible folder names that can match the target namespace.
// For example, if the target is "A.B.C", then the matching folder names include
// "A", "A.B" and "A.B.C". The item "index" in the result tuple is the number
// of items in namespace parts used to construct iten "foldername".
var candidates = Enumerable.Range(1, parts.Length)
.Select(i => (foldername: string.Join(".", parts.Take(i)), index: i))
.ToImmutableDictionary(t => t.foldername, t => t.index, PathUtilities.Comparer);
var subFolders = currentFolderInfo.ChildFolders;
var builder = ArrayBuilder<ImmutableArray<string>>.GetInstance();
foreach (var (folderName, index) in candidates)
{
if (subFolders.TryGetValue(folderName, out var matchingFolderInfo))
{
var newParts = index >= parts.Length
? ImmutableArray<string>.Empty
: ImmutableArray.Create(parts, index, parts.Length - index);
var newCurrentFolder = currentFolder.Add(matchingFolderInfo.Name);
builder.AddRange(FindCandidateFolders(matchingFolderInfo, newParts, newCurrentFolder));
}
}
// Make sure we always have the default path as an available option to the user
// (which might have been found by the search above, therefore the check here)
// For example, if the target namespace is "A.B.C.D", and there's folder <ROOT>\A.B\,
// the search above would only return "<ROOT>\A.B\C\D". We'd want to provide
// "<ROOT>\A\B\C\D" as the default path.
var defaultPathBasedOnCurrentFolder = currentFolder.AddRange(parts);
if (builder.All(folders => !folders.SequenceEqual(defaultPathBasedOnCurrentFolder, PathUtilities.Comparer)))
{
builder.Add(defaultPathBasedOnCurrentFolder);
}
return builder.ToImmutableAndFree();
}
private class FolderInfo
{
private readonly Dictionary<string, FolderInfo> _childFolders;
public string Name { get; }
public IReadOnlyDictionary<string, FolderInfo> ChildFolders => _childFolders;
private FolderInfo(string name)
{
Name = name;
_childFolders = new Dictionary<string, FolderInfo>(StringComparer.Ordinal);
}
private void AddFolder(IEnumerable<string> folder)
{
if (!folder.Any())
{
return;
}
var firstFolder = folder.First();
if (!_childFolders.TryGetValue(firstFolder, out var firstFolderInfo))
{
firstFolderInfo = new FolderInfo(firstFolder);
_childFolders[firstFolder] = firstFolderInfo;
}
firstFolderInfo.AddFolder(folder.Skip(1));
}
// TODO:
// Since we are getting folder data from documents, only non-empty folders
// in the project are discovered. It's possible to get complete folder structure
// from VS but it requires UI thread to do so. We might want to revisit this later.
public static FolderInfo CreateFolderHierarchyForProject(Project project)
{
var handledFolders = new HashSet<string>(StringComparer.Ordinal);
var rootFolderInfo = new FolderInfo("<ROOT>");
foreach (var document in project.Documents)
{
var folders = document.Folders;
if (handledFolders.Add(string.Join(PathUtilities.DirectorySeparatorStr, folders)))
{
rootFolderInfo.AddFolder(folders);
}
}
return rootFolderInfo;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace
{
internal abstract partial class AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax>
: CodeRefactoringProvider
where TNamespaceDeclarationSyntax : SyntaxNode
where TCompilationUnitSyntax : SyntaxNode
where TMemberDeclarationSyntax : SyntaxNode
{
private class MoveFileCodeAction : CodeAction
{
private readonly State _state;
private readonly ImmutableArray<string> _newfolders;
public override string Title
=> _newfolders.Length > 0
? string.Format(FeaturesResources.Move_file_to_0, string.Join(PathUtilities.DirectorySeparatorStr, _newfolders))
: FeaturesResources.Move_file_to_project_root_folder;
public MoveFileCodeAction(State state, ImmutableArray<string> newFolders)
{
_state = state;
_newfolders = newFolders;
}
protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
{
var id = _state.Document.Id;
var solution = _state.Document.Project.Solution;
var document = solution.GetDocument(id);
var newDocumentId = DocumentId.CreateNewId(document.Project.Id, document.Name);
solution = solution.RemoveDocument(id);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
solution = solution.AddDocument(newDocumentId, document.Name, text, folders: _newfolders);
return ImmutableArray.Create<CodeActionOperation>(
new ApplyChangesOperation(solution),
new OpenDocumentOperation(newDocumentId, activateIfAlreadyOpen: true));
}
public static ImmutableArray<MoveFileCodeAction> Create(State state)
{
Debug.Assert(state.RelativeDeclaredNamespace != null);
// Since all documents have identical folder structure, we can do the computation on any of them.
var document = state.Document;
// In case the relative namespace is "", the file should be moved to project root,
// set `parts` to empty to indicate that.
var parts = state.RelativeDeclaredNamespace.Length == 0
? ImmutableArray<string>.Empty
: state.RelativeDeclaredNamespace.Split(new[] { '.' }).ToImmutableArray();
// Invalid char can only appear in namespace name when there's error,
// which we have checked before creating any code actions.
Debug.Assert(parts.IsEmpty || parts.Any(s => s.IndexOfAny(Path.GetInvalidPathChars()) < 0));
var projectRootFolder = FolderInfo.CreateFolderHierarchyForProject(document.Project);
var candidateFolders = FindCandidateFolders(projectRootFolder, parts, ImmutableArray<string>.Empty);
return candidateFolders.SelectAsArray(folders => new MoveFileCodeAction(state, folders));
}
/// <summary>
/// We try to provide additional "move file" options if we can find existing folders that matches target namespace.
/// For example, if the target namespace is 'DefaultNamesapce.A.B.C', and there's a folder 'ProjectRoot\A.B\' already
/// exists, then will provide two actions, "move file to ProjectRoot\A.B\C\" and "move file to ProjectRoot\A\B\C\".
/// </summary>
private static ImmutableArray<ImmutableArray<string>> FindCandidateFolders(
FolderInfo currentFolderInfo,
ImmutableArray<string> parts,
ImmutableArray<string> currentFolder)
{
if (parts.IsEmpty)
{
return ImmutableArray.Create(currentFolder);
}
// Try to figure out all possible folder names that can match the target namespace.
// For example, if the target is "A.B.C", then the matching folder names include
// "A", "A.B" and "A.B.C". The item "index" in the result tuple is the number
// of items in namespace parts used to construct iten "foldername".
var candidates = Enumerable.Range(1, parts.Length)
.Select(i => (foldername: string.Join(".", parts.Take(i)), index: i))
.ToImmutableDictionary(t => t.foldername, t => t.index, PathUtilities.Comparer);
var subFolders = currentFolderInfo.ChildFolders;
var builder = ArrayBuilder<ImmutableArray<string>>.GetInstance();
foreach (var (folderName, index) in candidates)
{
if (subFolders.TryGetValue(folderName, out var matchingFolderInfo))
{
var newParts = index >= parts.Length
? ImmutableArray<string>.Empty
: ImmutableArray.Create(parts, index, parts.Length - index);
var newCurrentFolder = currentFolder.Add(matchingFolderInfo.Name);
builder.AddRange(FindCandidateFolders(matchingFolderInfo, newParts, newCurrentFolder));
}
}
// Make sure we always have the default path as an available option to the user
// (which might have been found by the search above, therefore the check here)
// For example, if the target namespace is "A.B.C.D", and there's folder <ROOT>\A.B\,
// the search above would only return "<ROOT>\A.B\C\D". We'd want to provide
// "<ROOT>\A\B\C\D" as the default path.
var defaultPathBasedOnCurrentFolder = currentFolder.AddRange(parts);
if (builder.All(folders => !folders.SequenceEqual(defaultPathBasedOnCurrentFolder, PathUtilities.Comparer)))
{
builder.Add(defaultPathBasedOnCurrentFolder);
}
return builder.ToImmutableAndFree();
}
private class FolderInfo
{
private readonly Dictionary<string, FolderInfo> _childFolders;
public string Name { get; }
public IReadOnlyDictionary<string, FolderInfo> ChildFolders => _childFolders;
private FolderInfo(string name)
{
Name = name;
_childFolders = new Dictionary<string, FolderInfo>(StringComparer.Ordinal);
}
private void AddFolder(IEnumerable<string> folder)
{
if (!folder.Any())
{
return;
}
var firstFolder = folder.First();
if (!_childFolders.TryGetValue(firstFolder, out var firstFolderInfo))
{
firstFolderInfo = new FolderInfo(firstFolder);
_childFolders[firstFolder] = firstFolderInfo;
}
firstFolderInfo.AddFolder(folder.Skip(1));
}
// TODO:
// Since we are getting folder data from documents, only non-empty folders
// in the project are discovered. It's possible to get complete folder structure
// from VS but it requires UI thread to do so. We might want to revisit this later.
public static FolderInfo CreateFolderHierarchyForProject(Project project)
{
var handledFolders = new HashSet<string>(StringComparer.Ordinal);
var rootFolderInfo = new FolderInfo("<ROOT>");
foreach (var document in project.Documents)
{
var folders = document.Folders;
if (handledFolders.Add(string.Join(PathUtilities.DirectorySeparatorStr, folders)))
{
rootFolderInfo.AddFolder(folders);
}
}
return rootFolderInfo;
}
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/EditorFeatures/Core/EditorConfigSettings/Updater/AnalyzerSettingsUpdater.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater
{
internal class AnalyzerSettingsUpdater : SettingsUpdaterBase<AnalyzerSetting, DiagnosticSeverity>
{
public AnalyzerSettingsUpdater(Workspace workspace, string editorconfigPath) : base(workspace, editorconfigPath)
{
}
protected override SourceText? GetNewText(SourceText sourceText,
IReadOnlyList<(AnalyzerSetting option, DiagnosticSeverity value)> settingsToUpdate,
CancellationToken token)
=> SettingsUpdateHelper.TryUpdateAnalyzerConfigDocument(sourceText, EditorconfigPath, settingsToUpdate);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater
{
internal class AnalyzerSettingsUpdater : SettingsUpdaterBase<AnalyzerSetting, DiagnosticSeverity>
{
public AnalyzerSettingsUpdater(Workspace workspace, string editorconfigPath) : base(workspace, editorconfigPath)
{
}
protected override SourceText? GetNewText(SourceText sourceText,
IReadOnlyList<(AnalyzerSetting option, DiagnosticSeverity value)> settingsToUpdate,
CancellationToken token)
=> SettingsUpdateHelper.TryUpdateAnalyzerConfigDocument(sourceText, EditorconfigPath, settingsToUpdate);
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/Test/Core/Assert/XunitTraceListener.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System.Diagnostics;
using System.Text;
using Xunit.Abstractions;
namespace Roslyn.Test.Utilities
{
public sealed class XunitTraceListener : TraceListener
{
private readonly ITestOutputHelper _logger;
private readonly StringBuilder _lineInProgress = new StringBuilder();
private bool _disposed;
public XunitTraceListener(ITestOutputHelper logger)
=> _logger = logger;
public override bool IsThreadSafe
=> false;
public override void Write(string? message)
=> _lineInProgress.Append(message);
public override void WriteLine(string? message)
{
if (!_disposed)
{
_logger.WriteLine(_lineInProgress.ToString() + message);
_lineInProgress.Clear();
}
}
protected override void Dispose(bool disposing)
{
_disposed = true;
base.Dispose(disposing);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System.Diagnostics;
using System.Text;
using Xunit.Abstractions;
namespace Roslyn.Test.Utilities
{
public sealed class XunitTraceListener : TraceListener
{
private readonly ITestOutputHelper _logger;
private readonly StringBuilder _lineInProgress = new StringBuilder();
private bool _disposed;
public XunitTraceListener(ITestOutputHelper logger)
=> _logger = logger;
public override bool IsThreadSafe
=> false;
public override void Write(string? message)
=> _lineInProgress.Append(message);
public override void WriteLine(string? message)
{
if (!_disposed)
{
_logger.WriteLine(_lineInProgress.ToString() + message);
_lineInProgress.Clear();
}
}
protected override void Dispose(bool disposing)
{
_disposed = true;
base.Dispose(disposing);
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/EditorFeatures/Core/Shared/Utilities/ThreadingContextTaskSchedulerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
[ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Editor), Shared]
internal sealed class ThreadingContextTaskSchedulerProvider : ITaskSchedulerProvider
{
public TaskScheduler CurrentContextScheduler { get; }
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ThreadingContextTaskSchedulerProvider(IThreadingContext threadingContext)
{
CurrentContextScheduler = threadingContext.HasMainThread
? new JoinableTaskFactoryTaskScheduler(threadingContext.JoinableTaskFactory)
: TaskScheduler.Default;
}
private sealed class JoinableTaskFactoryTaskScheduler : TaskScheduler
{
private readonly JoinableTaskFactory _joinableTaskFactory;
public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory)
=> _joinableTaskFactory = joinableTaskFactory;
public override int MaximumConcurrencyLevel => 1;
protected override IEnumerable<Task> GetScheduledTasks()
=> SpecializedCollections.EmptyEnumerable<Task>();
protected override void QueueTask(Task task)
{
_joinableTaskFactory.RunAsync(async () =>
{
await _joinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true);
TryExecuteTask(task);
});
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (_joinableTaskFactory.Context.IsOnMainThread)
{
return TryExecuteTask(task);
}
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.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
[ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Editor), Shared]
internal sealed class ThreadingContextTaskSchedulerProvider : ITaskSchedulerProvider
{
public TaskScheduler CurrentContextScheduler { get; }
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ThreadingContextTaskSchedulerProvider(IThreadingContext threadingContext)
{
CurrentContextScheduler = threadingContext.HasMainThread
? new JoinableTaskFactoryTaskScheduler(threadingContext.JoinableTaskFactory)
: TaskScheduler.Default;
}
private sealed class JoinableTaskFactoryTaskScheduler : TaskScheduler
{
private readonly JoinableTaskFactory _joinableTaskFactory;
public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory)
=> _joinableTaskFactory = joinableTaskFactory;
public override int MaximumConcurrencyLevel => 1;
protected override IEnumerable<Task> GetScheduledTasks()
=> SpecializedCollections.EmptyEnumerable<Task>();
protected override void QueueTask(Task task)
{
_joinableTaskFactory.RunAsync(async () =>
{
await _joinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true);
TryExecuteTask(task);
});
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (_joinableTaskFactory.Context.IsOnMainThread)
{
return TryExecuteTask(task);
}
return false;
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Workspaces/Core/Portable/Shared/TestHooks/IAsyncToken.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.TestHooks
{
internal interface IAsyncToken : IDisposable
{
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.TestHooks
{
internal interface IAsyncToken : IDisposable
{
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_NullablePublicOnly.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AttributeTests_NullablePublicOnly : CSharpTestBase
{
[Fact]
public void ExplicitAttribute_FromSource()
{
var source =
@"public class A<T>
{
}
public class B : A<object?>
{
}";
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullablePublicOnlyAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true));
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: true, publicDefinition: true));
}
[Fact]
public void ExplicitAttribute_FromMetadata()
{
var source =
@"public class A<T>
{
}
public class B : A<object?>
{
}";
var comp = CreateCompilation(NullablePublicOnlyAttributeDefinition, parseOptions: TestOptions.Regular7);
comp.VerifyDiagnostics();
var ref1 = comp.EmitToImageReference();
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
comp = CreateCompilation(source, references: new[] { ref1 }, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: false, includesAttributeUse: false, publicDefinition: true));
comp = CreateCompilation(source, references: new[] { ref1 }, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: false, includesAttributeUse: true, publicDefinition: true));
}
[Fact]
public void ExplicitAttribute_MissingSingleValueConstructor()
{
var source1 =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullablePublicOnlyAttribute : Attribute
{
}
}";
var source2 =
@"public class A<T>
{
}
public class B : A<object?>
{
}";
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(new[] { source1, source2 }, options: options, parseOptions: parseOptions);
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(new[] { source1, source2 }, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullablePublicOnlyAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Runtime.CompilerServices.NullablePublicOnlyAttribute", ".ctor").WithLocation(1, 1));
}
[Fact]
public void EmptyProject()
{
var source = @"";
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void CSharp7_NoAttribute()
{
var source =
@"public class A<T>
{
}
public class B : A<object>
{
}";
var options = TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular7;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void NullableEnabled()
{
var source =
@"public class A<T>
{
}
public class B : A<object?>
{
}";
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNullablePublicOnlyAttribute);
}
[Fact]
public void NullableEnabled_NoPublicMembers()
{
var source =
@"class A<T>
{
}
class B : A<object?>
{
}";
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void NullableDisabled()
{
var source =
@"public class A<T>
{
}
public class B : A<object>
{
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void NullableDisabled_Annotation()
{
var source =
@"public class A<T>
{
}
public class B : A<object?>
{
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNullablePublicOnlyAttribute);
}
[Fact]
public void NullableDisabled_OtherNullableAttributeDefinitions()
{
var source =
@"public class Program
{
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void NullableEnabled_MethodBodyOnly()
{
var source0 =
@"#nullable enable
public class A
{
public static object? F;
public static void M(object o) { }
}";
var comp = CreateCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"public class B
{
static void Main()
{
#nullable enable
A.M(A.F);
}
}";
comp = CreateCompilation(
source1,
references: new[] { ref0 },
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular8.WithNullablePublicOnly());
comp.VerifyDiagnostics(
// (6,13): warning CS8604: Possible null reference argument for parameter 'o' in 'void A.M(object o)'.
// A.M(A.F);
Diagnostic(ErrorCode.WRN_NullReferenceArgument, "A.F").WithArguments("o", "void A.M(object o)").WithLocation(6, 13));
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void NullableEnabled_AllNullableAttributeDefinitions_01()
{
var source =
@"#nullable enable
public class Program
{
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, NullablePublicOnlyAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true));
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true));
}
[Fact]
public void NullableEnabled_AllNullableAttributeDefinitions_02()
{
var source =
@"#nullable enable
public class Program
{
public object F() => null!;
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, NullablePublicOnlyAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true));
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: true, publicDefinition: true));
}
[Fact]
public void NullableEnabled_OtherNullableAttributeDefinitions_01()
{
var source =
@"#nullable enable
public class Program
{
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void NullableEnabled_OtherNullableAttributeDefinitions_02()
{
var source =
@"#nullable enable
public class Program
{
public object F() => null!;
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNullablePublicOnlyAttribute);
}
[Fact]
public void LocalFunctionReturnType_SynthesizedAttributeDefinitions()
{
var source =
@"public class Program
{
static void Main()
{
#nullable enable
object? L() => null;
L();
}
}";
var options = TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void LocalFunctionReturnType_ExplicitAttributeDefinitions()
{
var source =
@"public class Program
{
static void Main()
{
#nullable enable
object? L() => null;
L();
}
}";
var options = TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, NullablePublicOnlyAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true));
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true));
}
[Fact]
[WorkItem(36457, "https://github.com/dotnet/roslyn/issues/36457")]
public void ExplicitAttribute_ReferencedInSource_Assembly()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
internal class NullablePublicOnlyAttribute : System.Attribute
{
internal NullablePublicOnlyAttribute(bool b) { }
}
}";
var source =
@"using System.Runtime.CompilerServices;
[assembly: NullablePublicOnly(false)]
[module: NullablePublicOnly(false)]
";
// C#7
var comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular7);
verifyDiagnostics(comp);
// C#8
comp = CreateCompilation(new[] { sourceAttribute, source });
verifyDiagnostics(comp);
static void verifyDiagnostics(CSharpCompilation comp)
{
comp.VerifyDiagnostics(
// (3,10): error CS8335: Do not use 'System.Runtime.CompilerServices.NullablePublicOnlyAttribute'. This is reserved for compiler usage.
// [module: NullablePublicOnly(false)]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullablePublicOnly(false)").WithArguments("System.Runtime.CompilerServices.NullablePublicOnlyAttribute").WithLocation(3, 10));
}
}
[Fact]
[WorkItem(36457, "https://github.com/dotnet/roslyn/issues/36457")]
public void ExplicitAttribute_ReferencedInSource_Other()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
internal class NullablePublicOnlyAttribute : System.Attribute
{
internal NullablePublicOnlyAttribute(bool b) { }
}
}";
var source =
@"using System.Runtime.CompilerServices;
[NullablePublicOnly(false)]
class Program
{
}";
var comp = CreateCompilation(new[] { sourceAttribute, source });
comp.VerifyDiagnostics();
}
[Fact]
public void ExplicitAttribute_WithNullableAttribute()
{
var sourceAttribute =
@"#nullable enable
namespace System.Runtime.CompilerServices
{
public class NullablePublicOnlyAttribute : System.Attribute
{
public NullablePublicOnlyAttribute(bool b) { }
public NullablePublicOnlyAttribute(
object x,
object? y,
#nullable disable
object z)
{
}
}
}";
var comp = CreateCompilation(sourceAttribute);
var ref0 = comp.EmitToImageReference();
var expected =
@"System.Runtime.CompilerServices.NullablePublicOnlyAttribute
NullablePublicOnlyAttribute(System.Object! x, System.Object? y, System.Object z)
[Nullable(1)] System.Object! x
[Nullable(2)] System.Object? y
";
AssertNullableAttributes(comp, expected);
var source =
@"#nullable enable
public class Program
{
public object _f1;
public object? _f2;
#nullable disable
public object _f3;
}";
comp = CreateCompilation(source, references: new[] { ref0 });
expected =
@"Program
[Nullable(1)] System.Object! _f1
[Nullable(2)] System.Object? _f2
";
AssertNullableAttributes(comp, expected);
}
[Fact]
[WorkItem(36934, "https://github.com/dotnet/roslyn/issues/36934")]
public void AttributeUsage()
{
var source =
@"#nullable enable
public class Program
{
public object? F;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithNullablePublicOnly(), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NullablePublicOnlyAttribute");
AttributeUsageInfo attributeUsage = attributeType.GetAttributeUsageInfo();
Assert.False(attributeUsage.Inherited);
Assert.False(attributeUsage.AllowMultiple);
Assert.True(attributeUsage.HasValidAttributeTargets);
Assert.Equal(AttributeTargets.Module, attributeUsage.ValidTargets);
});
}
[Fact]
public void MissingAttributeUsageAttribute()
{
var source =
@"#nullable enable
public class Program
{
public object? F;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithNullablePublicOnly());
comp.MakeTypeMissing(WellKnownType.System_AttributeUsageAttribute);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1));
}
[Fact]
public void AttributeField()
{
var source =
@"#nullable enable
using System;
using System.Linq;
using System.Reflection;
public class Program
{
public static void Main(string[] args)
{
var value = GetAttributeValue(typeof(Program).Assembly.Modules.First());
Console.WriteLine(value == null ? ""<null>"" : value.ToString());
}
static bool? GetAttributeValue(Module module)
{
var attribute = module.GetCustomAttributes(false).SingleOrDefault(a => a.GetType().Name == ""NullablePublicOnlyAttribute"");
if (attribute == null) return null;
var field = attribute.GetType().GetField(""IncludesInternals"");
return (bool)field.GetValue(attribute);
}
}";
var sourceIVTs =
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""Other"")]";
var parseOptions = TestOptions.Regular8;
CompileAndVerify(source, parseOptions: parseOptions, expectedOutput: "<null>");
CompileAndVerify(source, parseOptions: parseOptions.WithNullablePublicOnly(), expectedOutput: "False");
CompileAndVerify(new[] { source, sourceIVTs }, parseOptions: parseOptions, expectedOutput: "<null>");
CompileAndVerify(new[] { source, sourceIVTs }, parseOptions: parseOptions.WithNullablePublicOnly(), expectedOutput: "True");
}
private static void AssertNoNullablePublicOnlyAttribute(ModuleSymbol module)
{
AssertNullablePublicOnlyAttribute(module, includesAttributeDefinition: false, includesAttributeUse: false, publicDefinition: false);
}
private static void AssertNullablePublicOnlyAttribute(ModuleSymbol module)
{
AssertNullablePublicOnlyAttribute(module, includesAttributeDefinition: true, includesAttributeUse: true, publicDefinition: false);
}
private static void AssertNullablePublicOnlyAttribute(ModuleSymbol module, bool includesAttributeDefinition, bool includesAttributeUse, bool publicDefinition)
{
const string attributeName = "System.Runtime.CompilerServices.NullablePublicOnlyAttribute";
var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember(attributeName);
var attribute = module.GetAttributes().SingleOrDefault();
if (includesAttributeDefinition)
{
Assert.NotNull(type);
}
else
{
Assert.Null(type);
if (includesAttributeUse)
{
type = attribute.AttributeClass;
}
}
if (type is object)
{
Assert.Equal(publicDefinition ? Accessibility.Public : Accessibility.Internal, type.DeclaredAccessibility);
}
if (includesAttributeUse)
{
Assert.Equal(type, attribute.AttributeClass);
}
else
{
Assert.Null(attribute);
}
}
private void AssertNullableAttributes(CSharpCompilation comp, string expected)
{
CompileAndVerify(comp, symbolValidator: module => AssertNullableAttributes(module, expected));
}
private static void AssertNullableAttributes(ModuleSymbol module, string expected)
{
var actual = NullableAttributesVisitor.GetString((PEModuleSymbol)module);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AttributeTests_NullablePublicOnly : CSharpTestBase
{
[Fact]
public void ExplicitAttribute_FromSource()
{
var source =
@"public class A<T>
{
}
public class B : A<object?>
{
}";
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullablePublicOnlyAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true));
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: true, publicDefinition: true));
}
[Fact]
public void ExplicitAttribute_FromMetadata()
{
var source =
@"public class A<T>
{
}
public class B : A<object?>
{
}";
var comp = CreateCompilation(NullablePublicOnlyAttributeDefinition, parseOptions: TestOptions.Regular7);
comp.VerifyDiagnostics();
var ref1 = comp.EmitToImageReference();
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
comp = CreateCompilation(source, references: new[] { ref1 }, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: false, includesAttributeUse: false, publicDefinition: true));
comp = CreateCompilation(source, references: new[] { ref1 }, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: false, includesAttributeUse: true, publicDefinition: true));
}
[Fact]
public void ExplicitAttribute_MissingSingleValueConstructor()
{
var source1 =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullablePublicOnlyAttribute : Attribute
{
}
}";
var source2 =
@"public class A<T>
{
}
public class B : A<object?>
{
}";
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(new[] { source1, source2 }, options: options, parseOptions: parseOptions);
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(new[] { source1, source2 }, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullablePublicOnlyAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Runtime.CompilerServices.NullablePublicOnlyAttribute", ".ctor").WithLocation(1, 1));
}
[Fact]
public void EmptyProject()
{
var source = @"";
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void CSharp7_NoAttribute()
{
var source =
@"public class A<T>
{
}
public class B : A<object>
{
}";
var options = TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular7;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void NullableEnabled()
{
var source =
@"public class A<T>
{
}
public class B : A<object?>
{
}";
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNullablePublicOnlyAttribute);
}
[Fact]
public void NullableEnabled_NoPublicMembers()
{
var source =
@"class A<T>
{
}
class B : A<object?>
{
}";
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void NullableDisabled()
{
var source =
@"public class A<T>
{
}
public class B : A<object>
{
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void NullableDisabled_Annotation()
{
var source =
@"public class A<T>
{
}
public class B : A<object?>
{
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNullablePublicOnlyAttribute);
}
[Fact]
public void NullableDisabled_OtherNullableAttributeDefinitions()
{
var source =
@"public class Program
{
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void NullableEnabled_MethodBodyOnly()
{
var source0 =
@"#nullable enable
public class A
{
public static object? F;
public static void M(object o) { }
}";
var comp = CreateCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"public class B
{
static void Main()
{
#nullable enable
A.M(A.F);
}
}";
comp = CreateCompilation(
source1,
references: new[] { ref0 },
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular8.WithNullablePublicOnly());
comp.VerifyDiagnostics(
// (6,13): warning CS8604: Possible null reference argument for parameter 'o' in 'void A.M(object o)'.
// A.M(A.F);
Diagnostic(ErrorCode.WRN_NullReferenceArgument, "A.F").WithArguments("o", "void A.M(object o)").WithLocation(6, 13));
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void NullableEnabled_AllNullableAttributeDefinitions_01()
{
var source =
@"#nullable enable
public class Program
{
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, NullablePublicOnlyAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true));
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true));
}
[Fact]
public void NullableEnabled_AllNullableAttributeDefinitions_02()
{
var source =
@"#nullable enable
public class Program
{
public object F() => null!;
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, NullablePublicOnlyAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true));
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: true, publicDefinition: true));
}
[Fact]
public void NullableEnabled_OtherNullableAttributeDefinitions_01()
{
var source =
@"#nullable enable
public class Program
{
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void NullableEnabled_OtherNullableAttributeDefinitions_02()
{
var source =
@"#nullable enable
public class Program
{
public object F() => null!;
}";
var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNullablePublicOnlyAttribute);
}
[Fact]
public void LocalFunctionReturnType_SynthesizedAttributeDefinitions()
{
var source =
@"public class Program
{
static void Main()
{
#nullable enable
object? L() => null;
L();
}
}";
var options = TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(source, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute);
}
[Fact]
public void LocalFunctionReturnType_ExplicitAttributeDefinitions()
{
var source =
@"public class Program
{
static void Main()
{
#nullable enable
object? L() => null;
L();
}
}";
var options = TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, NullablePublicOnlyAttributeDefinition, source };
var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions);
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true));
comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly());
CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true));
}
[Fact]
[WorkItem(36457, "https://github.com/dotnet/roslyn/issues/36457")]
public void ExplicitAttribute_ReferencedInSource_Assembly()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
internal class NullablePublicOnlyAttribute : System.Attribute
{
internal NullablePublicOnlyAttribute(bool b) { }
}
}";
var source =
@"using System.Runtime.CompilerServices;
[assembly: NullablePublicOnly(false)]
[module: NullablePublicOnly(false)]
";
// C#7
var comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular7);
verifyDiagnostics(comp);
// C#8
comp = CreateCompilation(new[] { sourceAttribute, source });
verifyDiagnostics(comp);
static void verifyDiagnostics(CSharpCompilation comp)
{
comp.VerifyDiagnostics(
// (3,10): error CS8335: Do not use 'System.Runtime.CompilerServices.NullablePublicOnlyAttribute'. This is reserved for compiler usage.
// [module: NullablePublicOnly(false)]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullablePublicOnly(false)").WithArguments("System.Runtime.CompilerServices.NullablePublicOnlyAttribute").WithLocation(3, 10));
}
}
[Fact]
[WorkItem(36457, "https://github.com/dotnet/roslyn/issues/36457")]
public void ExplicitAttribute_ReferencedInSource_Other()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
internal class NullablePublicOnlyAttribute : System.Attribute
{
internal NullablePublicOnlyAttribute(bool b) { }
}
}";
var source =
@"using System.Runtime.CompilerServices;
[NullablePublicOnly(false)]
class Program
{
}";
var comp = CreateCompilation(new[] { sourceAttribute, source });
comp.VerifyDiagnostics();
}
[Fact]
public void ExplicitAttribute_WithNullableAttribute()
{
var sourceAttribute =
@"#nullable enable
namespace System.Runtime.CompilerServices
{
public class NullablePublicOnlyAttribute : System.Attribute
{
public NullablePublicOnlyAttribute(bool b) { }
public NullablePublicOnlyAttribute(
object x,
object? y,
#nullable disable
object z)
{
}
}
}";
var comp = CreateCompilation(sourceAttribute);
var ref0 = comp.EmitToImageReference();
var expected =
@"System.Runtime.CompilerServices.NullablePublicOnlyAttribute
NullablePublicOnlyAttribute(System.Object! x, System.Object? y, System.Object z)
[Nullable(1)] System.Object! x
[Nullable(2)] System.Object? y
";
AssertNullableAttributes(comp, expected);
var source =
@"#nullable enable
public class Program
{
public object _f1;
public object? _f2;
#nullable disable
public object _f3;
}";
comp = CreateCompilation(source, references: new[] { ref0 });
expected =
@"Program
[Nullable(1)] System.Object! _f1
[Nullable(2)] System.Object? _f2
";
AssertNullableAttributes(comp, expected);
}
[Fact]
[WorkItem(36934, "https://github.com/dotnet/roslyn/issues/36934")]
public void AttributeUsage()
{
var source =
@"#nullable enable
public class Program
{
public object? F;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithNullablePublicOnly(), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NullablePublicOnlyAttribute");
AttributeUsageInfo attributeUsage = attributeType.GetAttributeUsageInfo();
Assert.False(attributeUsage.Inherited);
Assert.False(attributeUsage.AllowMultiple);
Assert.True(attributeUsage.HasValidAttributeTargets);
Assert.Equal(AttributeTargets.Module, attributeUsage.ValidTargets);
});
}
[Fact]
public void MissingAttributeUsageAttribute()
{
var source =
@"#nullable enable
public class Program
{
public object? F;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithNullablePublicOnly());
comp.MakeTypeMissing(WellKnownType.System_AttributeUsageAttribute);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1));
}
[Fact]
public void AttributeField()
{
var source =
@"#nullable enable
using System;
using System.Linq;
using System.Reflection;
public class Program
{
public static void Main(string[] args)
{
var value = GetAttributeValue(typeof(Program).Assembly.Modules.First());
Console.WriteLine(value == null ? ""<null>"" : value.ToString());
}
static bool? GetAttributeValue(Module module)
{
var attribute = module.GetCustomAttributes(false).SingleOrDefault(a => a.GetType().Name == ""NullablePublicOnlyAttribute"");
if (attribute == null) return null;
var field = attribute.GetType().GetField(""IncludesInternals"");
return (bool)field.GetValue(attribute);
}
}";
var sourceIVTs =
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""Other"")]";
var parseOptions = TestOptions.Regular8;
CompileAndVerify(source, parseOptions: parseOptions, expectedOutput: "<null>");
CompileAndVerify(source, parseOptions: parseOptions.WithNullablePublicOnly(), expectedOutput: "False");
CompileAndVerify(new[] { source, sourceIVTs }, parseOptions: parseOptions, expectedOutput: "<null>");
CompileAndVerify(new[] { source, sourceIVTs }, parseOptions: parseOptions.WithNullablePublicOnly(), expectedOutput: "True");
}
private static void AssertNoNullablePublicOnlyAttribute(ModuleSymbol module)
{
AssertNullablePublicOnlyAttribute(module, includesAttributeDefinition: false, includesAttributeUse: false, publicDefinition: false);
}
private static void AssertNullablePublicOnlyAttribute(ModuleSymbol module)
{
AssertNullablePublicOnlyAttribute(module, includesAttributeDefinition: true, includesAttributeUse: true, publicDefinition: false);
}
private static void AssertNullablePublicOnlyAttribute(ModuleSymbol module, bool includesAttributeDefinition, bool includesAttributeUse, bool publicDefinition)
{
const string attributeName = "System.Runtime.CompilerServices.NullablePublicOnlyAttribute";
var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember(attributeName);
var attribute = module.GetAttributes().SingleOrDefault();
if (includesAttributeDefinition)
{
Assert.NotNull(type);
}
else
{
Assert.Null(type);
if (includesAttributeUse)
{
type = attribute.AttributeClass;
}
}
if (type is object)
{
Assert.Equal(publicDefinition ? Accessibility.Public : Accessibility.Internal, type.DeclaredAccessibility);
}
if (includesAttributeUse)
{
Assert.Equal(type, attribute.AttributeClass);
}
else
{
Assert.Null(attribute);
}
}
private void AssertNullableAttributes(CSharpCompilation comp, string expected)
{
CompileAndVerify(comp, symbolValidator: module => AssertNullableAttributes(module, expected));
}
private static void AssertNullableAttributes(ModuleSymbol module, string expected)
{
var actual = NullableAttributesVisitor.GetString((PEModuleSymbol)module);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual);
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/EditorFeatures/TestUtilities/Workspaces/TestWorkspaceFixture.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Xml;
using System.Xml.Linq;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public abstract class TestWorkspaceFixture : IDisposable
{
public int Position;
public string Code;
private TestWorkspace _workspace;
private TestHostDocument _currentDocument;
public TestHostDocument CurrentDocument => _currentDocument ?? _workspace.Documents.Single();
public TestWorkspace GetWorkspace(ExportProvider exportProvider = null)
{
_workspace = _workspace ?? CreateWorkspace(exportProvider);
return _workspace;
}
public TestWorkspace GetWorkspace(string markup, ExportProvider exportProvider = null, string workspaceKind = null)
{
// If it looks like XML, we'll treat it as XML; any parse error would be rejected and will throw.
// We'll do a case insensitive search here so if somebody has a lowercase W it'll be tried (and
// rejected by the XML parser) rather than treated as regular text.
if (markup.TrimStart().StartsWith("<Workspace>", StringComparison.OrdinalIgnoreCase))
{
CloseTextView();
_workspace?.Dispose();
_workspace = TestWorkspace.CreateWorkspace(XElement.Parse(markup), exportProvider: exportProvider, workspaceKind: workspaceKind);
_currentDocument = _workspace.Documents.First(d => d.CursorPosition.HasValue);
Position = _currentDocument.CursorPosition.Value;
Code = _currentDocument.GetTextBuffer().CurrentSnapshot.GetText();
return _workspace;
}
else
{
MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out Code, out Position);
var workspace = GetWorkspace(exportProvider);
_currentDocument = workspace.Documents.Single();
return workspace;
}
}
protected abstract TestWorkspace CreateWorkspace(ExportProvider exportProvider);
public void Dispose()
{
if (_workspace is null)
return;
try
{
CloseTextView();
_currentDocument = null;
Code = null;
Position = 0;
_workspace?.Dispose();
}
finally
{
_workspace = null;
}
}
public Document UpdateDocument(string text, SourceCodeKind sourceCodeKind, bool cleanBeforeUpdate = true)
{
var hostDocument = _currentDocument ?? (GetWorkspace()).Documents.Single();
// clear the document
if (cleanBeforeUpdate)
{
UpdateText(hostDocument.GetTextBuffer(), string.Empty);
}
// and set the content
UpdateText(hostDocument.GetTextBuffer(), text);
GetWorkspace().OnDocumentSourceCodeKindChanged(hostDocument.Id, sourceCodeKind);
return GetWorkspace().CurrentSolution.GetDocument(hostDocument.Id);
}
private static void UpdateText(ITextBuffer textBuffer, string text)
{
using (var edit = textBuffer.CreateEdit())
{
edit.Replace(0, textBuffer.CurrentSnapshot.Length, text);
edit.Apply();
}
}
private void CloseTextView()
{
// The standard use for TestWorkspaceFixture is to call this method in the test's dispose to make sure it's ready to be used for
// the next test. But some tests in a test class won't use it, so _workspace might still be null.
if (_workspace?.Documents != null)
{
foreach (var document in _workspace?.Documents)
{
document.CloseTextView();
}
}
// The editor caches TextFormattingRunProperties instances for better perf, but since things like
// Brushes are DispatcherObjects, they are tied to the thread they are created on. Since we're going
// to be run on a different thread, clear out their collection.
var textFormattingRunPropertiesType = typeof(VisualStudio.Text.Formatting.TextFormattingRunProperties);
var existingPropertiesField = textFormattingRunPropertiesType.GetField("ExistingProperties", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
var existingProperties = (List<VisualStudio.Text.Formatting.TextFormattingRunProperties>)existingPropertiesField.GetValue(null);
existingProperties.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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public abstract class TestWorkspaceFixture : IDisposable
{
public int Position;
public string Code;
private TestWorkspace _workspace;
private TestHostDocument _currentDocument;
public TestHostDocument CurrentDocument => _currentDocument ?? _workspace.Documents.Single();
public TestWorkspace GetWorkspace(ExportProvider exportProvider = null)
{
_workspace = _workspace ?? CreateWorkspace(exportProvider);
return _workspace;
}
public TestWorkspace GetWorkspace(string markup, ExportProvider exportProvider = null, string workspaceKind = null)
{
// If it looks like XML, we'll treat it as XML; any parse error would be rejected and will throw.
// We'll do a case insensitive search here so if somebody has a lowercase W it'll be tried (and
// rejected by the XML parser) rather than treated as regular text.
if (markup.TrimStart().StartsWith("<Workspace>", StringComparison.OrdinalIgnoreCase))
{
CloseTextView();
_workspace?.Dispose();
_workspace = TestWorkspace.CreateWorkspace(XElement.Parse(markup), exportProvider: exportProvider, workspaceKind: workspaceKind);
_currentDocument = _workspace.Documents.First(d => d.CursorPosition.HasValue);
Position = _currentDocument.CursorPosition.Value;
Code = _currentDocument.GetTextBuffer().CurrentSnapshot.GetText();
return _workspace;
}
else
{
MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out Code, out Position);
var workspace = GetWorkspace(exportProvider);
_currentDocument = workspace.Documents.Single();
return workspace;
}
}
protected abstract TestWorkspace CreateWorkspace(ExportProvider exportProvider);
public void Dispose()
{
if (_workspace is null)
return;
try
{
CloseTextView();
_currentDocument = null;
Code = null;
Position = 0;
_workspace?.Dispose();
}
finally
{
_workspace = null;
}
}
public Document UpdateDocument(string text, SourceCodeKind sourceCodeKind, bool cleanBeforeUpdate = true)
{
var hostDocument = _currentDocument ?? (GetWorkspace()).Documents.Single();
// clear the document
if (cleanBeforeUpdate)
{
UpdateText(hostDocument.GetTextBuffer(), string.Empty);
}
// and set the content
UpdateText(hostDocument.GetTextBuffer(), text);
GetWorkspace().OnDocumentSourceCodeKindChanged(hostDocument.Id, sourceCodeKind);
return GetWorkspace().CurrentSolution.GetDocument(hostDocument.Id);
}
private static void UpdateText(ITextBuffer textBuffer, string text)
{
using (var edit = textBuffer.CreateEdit())
{
edit.Replace(0, textBuffer.CurrentSnapshot.Length, text);
edit.Apply();
}
}
private void CloseTextView()
{
// The standard use for TestWorkspaceFixture is to call this method in the test's dispose to make sure it's ready to be used for
// the next test. But some tests in a test class won't use it, so _workspace might still be null.
if (_workspace?.Documents != null)
{
foreach (var document in _workspace?.Documents)
{
document.CloseTextView();
}
}
// The editor caches TextFormattingRunProperties instances for better perf, but since things like
// Brushes are DispatcherObjects, they are tied to the thread they are created on. Since we're going
// to be run on a different thread, clear out their collection.
var textFormattingRunPropertiesType = typeof(VisualStudio.Text.Formatting.TextFormattingRunProperties);
var existingPropertiesField = textFormattingRunPropertiesType.GetField("ExistingProperties", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
var existingProperties = (List<VisualStudio.Text.Formatting.TextFormattingRunProperties>)existingPropertiesField.GetValue(null);
existingProperties.Clear();
}
}
}
| -1 |
|
dotnet/roslyn | 55,290 | Fix 'quick info' and 'use explicit type' for implicit lambdas | CyrusNajmabadi | 2021-07-30T18:48:59Z | 2021-08-03T18:56:45Z | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | 416765ff976b2a2776c0103d3c7033f9b1667f27 | Fix 'quick info' and 'use explicit type' for implicit lambdas. | ./src/EditorFeatures/VisualBasicTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithNext.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.SplitOrMergeIfStatements
Partial Public NotInheritable Class MergeConsecutiveIfStatementsTests
<Theory>
<InlineData("[||]if a then")>
<InlineData("i[||]f a then")>
<InlineData("if[||] a then")>
<InlineData("if a [||]then")>
<InlineData("if a th[||]en")>
<InlineData("if a then[||]")>
<InlineData("[|if|] a then")>
<InlineData("[|if a then|]")>
Public Async Function MergedOnIfSpans(ifLine As String) As Task
Await TestInRegularAndScriptAsync(
$"class C
sub M(a as boolean, b as boolean)
{ifLine}
elseif b then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnIfExtendedStatementSelection() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
|] elseif b then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnIfFullSelectionWithoutElseIfClause() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
System.Console.WriteLine()|]
elseif b then
System.Console.WriteLine()
else
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
System.Console.WriteLine()
else
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnIfExtendedFullSelectionWithoutElseIfClause() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
System.Console.WriteLine()
|] elseif b then
System.Console.WriteLine()
else
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
System.Console.WriteLine()
else
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfFullSelectionWithElseIfClause() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()|]
else
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfExtendedFullSelectionWithElseIfClause() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()
|] else
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfFullSelectionWithElseIfElseClauses() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()
else
end if|]
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfExtendedFullSelectionWithElseIfElseClauses() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()
else
end if
|] end sub
end class")
End Function
<Theory>
<InlineData("if [||]a then")>
<InlineData("[|i|]f a then")>
<InlineData("[|if a|] then")>
<InlineData("if [|a|] then")>
<InlineData("if a [|then|]")>
Public Async Function NotMergedOnIfSpans(ifLine As String) As Task
Await TestMissingInRegularAndScriptAsync(
$"class C
sub M(a as boolean, b as boolean)
{ifLine}
elseif b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfOverreachingSelection() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
|]elseif b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfBodyStatementSelection() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a then
[|return|]
elseif b then
return
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnMiddleIfMergableWithNextOnly() As Task
Const Initial As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine(nothing)
[||]elseif b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine()
end if
end sub
end class"
Const Expected As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine(nothing)
elseif b OrElse c then
System.Console.WriteLine()
end if
end sub
end class"
Await TestActionCountAsync(Initial, 1)
Await TestInRegularAndScriptAsync(Initial, Expected)
End Function
<Fact>
Public Async Function MergedOnMiddleIfMergableWithPreviousOnly() As Task
Const Initial As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine()
[||]elseif b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine(nothing)
end if
end sub
end class"
Const Expected As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a OrElse b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine(nothing)
end if
end sub
end class"
Await TestActionCountAsync(Initial, 1)
Await TestInRegularAndScriptAsync(Initial, Expected)
End Function
<Fact>
Public Async Function MergedOnMiddleIfMergableWithBoth() As Task
Const Initial As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine()
[||]elseif b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine()
end if
end sub
end class"
Const Expected1 As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a OrElse b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine()
end if
end sub
end class"
Const Expected2 As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine()
elseif b OrElse c then
System.Console.WriteLine()
end if
end sub
end class"
Await TestActionCountAsync(Initial, 2)
Await TestInRegularAndScriptAsync(Initial, Expected1, index:=0)
Await TestInRegularAndScriptAsync(Initial, Expected2, index:=1)
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.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitOrMergeIfStatements
Partial Public NotInheritable Class MergeConsecutiveIfStatementsTests
<Theory>
<InlineData("[||]if a then")>
<InlineData("i[||]f a then")>
<InlineData("if[||] a then")>
<InlineData("if a [||]then")>
<InlineData("if a th[||]en")>
<InlineData("if a then[||]")>
<InlineData("[|if|] a then")>
<InlineData("[|if a then|]")>
Public Async Function MergedOnIfSpans(ifLine As String) As Task
Await TestInRegularAndScriptAsync(
$"class C
sub M(a as boolean, b as boolean)
{ifLine}
elseif b then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnIfExtendedStatementSelection() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
|] elseif b then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnIfFullSelectionWithoutElseIfClause() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
System.Console.WriteLine()|]
elseif b then
System.Console.WriteLine()
else
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
System.Console.WriteLine()
else
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnIfExtendedFullSelectionWithoutElseIfClause() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
System.Console.WriteLine()
|] elseif b then
System.Console.WriteLine()
else
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
System.Console.WriteLine()
else
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfFullSelectionWithElseIfClause() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()|]
else
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfExtendedFullSelectionWithElseIfClause() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()
|] else
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfFullSelectionWithElseIfElseClauses() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()
else
end if|]
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfExtendedFullSelectionWithElseIfElseClauses() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()
else
end if
|] end sub
end class")
End Function
<Theory>
<InlineData("if [||]a then")>
<InlineData("[|i|]f a then")>
<InlineData("[|if a|] then")>
<InlineData("if [|a|] then")>
<InlineData("if a [|then|]")>
Public Async Function NotMergedOnIfSpans(ifLine As String) As Task
Await TestMissingInRegularAndScriptAsync(
$"class C
sub M(a as boolean, b as boolean)
{ifLine}
elseif b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfOverreachingSelection() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
|]elseif b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfBodyStatementSelection() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a then
[|return|]
elseif b then
return
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnMiddleIfMergableWithNextOnly() As Task
Const Initial As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine(nothing)
[||]elseif b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine()
end if
end sub
end class"
Const Expected As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine(nothing)
elseif b OrElse c then
System.Console.WriteLine()
end if
end sub
end class"
Await TestActionCountAsync(Initial, 1)
Await TestInRegularAndScriptAsync(Initial, Expected)
End Function
<Fact>
Public Async Function MergedOnMiddleIfMergableWithPreviousOnly() As Task
Const Initial As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine()
[||]elseif b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine(nothing)
end if
end sub
end class"
Const Expected As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a OrElse b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine(nothing)
end if
end sub
end class"
Await TestActionCountAsync(Initial, 1)
Await TestInRegularAndScriptAsync(Initial, Expected)
End Function
<Fact>
Public Async Function MergedOnMiddleIfMergableWithBoth() As Task
Const Initial As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine()
[||]elseif b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine()
end if
end sub
end class"
Const Expected1 As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a OrElse b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine()
end if
end sub
end class"
Const Expected2 As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine()
elseif b OrElse c then
System.Console.WriteLine()
end if
end sub
end class"
Await TestActionCountAsync(Initial, 2)
Await TestInRegularAndScriptAsync(Initial, Expected1, index:=0)
Await TestInRegularAndScriptAsync(Initial, Expected2, index:=1)
End Function
End Class
End Namespace
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.