PatternTests.cs 17.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
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 PatternTests : EmitMetadataTestBase
    {
        [Fact, WorkItem(18811, "https://github.com/dotnet/roslyn/issues/18811")]
        public void MissingNullable_01()
        {
            var source = @"namespace System {
    public class Object { }
    public abstract class ValueType { }
    public struct Void { }
    public struct Boolean { }
    public struct Int32 { }
}
static class C {
    public static bool M() => ((object)123) is int i;
}
";
J
Jared Parsons 已提交
30
            var compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseDll);
31 32 33
            compilation.GetDiagnostics().Verify();
            compilation.GetEmitDiagnostics().Verify(
                // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
34
                Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1)
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
                );
        }

        [Fact, WorkItem(18811, "https://github.com/dotnet/roslyn/issues/18811")]
        public void MissingNullable_02()
        {
            var source = @"namespace System {
    public class Object { }
    public abstract class ValueType { }
    public struct Void { }
    public struct Boolean { }
    public struct Int32 { }
    public struct Nullable<T> where T : struct { }
}
static class C {
    public static bool M() => ((object)123) is int i;
}
";
J
Jared Parsons 已提交
53
            var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll);
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
            compilation.GetDiagnostics().Verify();
            compilation.GetEmitDiagnostics().Verify(
                // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
                Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion)
                );
        }

        [Fact]
        public void MissingNullable_03()
        {
            var source = @"namespace System {
    public class Object { }
    public abstract class ValueType { }
    public struct Void { }
    public struct Boolean { }
    public struct Int32 { }
    public struct Nullable<T> where T : struct { }
}
static class C {
    static void M1(int? x)
    {
        switch (x)
        {
            case int i: break;
        }
    }
    static bool M2(int? x) => x is int i;
}
";
J
Jared Parsons 已提交
83
            var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll);
84 85 86 87
            compilation.GetDiagnostics().Verify();
            compilation.GetEmitDiagnostics().Verify(
                // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
                Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1),
88 89 90
                // (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
                //             case int i: break;
                Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(14, 18),
91 92 93
                // (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault'
                //             case int i: break;
                Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(14, 18),
94
                // (12,17): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value'
95
                //         switch (x)
96
                Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x").WithArguments("System.Nullable`1", "get_Value").WithLocation(12, 17),
97 98 99
                // (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
                //     static bool M2(int? x) => x is int i;
                Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 36),
100 101 102
                // (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault'
                //     static bool M2(int? x) => x is int i;
                Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(17, 36),
103
                // (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value'
104
                //     static bool M2(int? x) => x is int i;
105
                Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_Value").WithLocation(17, 36)
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
                );
        }

        [Fact]
        public void MissingNullable_04()
        {
            var source = @"namespace System {
    public class Object { }
    public abstract class ValueType { }
    public struct Void { }
    public struct Boolean { }
    public struct Int32 { }
    public struct Nullable<T> where T : struct { public T GetValueOrDefault() => default(T); }
}
static class C {
    static void M1(int? x)
    {
        switch (x)
        {
            case int i: break;
        }
    }
    static bool M2(int? x) => x is int i;
}
";
J
Jared Parsons 已提交
131
            var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll);
132 133 134
            compilation.GetDiagnostics().Verify();
            compilation.GetEmitDiagnostics().Verify(
                // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
135
                Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1),
136 137 138
                // (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
                //             case int i: break;
                Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(14, 18),
139 140
                // (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
                //     static bool M2(int? x) => x is int i;
141
                Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 36)
142 143
                );
        }
144

145 146
        // PROTOTYPE(patterns2): code quality has regressed for this test because the lowering strategy reifies the boolean result of the if expression.
        [Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")]
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
        public void DoubleEvaluation01()
        {
            var source =
@"using System;
public class C
{
    public static void Main()
    {
        if (TryGet() is int index)
        {
            Console.WriteLine(index);
        }
    }

    public static int? TryGet()
    {
        Console.WriteLine(""eval"");
        return null;
    }
}";
J
Jared Parsons 已提交
167
            var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
168 169 170 171 172
            compilation.VerifyDiagnostics();
            var expectedOutput = @"eval";
            var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
            compVerifier.VerifyIL("C.Main",
@"{
173
  // Code size       44 (0x2c)
174 175 176
  .maxstack  1
  .locals init (int V_0, //index
                bool V_1,
177 178
                int? V_2,
                int V_3)
179 180 181 182
  IL_0000:  nop
  IL_0001:  call       ""int? C.TryGet()""
  IL_0006:  stloc.2
  IL_0007:  ldloca.s   V_2
183 184 185 186 187 188 189 190 191 192 193 194 195
  IL_0009:  call       ""bool int?.HasValue.get""
  IL_000e:  brfalse.s  IL_001d
  IL_0010:  ldloca.s   V_2
  IL_0012:  call       ""int int?.GetValueOrDefault()""
  IL_0017:  stloc.3
  IL_0018:  ldloc.3
  IL_0019:  stloc.0
  IL_001a:  ldc.i4.1
  IL_001b:  br.s       IL_001e
  IL_001d:  ldc.i4.0
  IL_001e:  stloc.1
  IL_001f:  ldloc.1
  IL_0020:  brfalse.s  IL_002b
196
  IL_0022:  nop
197 198 199 200 201
  IL_0023:  ldloc.0
  IL_0024:  call       ""void System.Console.WriteLine(int)""
  IL_0029:  nop
  IL_002a:  nop
  IL_002b:  ret
202 203 204
}");
        }

205
        [Fact, WorkItem(19122, "https://github.com/dotnet/roslyn/issues/19122")]
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
        public void PatternCrash_01()
        {
            var source = @"using System;
using System.Collections.Generic;
using System.Linq;

public class Class2 : IDisposable
{
    public Class2(bool parameter = false)
    {
    }

    public void Dispose()
    {
    }
}

class X<T>
{
    IdentityAccessor<T> idAccessor = new IdentityAccessor<T>();
    void Y<U>() where U : T
    {
        // BUG: The following line is the problem
        if (GetT().FirstOrDefault(p => idAccessor.GetId(p) == Guid.Empty) is U u)
        {
        }
    }

    IEnumerable<T> GetT()
    {
        yield return default(T);
    }
}
class IdentityAccessor<T>
{
    public Guid GetId(T t)
    {
        return Guid.Empty;
    }
}";
J
Jared Parsons 已提交
246
            var compilation = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { LinqAssemblyRef });
247 248 249 250
            compilation.VerifyDiagnostics();
            var compVerifier = CompileAndVerify(compilation);
            compVerifier.VerifyIL("X<T>.Y<U>",
@"{
251
  // Code size       71 (0x47)
252 253 254
  .maxstack  3
  .locals init (U V_0, //u
                bool V_1,
255 256
                T V_2,
                U V_3)
257 258 259 260 261 262 263
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  call       ""System.Collections.Generic.IEnumerable<T> X<T>.GetT()""
  IL_0007:  ldarg.0
  IL_0008:  ldftn      ""bool X<T>.<Y>b__1_0<U>(T)""
  IL_000e:  newobj     ""System.Func<T, bool>..ctor(object, System.IntPtr)""
  IL_0013:  call       ""T System.Linq.Enumerable.FirstOrDefault<T>(System.Collections.Generic.IEnumerable<T>, System.Func<T, bool>)""
264 265
  IL_0018:  stloc.2
  IL_0019:  ldloc.2
266
  IL_001a:  box        ""T""
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
  IL_001f:  brfalse.s  IL_003f
  IL_0021:  ldloc.2
  IL_0022:  box        ""T""
  IL_0027:  isinst     ""U""
  IL_002c:  brfalse.s  IL_003f
  IL_002e:  ldloc.2
  IL_002f:  box        ""T""
  IL_0034:  unbox.any  ""U""
  IL_0039:  stloc.3
  IL_003a:  ldloc.3
  IL_003b:  stloc.0
  IL_003c:  ldc.i4.1
  IL_003d:  br.s       IL_0040
  IL_003f:  ldc.i4.0
  IL_0040:  stloc.1
  IL_0041:  ldloc.1
  IL_0042:  brfalse.s  IL_0046
  IL_0044:  nop
  IL_0045:  nop
  IL_0046:  ret
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
}");
        }

        [Fact, WorkItem(24522, "https://github.com/dotnet/roslyn/issues/24522")]
        public void IgnoreDeclaredConversion_01()
        {
            var source =
@"class Base<T>
{
    public static implicit operator Derived(Base<T> obj)
    {
        return new Derived();
    }
}

class Derived : Base<object>
{
}

class Program
{
    static void Main(string[] args)
    {
        Base<object> x = new Derived();
        System.Console.WriteLine(x is Derived);
        System.Console.WriteLine(x is Derived y);
        switch (x)
        {
            case Derived z: System.Console.WriteLine(true); break;
        }
        System.Console.WriteLine(null != (x as Derived));
    }
}";
J
Jared Parsons 已提交
320
            var compilation = CreateCompilation(source, options: TestOptions.DebugExe, references: new[] { LinqAssemblyRef });
321 322 323 324 325 326 327 328 329
            compilation.VerifyDiagnostics();
            var expectedOutput =
@"True
True
True
True";
            var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
            compVerifier.VerifyIL("Program.Main",
@"{
330
  // Code size      113 (0x71)
331 332 333
  .maxstack  2
  .locals init (Base<object> V_0, //x
                Derived V_1, //y
N
Neal Gafter 已提交
334
                Derived V_2,
335 336 337
                Derived V_3, //z
                Base<object> V_4,
                Derived V_5,
N
Neal Gafter 已提交
338
                Base<object> V_6)
339 340 341 342 343 344 345 346 347 348
  IL_0000:  nop
  IL_0001:  newobj     ""Derived..ctor()""
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  isinst     ""Derived""
  IL_000d:  ldnull
  IL_000e:  cgt.un
  IL_0010:  call       ""void System.Console.WriteLine(bool)""
  IL_0015:  nop
  IL_0016:  ldloc.0
N
Neal Gafter 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
  IL_0017:  brfalse.s  IL_002d
  IL_0019:  ldloc.0
  IL_001a:  isinst     ""Derived""
  IL_001f:  brfalse.s  IL_002d
  IL_0021:  ldloc.0
  IL_0022:  castclass  ""Derived""
  IL_0027:  stloc.2
  IL_0028:  ldloc.2
  IL_0029:  stloc.1
  IL_002a:  ldc.i4.1
  IL_002b:  br.s       IL_002e
  IL_002d:  ldc.i4.0
  IL_002e:  call       ""void System.Console.WriteLine(bool)""
  IL_0033:  nop
  IL_0034:  ldloc.0
  IL_0035:  stloc.s    V_6
  IL_0037:  ldloc.s    V_6
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
  IL_0039:  stloc.s    V_4
  IL_003b:  ldloc.s    V_4
  IL_003d:  brfalse.s  IL_0061
  IL_003f:  ldloc.s    V_4
  IL_0041:  isinst     ""Derived""
  IL_0046:  brfalse.s  IL_0061
  IL_0048:  ldloc.s    V_4
  IL_004a:  castclass  ""Derived""
  IL_004f:  stloc.s    V_5
  IL_0051:  br.s       IL_0053
  IL_0053:  ldloc.s    V_5
  IL_0055:  stloc.3
  IL_0056:  br.s       IL_0058
  IL_0058:  ldc.i4.1
  IL_0059:  call       ""void System.Console.WriteLine(bool)""
  IL_005e:  nop
  IL_005f:  br.s       IL_0061
  IL_0061:  ldloc.0
  IL_0062:  isinst     ""Derived""
  IL_0067:  ldnull
  IL_0068:  cgt.un
  IL_006a:  call       ""void System.Console.WriteLine(bool)""
  IL_006f:  nop
  IL_0070:  ret
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
}");
        }

        [Fact]
        public void DoublePattern01()
        {
            var source =
@"using System;
class Program
{
    static bool P1(double d) => d is double.NaN;
    static bool P2(float f) => f is float.NaN;
    static bool P3(double d) => d is 3.14d;
    static bool P4(float f) => f is 3.14f;
    static bool P5(object o)
    {
        switch (o)
        {
            case double.NaN: return true;
            case float.NaN: return true;
            case 3.14d: return true;
            case 3.14f: return true;
            default: return false;
        }
    }
    public static void Main(string[] args)
    {
        Console.Write(P1(double.NaN));
        Console.Write(P1(1.0));
        Console.Write(P2(float.NaN));
        Console.Write(P2(1.0f));
        Console.Write(P3(3.14));
        Console.Write(P3(double.NaN));
        Console.Write(P4(3.14f));
        Console.Write(P4(float.NaN));
        Console.Write(P5(double.NaN));
        Console.Write(P5(0.0d));
        Console.Write(P5(float.NaN));
        Console.Write(P5(0.0f));
        Console.Write(P5(3.14d));
        Console.Write(P5(125));
        Console.Write(P5(3.14f));
        Console.Write(P5(1.0f));
    }
}";
435
            var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
            compilation.VerifyDiagnostics();
            var expectedOutput = @"TrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalse";
            var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
            compVerifier.VerifyIL("Program.P1",
@"{
  // Code size        7 (0x7)
  .maxstack  1
  IL_0000:  ldarg.0
  IL_0001:  call       ""bool double.IsNaN(double)""
  IL_0006:  ret
}");
            compVerifier.VerifyIL("Program.P2",
@"{
  // Code size        7 (0x7)
  .maxstack  1
  IL_0000:  ldarg.0
  IL_0001:  call       ""bool float.IsNaN(float)""
  IL_0006:  ret
}");
            compVerifier.VerifyIL("Program.P3",
@"{
  // Code size       13 (0xd)
  .maxstack  2
  IL_0000:  ldc.r8     3.14
  IL_0009:  ldarg.0
  IL_000a:  ceq
  IL_000c:  ret
}");
            compVerifier.VerifyIL("Program.P4",
@"{
  // Code size        9 (0x9)
  .maxstack  2
  IL_0000:  ldc.r4     3.14
  IL_0005:  ldarg.0
  IL_0006:  ceq
  IL_0008:  ret
}");
            compVerifier.VerifyIL("Program.P5",
@"{
475
  // Code size      125 (0x7d)
476 477 478 479 480
  .maxstack  2
  .locals init (object V_0,
                double V_1,
                float V_2,
                object V_3,
481
                bool V_4)
482 483 484 485 486 487
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  stloc.3
  IL_0003:  ldloc.3
  IL_0004:  stloc.0
  IL_0005:  ldloc.0
488
  IL_0006:  brfalse.s  IL_0075
489 490
  IL_0008:  ldloc.0
  IL_0009:  isinst     ""double""
491
  IL_000e:  brfalse.s  IL_0035
492 493 494 495 496
  IL_0010:  ldloc.0
  IL_0011:  unbox.any  ""double""
  IL_0016:  stloc.1
  IL_0017:  ldloc.1
  IL_0018:  call       ""bool double.IsNaN(double)""
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
  IL_001d:  brtrue.s   IL_0061
  IL_001f:  ldloc.0
  IL_0020:  isinst     ""double""
  IL_0025:  brfalse.s  IL_0075
  IL_0027:  ldc.r8     3.14
  IL_0030:  ldloc.1
  IL_0031:  beq.s      IL_006b
  IL_0033:  br.s       IL_0075
  IL_0035:  ldloc.0
  IL_0036:  brfalse.s  IL_0075
  IL_0038:  ldloc.0
  IL_0039:  isinst     ""float""
  IL_003e:  brfalse.s  IL_0075
  IL_0040:  ldloc.0
  IL_0041:  unbox.any  ""float""
  IL_0046:  stloc.2
  IL_0047:  ldloc.2
  IL_0048:  call       ""bool float.IsNaN(float)""
  IL_004d:  brtrue.s   IL_0066
  IL_004f:  ldloc.0
  IL_0050:  isinst     ""float""
  IL_0055:  brfalse.s  IL_0075
  IL_0057:  ldc.r4     3.14
  IL_005c:  ldloc.2
  IL_005d:  beq.s      IL_0070
  IL_005f:  br.s       IL_0075
  IL_0061:  ldc.i4.1
  IL_0062:  stloc.s    V_4
  IL_0064:  br.s       IL_007a
  IL_0066:  ldc.i4.1
  IL_0067:  stloc.s    V_4
  IL_0069:  br.s       IL_007a
  IL_006b:  ldc.i4.1
  IL_006c:  stloc.s    V_4
  IL_006e:  br.s       IL_007a
  IL_0070:  ldc.i4.1
  IL_0071:  stloc.s    V_4
  IL_0073:  br.s       IL_007a
  IL_0075:  ldc.i4.0
  IL_0076:  stloc.s    V_4
  IL_0078:  br.s       IL_007a
  IL_007a:  ldloc.s    V_4
  IL_007c:  ret
540 541
}");
        }
542 543
    }
}