LambdaTests.cs 137.6 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2 3 4 5

using System;
using System.IO;
using System.Linq;
6
using System.Text;
P
Pilchie 已提交
7 8 9
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
10
using Microsoft.CodeAnalysis.Emit;
P
Pilchie 已提交
11 12 13 14 15 16
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
C
Charles Stoner 已提交
17
    public class LambdaTests : CompilingTestBase
P
Pilchie 已提交
18
    {
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
        [Fact, WorkItem(37456, "https://github.com/dotnet/roslyn/issues/37456")]
        public void Verify37456()
        {
            var comp = CreateCompilation(@"
using System;
using System.Collections.Generic;
using System.Linq;

public static partial class EnumerableEx
{
    public static void Join1<TA, TKey, T>(this IEnumerable<TA> a, Func<TA, TKey> aKey, Func<TA, T> aSel, Func<TA, TA, T> sel)
    {
        KeyValuePair<TK, TV> Pair<TK, TV>(TK k, TV v) => new KeyValuePair<TK, TV>(k, v);

        _ = a.GroupJoin(a, aKey, aKey, (f, ss) => Pair(f, ss.Select(s => Pair(true, s)))); // simplified repro
    }

    public static IEnumerable<T> Join2<TA, TB, TKey, T>(this IEnumerable<TA> a, IEnumerable<TB> b, Func<TA, TKey> aKey, Func<TB, TKey> bKey, Func<TA, T> aSel, Func<TA, TB, T> sel, IEqualityComparer<TKey> comp) 
    {
        KeyValuePair<TK, TV> Pair<TK, TV>(TK k, TV v) => new KeyValuePair<TK, TV>(k, v);

        return
            from j in a.GroupJoin(b, aKey, bKey, (f, ss) => Pair(f, from s in ss select Pair(true, s)), comp)
            from s in j.Value.DefaultIfEmpty()
            select s.Key ? sel(j.Key, s.Value) : aSel(j.Key);
    }
}");

            comp.VerifyDiagnostics();
            CompileAndVerify(comp);
            // emitting should not hang
        }

J
Jared Parsons 已提交
52
        [Fact, WorkItem(608181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608181")]
P
Pilchie 已提交
53 54 55 56 57 58 59 60 61 62
        public void BadInvocationInLambda()
        {
            var src = @"
using System;
using System.Linq.Expressions;

class C
{
    Expression<Action<dynamic>> e = x => new object[](x);
}";
J
Jared Parsons 已提交
63
            var comp = CreateCompilationWithMscorlib40AndSystemCore(src);
P
Pilchie 已提交
64 65 66
            comp.VerifyDiagnostics(
                // (7,52): error CS1586: Array creation must have array size or array initializer
                //     Expression<Action<dynamic>> e = x => new object[](x);
67
                Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(7, 52)
68
                );
P
Pilchie 已提交
69 70 71 72 73
        }

        [Fact]
        public void TestLambdaErrors01()
        {
J
Jared Parsons 已提交
74
            var comp = CreateCompilationWithMscorlib40AndSystemCore(@"
P
Pilchie 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
using System;
using System.Linq.Expressions;

namespace System.Linq.Expressions
{
    public class Expression<T> {}
}

class C 
{ 
    delegate void D1(ref int x, out int y, int z);
    delegate void D2(out int x);
    void M() 
    { 
        int q1 = ()=>1;
        int q2 = delegate { return 1; };
        Func<int> q3 = x3=>1;
        Func<int, int> q4 = (System.Itn23 x4)=>1; // type mismatch error should be suppressed on error type
        Func<double> q5 = (System.Duobel x5)=>1;  // but arity error should not be suppressed on error type
        D1 q6 = (double x6, ref int y6, ref int z6)=>1; 

        // COMPATIBILITY: The C# 4 compiler produces two errors:
        //
        // error CS1676: Parameter 2 must be declared with the 'out' keyword
        // error CS1688: Cannot convert anonymous method block without a parameter list 
        // to delegate type 'D1' because it has one or more out parameters
        //
        // This seems redundant (because there is no 'parameter 2' in the source code)
        // I propose that we eliminate the first error.

        D1 q7 = delegate {};

        Frob q8 = ()=>{};

        D2 q9 = x9=>{};

        D1 q10 = (x10,y10,z10)=>{}; 

113
        // COMPATIBILITY: The C# 4 compiler produces two errors:
P
Pilchie 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
        //
        // error CS0127: Since 'System.Action' returns void, a return keyword must 
        // not be followed by an object expression
        //
        // error CS1662: Cannot convert lambda expression to delegate type 'System.Action' 
        // because some of the return types in the block are not implicitly convertible to 
        // the delegate return type
        //
        // The problem is adequately characterized by the first message; I propose we 
        // eliminate the second, which seems both redundant and wrong.

        Action q11 = ()=>{ return 1; };

        Action q12 = ()=>1;

        Func<int> q13 = ()=>{ if (false) return 1; };

        Func<int> q14 = ()=>123.456;

        // Note that the type error is still an error even if the offending 
        // return is unreachable.
        Func<double> q15 = ()=>{if (false) return 1m; else return 0; };
        // In the native compiler these errors were caught at parse time. In Roslyn, these are now semantic
        // analysis errors. See changeset 1674 for details.

        Action<int[]> q16 = delegate (params int[] p) { };
        Action<string[]> q17 = (params string[] s)=>{};
        Action<int, double[]> q18 = (int x, params double[] s)=>{};

        object q19 = new Action( (int x)=>{} );
 
145
        Expression<int> ex1 = ()=>1;
P
Pilchie 已提交
146 147 148 149 150 151 152 153 154 155 156

    }
}");

            comp.VerifyDiagnostics(
    // (16,18): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type
    //         int q1 = ()=>1;
    Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "()=>1").WithArguments("lambda expression", "int").WithLocation(16, 18),
    // (17,18): error CS1660: Cannot convert anonymous method to type 'int' because it is not a delegate type
    //         int q2 = delegate { return 1; };
    Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate { return 1; }").WithArguments("anonymous method", "int").WithLocation(17, 18),
157
    // (18,24): error CS1593: Delegate 'Func<int>' does not take 1 arguments
P
Pilchie 已提交
158 159 160 161 162 163 164 165
    //         Func<int> q3 = x3=>1;
    Diagnostic(ErrorCode.ERR_BadDelArgCount, "x3=>1").WithArguments("System.Func<int>", "1").WithLocation(18, 24),
    // (19,37): error CS0234: The type or namespace name 'Itn23' does not exist in the namespace 'System' (are you missing an assembly reference?)
    //         Func<int, int> q4 = (System.Itn23 x4)=>1; // type mismatch error should be suppressed on error type
    Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Itn23").WithArguments("Itn23", "System").WithLocation(19, 37),
    // (20,35): error CS0234: The type or namespace name 'Duobel' does not exist in the namespace 'System' (are you missing an assembly reference?)
    //         Func<double> q5 = (System.Duobel x5)=>1;  // but arity error should not be suppressed on error type
    Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Duobel").WithArguments("Duobel", "System").WithLocation(20, 35),
166
    // (20,27): error CS1593: Delegate 'Func<double>' does not take 1 arguments
P
Pilchie 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
    //         Func<double> q5 = (System.Duobel x5)=>1;  // but arity error should not be suppressed on error type
    Diagnostic(ErrorCode.ERR_BadDelArgCount, "(System.Duobel x5)=>1").WithArguments("System.Func<double>", "1").WithLocation(20, 27),
    // (21,17): error CS1661: Cannot convert lambda expression to delegate type 'C.D1' because the parameter types do not match the delegate parameter types
    //         D1 q6 = (double x6, ref int y6, ref int z6)=>1; 
    Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(double x6, ref int y6, ref int z6)=>1").WithArguments("lambda expression", "C.D1").WithLocation(21, 17),
    // (21,25): error CS1678: Parameter 1 is declared as type 'double' but should be 'ref int'
    //         D1 q6 = (double x6, ref int y6, ref int z6)=>1; 
    Diagnostic(ErrorCode.ERR_BadParamType, "x6").WithArguments("1", "", "double", "ref ", "int").WithLocation(21, 25),
    // (21,37): error CS1676: Parameter 2 must be declared with the 'out' keyword
    //         D1 q6 = (double x6, ref int y6, ref int z6)=>1; 
    Diagnostic(ErrorCode.ERR_BadParamRef, "y6").WithArguments("2", "out").WithLocation(21, 37),
    // (21,49): error CS1677: Parameter 3 should not be declared with the 'ref' keyword
    //         D1 q6 = (double x6, ref int y6, ref int z6)=>1; 
    Diagnostic(ErrorCode.ERR_BadParamExtraRef, "z6").WithArguments("3", "ref").WithLocation(21, 49),
    // (32,17): error CS1688: Cannot convert anonymous method block without a parameter list to delegate type 'C.D1' because it has one or more out parameters
    //         D1 q7 = delegate {};
    Diagnostic(ErrorCode.ERR_CantConvAnonMethNoParams, "delegate {}").WithArguments("C.D1").WithLocation(32, 17),
    // (34,9): error CS0246: The type or namespace name 'Frob' could not be found (are you missing a using directive or an assembly reference?)
    //         Frob q8 = ()=>{};
    Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Frob").WithArguments("Frob").WithLocation(34, 9),
    // (36,17): error CS1676: Parameter 1 must be declared with the 'out' keyword
    //         D2 q9 = x9=>{};
    Diagnostic(ErrorCode.ERR_BadParamRef, "x9").WithArguments("1", "out").WithLocation(36, 17),
    // (38,19): error CS1676: Parameter 1 must be declared with the 'ref' keyword
    //         D1 q10 = (x10,y10,z10)=>{}; 
    Diagnostic(ErrorCode.ERR_BadParamRef, "x10").WithArguments("1", "ref").WithLocation(38, 19),
    // (38,23): error CS1676: Parameter 2 must be declared with the 'out' keyword
    //         D1 q10 = (x10,y10,z10)=>{}; 
    Diagnostic(ErrorCode.ERR_BadParamRef, "y10").WithArguments("2", "out").WithLocation(38, 23),
    // (52,28): error CS8030: Anonymous function converted to a void returning delegate cannot return a value
    //         Action q11 = ()=>{ return 1; };
    Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(52, 28),
199
    // (54,26): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
P
Pilchie 已提交
200 201 202 203 204
    //         Action q12 = ()=>1;
    Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(54, 26),
    // (56,42): warning CS0162: Unreachable code detected
    //         Func<int> q13 = ()=>{ if (false) return 1; };
    Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(56, 42),
205
    // (56,27): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>'
P
Pilchie 已提交
206
    //         Func<int> q13 = ()=>{ if (false) return 1; };
207
    Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(56, 27),
P
Pilchie 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    // (58,29): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
    //         Func<int> q14 = ()=>123.456;
    Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "123.456").WithArguments("double", "int").WithLocation(58, 29),
    // (58,29): 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<int> q14 = ()=>123.456;
    Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "123.456").WithArguments("lambda expression").WithLocation(58, 29),
    // (62,51): error CS0266: Cannot implicitly convert type 'decimal' to 'double'. An explicit conversion exists (are you missing a cast?)
    //         Func<double> q15 = ()=>{if (false) return 1m; else return 0; };
    Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1m").WithArguments("decimal", "double").WithLocation(62, 51),
    // (62,51): 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<double> q15 = ()=>{if (false) return 1m; else return 0; };
    Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1m").WithArguments("lambda expression").WithLocation(62, 51),
    // (62,44): warning CS0162: Unreachable code detected
    //         Func<double> q15 = ()=>{if (false) return 1m; else return 0; };
    Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(62, 44),
    // (66,39): error CS1670: params is not valid in this context
    //         Action<int[]> q16 = delegate (params int[] p) { };
    Diagnostic(ErrorCode.ERR_IllegalParams, "params int[] p").WithLocation(66, 39),
    // (67,33): error CS1670: params is not valid in this context
    //         Action<string[]> q17 = (params string[] s)=>{};
    Diagnostic(ErrorCode.ERR_IllegalParams, "params string[] s").WithLocation(67, 33),
    // (68,45): error CS1670: params is not valid in this context
    //         Action<int, double[]> q18 = (int x, params double[] s)=>{};
    Diagnostic(ErrorCode.ERR_IllegalParams, "params double[] s").WithLocation(68, 45),
232
    // (70,34): error CS1593: Delegate 'Action' does not take 1 arguments
P
Pilchie 已提交
233 234
    //         object q19 = new Action( (int x)=>{} );
    Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int x)=>{}").WithArguments("System.Action", "1").WithLocation(70, 34),
235
    // (72,9): warning CS0436: The type 'Expression<T>' in '' conflicts with the imported type 'Expression<TDelegate>' in 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
P
Pilchie 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    //         Expression<int> ex1 = ()=>1;  
    Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Expression<int>").WithArguments("", "System.Linq.Expressions.Expression<T>", "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Linq.Expressions.Expression<TDelegate>").WithLocation(72, 9),
    // (72,31): error CS0835: Cannot convert lambda to an expression tree whose type argument 'int' is not a delegate type
    //         Expression<int> ex1 = ()=>1;  
    Diagnostic(ErrorCode.ERR_ExpressionTreeMustHaveDelegate, "()=>1").WithArguments("int").WithLocation(72, 31)
                );
        }

        [Fact] // 5368
        public void TestLambdaErrors02()
        {
            string code = @"
class C
{
    void M()
    {
        System.Func<int, int> del = x => x + 1;
    }
}";
J
Jared Parsons 已提交
255
            var compilation = CreateCompilation(code);
256
            compilation.VerifyDiagnostics(); // no errors expected
P
Pilchie 已提交
257 258
        }

J
Jared Parsons 已提交
259
        [WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
P
Pilchie 已提交
260 261 262
        [Fact]
        public void TestLambdaErrors03()
        {
263
            string source = @"
P
Pilchie 已提交
264 265 266 267 268 269
using System;

interface I : IComparable<IComparable<I>> { }

class C
{
270 271
    static void Goo(Func<IComparable<I>> x) { }
    static void Goo(Func<I> x) {}
P
Pilchie 已提交
272 273
    static void M()
    {
274
        Goo(() => null);
P
Pilchie 已提交
275 276
    }
}
277
";
J
Jared Parsons 已提交
278
            CreateCompilation(source).VerifyDiagnostics(
279 280 281
                // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.Goo(Func<IComparable<I>>)' and 'C.Goo(Func<I>)'
                //         Goo(() => null);
                Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("C.Goo(System.Func<System.IComparable<I>>)", "C.Goo(System.Func<I>)").WithLocation(12, 9));
P
Pilchie 已提交
282 283
        }

284 285 286 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
        [WorkItem(18645, "https://github.com/dotnet/roslyn/issues/18645")]
        [Fact]
        public void LambdaExpressionTreesErrors()
        {
            string source = @"
using System;
using System.Linq.Expressions;

class C
{
    void M()
    {
        Expression<Func<int,int>> ex1 = () => 1;
        Expression<Func<int,int>> ex2 = (double d) => 1;
    }
}
";

            CreateCompilation(source).VerifyDiagnostics(
                // (9,41): error CS1593: Delegate 'Func<int, int>' does not take 0 arguments
                //         Expression<Func<int,int>> ex1 = () => 1;
                Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => 1").WithArguments("System.Func<int, int>", "0").WithLocation(9, 41),
                // (10,41): error CS1661: Cannot convert lambda expression to type 'Expression<Func<int, int>>' because the parameter types do not match the delegate parameter types
                //         Expression<Func<int,int>> ex2 = (double d) => 1;
                Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(double d) => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<int, int>>").WithLocation(10, 41),
                // (10,49): error CS1678: Parameter 1 is declared as type 'double' but should be 'int'
                //         Expression<Func<int,int>> ex2 = (double d) => 1;
                Diagnostic(ErrorCode.ERR_BadParamType, "d").WithArguments("1", "", "double", "", "int").WithLocation(10, 49));
        }

J
Jared Parsons 已提交
314
        [WorkItem(539976, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539976")]
P
Pilchie 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
        [Fact]
        public void LambdaArgumentToOverloadedDelegate()
        {
            var text = @"class W
{
    delegate T Func<A0, T>(A0 a0);

    static int F(Func<short, int> f) { return 0; }
    static int F(Func<short, double> f) { return 1; }

    static int Main()
    {
        return F(c => c);
    }
}
";
J
Jared Parsons 已提交
331
            var comp = CreateCompilation(Parse(text));
P
Pilchie 已提交
332 333 334
            comp.VerifyDiagnostics();
        }

J
Jared Parsons 已提交
335
        [WorkItem(528044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528044")]
P
Pilchie 已提交
336 337 338 339 340 341 342
        [Fact]
        public void MissingReferenceInOverloadResolution()
        {
            var text1 = @"
using System;
public static class A
{
343 344
    public static void Goo(Func<B, object> func) { }
    public static void Goo(Func<C, object> func) { }
P
Pilchie 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
}

public class B
{
    public Uri GetUrl()
    {
        return null;
    }
}

public class C
{
    public string GetUrl()
    {
        return null;
    }
}";

J
Jared Parsons 已提交
363 364
            var comp1 = CreateCompilationWithMscorlib40(
                new[] { Parse(text1) },
P
Pilchie 已提交
365 366 367 368 369 370 371
                new[] { TestReferences.NetFx.v4_0_30319.System });

            var text2 = @"
class Program
{
    static void Main()
    {
372
        A.Goo(x => x.GetUrl());
P
Pilchie 已提交
373 374 375 376
    }
}
";

J
Jared Parsons 已提交
377 378
            var comp2 = CreateCompilationWithMscorlib40(
                new[] { Parse(text2) },
P
Pilchie 已提交
379 380 381 382 383
                new[] { new CSharpCompilationReference(comp1) });

            Assert.Equal(0, comp2.GetDiagnostics().Count());
        }

J
Jared Parsons 已提交
384
        [WorkItem(528047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528047")]
P
Pilchie 已提交
385 386 387 388 389 390 391 392 393 394
        [Fact()]
        public void OverloadResolutionWithEmbeddedInteropType()
        {
            var text1 = @"
using System;
using System.Collections.Generic;
using stdole;

public static class A
{
395
    public static void Goo(Func<X> func) 
P
Pilchie 已提交
396 397 398
    { 
        System.Console.WriteLine(""X"");
}
399
    public static void Goo(Func<Y> func) 
P
Pilchie 已提交
400 401 402 403 404 405 406 407 408
    { 
        System.Console.WriteLine(""Y"");
    }
}

public delegate void X(List<IDispatch> addin);
public delegate void Y(List<string> addin);
";

J
Jared Parsons 已提交
409
            var comp1 = CreateCompilation(
P
Pilchie 已提交
410 411
                Parse(text1),
                new[] { TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true) },
412
                options: TestOptions.ReleaseDll);
P
Pilchie 已提交
413 414 415 416 417 418

            var text2 = @"
public class Program
{
    public static void Main()
    {
419
        A.Goo(() => delegate { });
P
Pilchie 已提交
420 421 422 423
    }
}
";

J
Jared Parsons 已提交
424
            var comp2 = CreateCompilation(
P
Pilchie 已提交
425 426 427 428 429 430
                Parse(text2),
                new MetadataReference[]
                    {
                        new CSharpCompilationReference(comp1),
                        TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true)
                    },
431
                options: TestOptions.ReleaseExe);
P
Pilchie 已提交
432 433 434

            CompileAndVerify(comp2, expectedOutput: "Y").Diagnostics.Verify();

J
Jared Parsons 已提交
435
            var comp3 = CreateCompilation(
P
Pilchie 已提交
436 437 438 439 440 441
                Parse(text2),
                new MetadataReference[]
                    {
                        comp1.EmitToImageReference(),
                        TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true)
                    },
442
                options: TestOptions.ReleaseExe);
P
Pilchie 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464

            CompileAndVerify(comp3, expectedOutput: "Y").Diagnostics.Verify();
        }

        [WorkItem(6358, "DevDiv_Projects/Roslyn")]
        [Fact]
        public void InvalidExpressionInvolveLambdaOperator()
        {
            var text1 = @"
class C
{
    static void X() 
    {
        int x=0; int y=0;
        if(x-=>*y)  // CS1525
            return;

        return; 
    }
}
";

J
Jared Parsons 已提交
465
            var comp = CreateCompilation(Parse(text1));
P
Pilchie 已提交
466 467 468 469 470
            var errs = comp.GetDiagnostics();
            Assert.True(0 < errs.Count(), "Diagnostics not empty");
            Assert.True(0 < errs.Where(e => e.Code == 1525).Select(e => e).Count(), "Diagnostics contains CS1525");
        }

J
Jared Parsons 已提交
471
        [WorkItem(540219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540219")]
P
Pilchie 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
        [Fact]
        public void OverloadResolutionWithStaticType()
        {
            var vbSource = @"
Imports System

Namespace Microsoft.VisualBasic.CompilerServices

    <System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)>
    Public NotInheritable Class StandardModuleAttribute
      Inherits System.Attribute

      Public Sub New()
        MyBase.New()
      End Sub

    End Class

End Namespace


Public Module M
494
  Sub Goo(x as Action(Of String))
P
Pilchie 已提交
495
  End Sub
496
  Sub Goo(x as Action(Of GC))
P
Pilchie 已提交
497 498 499 500
  End Sub
End Module
";

A
angocke 已提交
501
            var vbProject = VisualBasic.VisualBasicCompilation.Create(
P
Pilchie 已提交
502 503
                "VBProject",
                references: new[] { MscorlibRef },
A
angocke 已提交
504
                syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) });
P
Pilchie 已提交
505 506 507 508 509 510

            var csSource = @"
class Program
{
    static void Main()
    {
511
        M.Goo(x => { });
P
Pilchie 已提交
512 513 514 515
    }
}
";
            var metadataStream = new MemoryStream();
516
            var emitResult = vbProject.Emit(metadataStream, options: new EmitOptions(metadataOnly: true));
P
Pilchie 已提交
517 518
            Assert.True(emitResult.Success);

J
Jared Parsons 已提交
519
            var csProject = CreateCompilation(
P
Pilchie 已提交
520
                Parse(csSource),
521
                new[] { MetadataReference.CreateFromImage(metadataStream.ToImmutable()) });
P
Pilchie 已提交
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550

            Assert.Equal(0, csProject.GetDiagnostics().Count());
        }

        [Fact]
        public void OverloadResolutionWithStaticTypeError()
        {
            var vbSource = @"
Imports System

Namespace Microsoft.VisualBasic.CompilerServices

    <System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)>
    Public NotInheritable Class StandardModuleAttribute
      Inherits System.Attribute

      Public Sub New()
        MyBase.New()
      End Sub

    End Class

End Namespace

Public Module M
  Public Dim F As Action(Of GC)
End Module
";

A
angocke 已提交
551
            var vbProject = VisualBasic.VisualBasicCompilation.Create(
P
Pilchie 已提交
552 553
                "VBProject",
                references: new[] { MscorlibRef },
A
angocke 已提交
554
                syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) });
P
Pilchie 已提交
555 556 557 558 559 560 561 562 563 564

            var csSource = @"
class Program
{
    static void Main()
    {
        M.F = x=>{};
    }
}
";
565
            var vbMetadata = vbProject.EmitToArray(options: new EmitOptions(metadataOnly: true));
J
Jared Parsons 已提交
566
            var csProject = CreateCompilation(Parse(csSource), new[] { MetadataReference.CreateFromImage(vbMetadata) });
P
Pilchie 已提交
567 568 569

            var diagnostics = csProject.GetDiagnostics().Select(DumpDiagnostic);
            Assert.Equal(1, diagnostics.Count());
570
            Assert.Equal("'x' error CS0721: 'GC': static types cannot be used as parameters", diagnostics.First());
P
Pilchie 已提交
571 572
        }

J
Jared Parsons 已提交
573
        [WorkItem(540251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540251")]
P
Pilchie 已提交
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
        [Fact]
        public void AttributesCannotBeUsedInAnonymousMethods()
        {
            var csSource = @"
using System;

class Program
{
    static void Main()
    {
        const string message = ""The parameter is obsolete"";
        Action<int> a = delegate ([ObsoleteAttribute(message)] int x) { };
    }
}
";

J
Jared Parsons 已提交
590
            var csProject = CreateCompilation(csSource);
P
Pilchie 已提交
591 592 593 594 595 596 597

            var emitResult = csProject.Emit(Stream.Null);
            Assert.False(emitResult.Success);
            Assert.True(emitResult.Diagnostics.Any());
            // TODO: check error code
        }

J
Jared Parsons 已提交
598
        [WorkItem(540263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540263")]
P
Pilchie 已提交
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
        [Fact]
        public void ErrorsInUnboundLambdas()
        {
            var csSource = @"using System;

class Program
{
    static void Main()
    {
        ((Func<int>)delegate { return """"; })();
        ((Func<int>)delegate { })();
        ((Func<int>)delegate { 1 / 0; })();
    }
}
";

J
Jared Parsons 已提交
615
            CreateCompilation(csSource).VerifyDiagnostics(
P
Pilchie 已提交
616 617 618 619 620 621
    // (7,39): error CS0029: Cannot implicitly convert type 'string' to 'int'
    //         ((Func<int>)delegate { return ""; })();
    Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(7, 39),
    // (7,39): error CS1662: Cannot convert anonymous method to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
    //         ((Func<int>)delegate { return ""; })();
    Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @"""""").WithArguments("anonymous method").WithLocation(7, 39),
622
    // (8,21): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>'
P
Pilchie 已提交
623
    //         ((Func<int>)delegate { })();
624
    Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(8, 21),
P
Pilchie 已提交
625 626 627
    // (9,32): error CS0020: Division by constant zero
    //         ((Func<int>)delegate { 1 / 0; })();
    Diagnostic(ErrorCode.ERR_IntDivByZero, "1 / 0").WithLocation(9, 32),
628
    // (9,32): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
P
Pilchie 已提交
629 630
    //         ((Func<int>)delegate { 1 / 0; })();
    Diagnostic(ErrorCode.ERR_IllegalStatement, "1 / 0").WithLocation(9, 32),
631
    // (9,21): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>'
P
Pilchie 已提交
632
    //         ((Func<int>)delegate { 1 / 0; })();
633 634
    Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(9, 21)
            );
P
Pilchie 已提交
635 636
        }

J
Jared Parsons 已提交
637
        [WorkItem(540181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540181")]
P
Pilchie 已提交
638 639 640 641 642 643 644 645 646 647 648 649 650 651
        [Fact]
        public void ErrorInLambdaArgumentList()
        {
            var csSource = @"using System;

class Program
{
    public Program(string x) : this(() => x) { }
    static void Main(string[] args)
    {
        ((Action<string>)(f => Console.WriteLine(f)))(nulF);
    }
}";

J
Jared Parsons 已提交
652
            CreateCompilation(csSource).VerifyDiagnostics(
P
Pilchie 已提交
653 654 655 656 657 658
            // (5,37): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type
                Diagnostic(ErrorCode.ERR_AnonMethToNonDel, @"() => x").WithArguments("lambda expression", "string"),
            // (8,55): error CS0103: The name 'nulF' does not exist in the current context
                Diagnostic(ErrorCode.ERR_NameNotInContext, @"nulF").WithArguments("nulF"));
        }

J
Jared Parsons 已提交
659
        [WorkItem(541725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541725")]
P
Pilchie 已提交
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
        [Fact]
        public void DelegateCreationIsNotStatement()
        {
            var csSource = @"
delegate void D();
class Program
{
    public static void Main(string[] args)
    {
        D d = () => new D(() => { });
        new D(()=>{});
    }
}";

            // Though it is legal to have an object-creation-expression, because it might be useful
            // for its side effects, a delegate-creation-expression is not allowed as a
            // statement expression.

J
Jared Parsons 已提交
678
            CreateCompilation(csSource).VerifyDiagnostics(
679
                // (7,21): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
P
Pilchie 已提交
680 681
                //         D d = () => new D(() => { });
                Diagnostic(ErrorCode.ERR_IllegalStatement, "new D(() => { })"),
682
                // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
P
Pilchie 已提交
683 684 685 686
                //         new D(()=>{});
                Diagnostic(ErrorCode.ERR_IllegalStatement, "new D(()=>{})"));
        }

J
Jared Parsons 已提交
687
        [WorkItem(542336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542336")]
P
Pilchie 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701
        [Fact]
        public void ThisInStaticContext()
        {
            var csSource = @"
delegate void D();
class Program
{
    public static void Main(string[] args)
    {
        D d = () => {
            object o = this;
        };
    }
}";
J
Jared Parsons 已提交
702
            CreateCompilation(csSource).VerifyDiagnostics(
P
Pilchie 已提交
703 704 705 706 707 708
                // (8,24): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer
                //             object o = this;
                Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this")
                );
        }

J
Jared Parsons 已提交
709
        [WorkItem(542431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542431")]
P
Pilchie 已提交
710 711 712 713 714 715 716 717 718 719 720
        [Fact]
        public void LambdaHasMoreParametersThanDelegate()
        {
            var csSource = @"
class C
{
    static void Main()
    {
        System.Func<int> f = new System.Func<int>(r => 0);
    }
}";
J
Jared Parsons 已提交
721
            CreateCompilation(csSource).VerifyDiagnostics(
P
Pilchie 已提交
722 723 724 725
                // (6,51): error CS1593: Delegate 'System.Func<int>' does not take 1 arguments
                Diagnostic(ErrorCode.ERR_BadDelArgCount, "r => 0").WithArguments("System.Func<int>", "1"));
        }

J
Jared Parsons 已提交
726
        [Fact, WorkItem(529054, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529054")]
P
Pilchie 已提交
727 728 729 730 731 732 733 734 735 736 737
        public void LambdaInDynamicCall()
        {
            var source = @"
public class Program
{
    static void Main()
    {
        dynamic b = new string[] { ""AA"" };
        bool exists = System.Array.Exists(b, o => o != ""BB"");
    }
}";
J
Jared Parsons 已提交
738
            CreateCompilation(source).VerifyDiagnostics(
P
Pilchie 已提交
739 740 741 742 743 744
    // (7,46): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
    //         bool exists = System.Array.Exists(b, o => o != "BB");
    Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, @"o => o != ""BB""")
                );
        }

J
Jared Parsons 已提交
745
        [Fact, WorkItem(529389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529389")]
P
Pilchie 已提交
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
        public void ParenthesizedLambdaInCastExpression()
        {
            var source = @"
using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        int x = 1;
        byte y = (byte) (x + x);
        Func<int> f1 = (() => { return 1; });
        Func<int> f2 = (Func<int>) (() => { return 2; });
    }
}
";
            var tree = SyntaxFactory.ParseSyntaxTree(source);
J
Jared Parsons 已提交
763
            var comp = CreateCompilation(tree);
P
Pilchie 已提交
764 765 766
            var model = comp.GetSemanticModel(tree);

            ExpressionSyntax expr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().
767
                Where(e => e.Kind() == SyntaxKind.AddExpression).Single();
P
Pilchie 已提交
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795

            var tinfo = model.GetTypeInfo(expr);
            var conv = model.GetConversion(expr);
            // Not byte
            Assert.Equal("int", tinfo.Type.ToDisplayString());

            var exprs = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>();
            expr = exprs.First();
            tinfo = model.GetTypeInfo(expr);
            conv = model.GetConversion(expr);
            Assert.True(conv.IsAnonymousFunction, "LambdaConversion");
            Assert.Null(tinfo.Type);
            var sym = model.GetSymbolInfo(expr).Symbol;
            Assert.NotNull(sym);
            Assert.Equal(SymbolKind.Method, sym.Kind);
            Assert.Equal(MethodKind.AnonymousFunction, (sym as MethodSymbol).MethodKind);

            expr = exprs.Last();
            tinfo = model.GetTypeInfo(expr);
            conv = model.GetConversion(expr);
            Assert.True(conv.IsAnonymousFunction, "LambdaConversion");
            Assert.Null(tinfo.Type);
            sym = model.GetSymbolInfo(expr).Symbol;
            Assert.NotNull(sym);
            Assert.Equal(SymbolKind.Method, sym.Kind);
            Assert.Equal(MethodKind.AnonymousFunction, (sym as MethodSymbol).MethodKind);
        }

J
Jared Parsons 已提交
796
        [WorkItem(544594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544594")]
P
Pilchie 已提交
797 798 799 800 801 802 803 804 805 806 807 808 809
        [Fact]
        public void LambdaInEnumMemberDecl()
        {
            var csSource = @"
public class TestClass
{
    public enum Test { aa = ((System.Func<int>)(() => 1))() }
    Test MyTest = Test.aa;
    public static void Main()
    {
    }
}
";
J
Jared Parsons 已提交
810
            CreateCompilation(csSource).VerifyDiagnostics(
P
Pilchie 已提交
811 812 813 814 815 816
                // (4,29): error CS0133: The expression being assigned to 'TestClass.Test.aa' must be constant
                Diagnostic(ErrorCode.ERR_NotConstantExpression, "((System.Func<int>)(() => 1))()").WithArguments("TestClass.Test.aa"),
                // (5,10): warning CS0414: The field 'TestClass.MyTest' is assigned but its value is never used
                Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "MyTest").WithArguments("TestClass.MyTest"));
        }

J
Jared Parsons 已提交
817
        [WorkItem(544932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544932")]
P
Pilchie 已提交
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
        [Fact]
        public void AnonymousLambdaInEnumSubtraction()
        {
            string source = @"
class Test
{
    enum E1 : byte
    {
        A = byte.MinValue,
        C = 1
    }

    static void Main()
    {
        int j = ((System.Func<Test.E1>)(() => E1.A))() - E1.C;
        System.Console.WriteLine(j);
    }
}
";
            string expectedOutput = @"255";

            CompileAndVerify(new[] { source }, expectedOutput: expectedOutput);
        }

J
Jared Parsons 已提交
842
        [WorkItem(545156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545156")]
P
Pilchie 已提交
843 844 845 846 847 848 849 850 851 852 853 854
        [Fact]
        public void SpeculativelyBindOverloadResolution()
        {
            string source = @"
using System;
using System.Collections;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
855
        Goo(() => () => { var x = (IEnumerable<int>)null; return x; });
P
Pilchie 已提交
856 857
    }
 
858 859
    static void Goo(Func<Func<IEnumerable>> x) { }
    static void Goo(Func<Func<IFormattable>> x) { }
P
Pilchie 已提交
860 861
}
";
J
Jared Parsons 已提交
862
            var compilation = CreateCompilation(source);
P
Pilchie 已提交
863 864 865 866 867 868
            var tree = compilation.SyntaxTrees.Single();
            var model = compilation.GetSemanticModel(tree);

            var invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single();

            // Used to throw a NRE because of the ExpressionSyntax's null SyntaxTree.
869
            model.GetSpeculativeSymbolInfo(
P
Pilchie 已提交
870
                invocation.SpanStart,
871
                SyntaxFactory.ParseExpression("Goo(() => () => { var x = null; return x; })"), // cast removed
872
                SpeculativeBindingOption.BindAsExpression);
P
Pilchie 已提交
873 874
        }

J
Jared Parsons 已提交
875
        [WorkItem(545343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545343")]
P
Pilchie 已提交
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
        [Fact]
        public void LambdaUsingFieldInConstructor()
        {
            string source = @"
using System;

public class Derived
{
    int field = 1;

    Derived()
    {
        int local = 2;

        // A lambda that captures a local and refers to an instance field.
        Action a = () => Console.WriteLine(""Local = {0}, Field = {1}"", local, field); 

        // NullReferenceException if the ""this"" field of the display class hasn't been set.
        a();
    }

    public static void Main()
    {
        Derived d = new Derived();
    }
}";
            CompileAndVerify(source, expectedOutput: "Local = 2, Field = 1");
        }

J
Jared Parsons 已提交
905
        [WorkItem(642222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642222")]
P
Pilchie 已提交
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
        [Fact]
        public void SpeculativelyBindOverloadResolutionAndInferenceWithError()
        {
            string source = @"
using System;using System.Linq.Expressions;
namespace IntellisenseBug
{
    public class Program
    {
        void M(Mapper<FromData, ToData> mapper)
        {
            // Intellisense is broken here when you type . after the x:
            mapper.Map(x => x/* */.
        }
    }
    public class Mapper<TTypeFrom, TTypeTo>
    {
        public void Map<TPropertyFrom, TPropertyTo>(
            Expression<Func<TTypeFrom, TPropertyFrom>> from,
            Expression<Func<TTypeTo, TPropertyTo>> to)
        { }
    }
    public class FromData
    {
        public int Int { get; set; }
        public string String { get; set; }
    }
    public class ToData
    {
        public int Id { get; set; }
        public string Name
        {
            get; set;
        }
    }
}";
J
Jared Parsons 已提交
942
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
P
Pilchie 已提交
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
            // We don't actually require any particular diagnostics, but these are what we get.
            compilation.VerifyDiagnostics(
                // (10,36): error CS1001: Identifier expected
                //             mapper.Map(x => x/* */.
                Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
                // (10,36): error CS1026: ) expected
                //             mapper.Map(x => x/* */.
                Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
                // (10,36): error CS1002: ; expected
                //             mapper.Map(x => x/* */.
                Diagnostic(ErrorCode.ERR_SemicolonExpected, "")
                );
            var tree = compilation.SyntaxTrees.Single();
            var model = compilation.GetSemanticModel(tree);
            var xReference =
                tree
                .GetCompilationUnitRoot()
                .DescendantNodes()
                .OfType<ExpressionSyntax>()
                .Where(e => e.ToFullString() == "x/* */")
                .Last();
            var typeInfo = model.GetTypeInfo(xReference);
            Assert.NotNull(((TypeSymbol)typeInfo.Type).GetMember("String"));
        }

J
Jared Parsons 已提交
968
        [WorkItem(722288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722288")]
P
Pilchie 已提交
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
        [Fact]
        public void CompletionInLambdaInIncompleteInvocation()
        {
            string source = @"
using System;
using System.Linq.Expressions;
 
public class SomeType
{
    public string SomeProperty { get; set; }
}
public class IntelliSenseError
{
    public static void Test1<T>(Expression<Func<T, object>> expr)
    {
        Console.WriteLine(((MemberExpression)expr.Body).Member.Name);
    }
    public static void Test2<T>(Expression<Func<T, object>> expr, bool additionalParameter)
    {
        Test1(expr);
    }
    public static void Main()
    {
        Test2<SomeType>(o => o/* */.
    }
}
";
J
Jared Parsons 已提交
996
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
P
Pilchie 已提交
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
            // We don't actually require any particular diagnostics, but these are what we get.
            compilation.VerifyDiagnostics(
                // (21,37): error CS1001: Identifier expected
                //         Test2<SomeType>(o => o/* */.
                Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
                // (21,37): error CS1026: ) expected
                //         Test2<SomeType>(o => o/* */.
                Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
                // (21,37): error CS1002: ; expected
                //         Test2<SomeType>(o => o/* */.
                Diagnostic(ErrorCode.ERR_SemicolonExpected, "")
                );
            var tree = compilation.SyntaxTrees.Single();
            var model = compilation.GetSemanticModel(tree);
            var oReference =
                tree
                .GetCompilationUnitRoot()
                .DescendantNodes()
                .OfType<NameSyntax>()
                .Where(e => e.ToFullString() == "o/* */")
                .Last();
            var typeInfo = model.GetTypeInfo(oReference);
            Assert.NotNull(((TypeSymbol)typeInfo.Type).GetMember("SomeProperty"));
        }

J
Jared Parsons 已提交
1022
        [WorkItem(871896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/871896")]
P
Pilchie 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
        [Fact]
        public void Bug871896()
        {
            string source = @"
using System.Threading;
using System.Threading.Tasks;
class TestDataPointBase
{
    private readonly IVisualStudioIntegrationService integrationService;
    protected void TryGetDocumentId(CancellationToken token)
    {
        DocumentId documentId = null;
        if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false))
        {
        }
    }
}

";
J
Jared Parsons 已提交
1042
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
1043

P
Pilchie 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052
            var tree = compilation.SyntaxTrees.Single();
            var model = compilation.GetSemanticModel(tree);
            var oReference =
                tree
                .GetCompilationUnitRoot()
                .DescendantNodes()
                .OfType<ExpressionSyntax>()
                .OrderByDescending(s => s.SpanStart);

1053
            foreach (var name in oReference)
P
Pilchie 已提交
1054 1055 1056 1057
            {
                CSharpExtensions.GetSymbolInfo(model, name);
            }

C
Charles Stoner 已提交
1058
            // We should get a bunch of errors, but no asserts.
P
Pilchie 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
            compilation.VerifyDiagnostics(
    // (6,22): error CS0246: The type or namespace name 'IVisualStudioIntegrationService' could not be found (are you missing a using directive or an assembly reference?)
    //     private readonly IVisualStudioIntegrationService integrationService;
    Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IVisualStudioIntegrationService").WithArguments("IVisualStudioIntegrationService").WithLocation(6, 22),
    // (9,9): error CS0246: The type or namespace name 'DocumentId' could not be found (are you missing a using directive or an assembly reference?)
    //         DocumentId documentId = null;
    Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "DocumentId").WithArguments("DocumentId").WithLocation(9, 9),
    // (10,25): error CS0117: 'System.Threading.Tasks.Task' does not contain a definition for 'Run'
    //         if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false))
    Diagnostic(ErrorCode.ERR_NoSuchMember, "Run").WithArguments("System.Threading.Tasks.Task", "Run").WithLocation(10, 25),
    // (10,14): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
    //         if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false))
    Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)").WithLocation(10, 14),
    // (6,54): warning CS0649: Field 'TestDataPointBase.integrationService' is never assigned to, and will always have its default value null
    //     private readonly IVisualStudioIntegrationService integrationService;
    Diagnostic(ErrorCode.WRN_UnassignedInternalField, "integrationService").WithArguments("TestDataPointBase.integrationService", "null").WithLocation(6, 54)
                );
        }
1077

J
Jared Parsons 已提交
1078
        [Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")]
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
        public void Bug960755_01()
        {
            var source = @"
using System.Collections.Generic;
 
class C
{
    static void M(IList<C> c)
    {
        var tmp = new C();
        tmp.M((a, b) => c.Add);
    }
}

";
            var tree = SyntaxFactory.ParseSyntaxTree(source);
J
Jared Parsons 已提交
1095
            var comp = CreateCompilation(tree);
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
            var model = comp.GetSemanticModel(tree);

            var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single().Body;

            var symbolInfo = model.GetSymbolInfo(expr);

            Assert.Null(symbolInfo.Symbol);
            Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString());
            Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
        }

J
Jared Parsons 已提交
1107
        [Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")]
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
        public void Bug960755_02()
        {
            var source = @"
using System.Collections.Generic;
 
class C
{
    static void M(IList<C> c)
    {
        int tmp = c.Add;
    }
}

";
            var tree = SyntaxFactory.ParseSyntaxTree(source);
J
Jared Parsons 已提交
1123
            var comp = CreateCompilation(tree);
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
            var model = comp.GetSemanticModel(tree);

            var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer.Value;

            var symbolInfo = model.GetSymbolInfo(expr);

            Assert.Null(symbolInfo.Symbol);
            Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString());
            Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
        }

J
Jared Parsons 已提交
1135
        [Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")]
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
        public void Bug960755_03()
        {
            var source = @"
using System.Collections.Generic;
 
class C
{
    static void M(IList<C> c)
    {
        var tmp = new C();
        tmp.M((a, b) => c.Add);
    }

    static void M(System.Func<int, int, System.Action<C>> x)
    {}
}

";
            var tree = SyntaxFactory.ParseSyntaxTree(source);
J
Jared Parsons 已提交
1155
            var comp = CreateCompilation(tree);
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
            var model = comp.GetSemanticModel(tree);

            var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single().Body;

            var symbolInfo = model.GetSymbolInfo(expr);

            Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.Symbol.ToTestDisplayString());
            Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
            Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
        }
1166

1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
        [Fact]
        public void RefLambdaInferenceMethodArgument()
        {
            var text = @"
delegate ref int D();

class C
{
    static void MD(D d) { }

    static int i = 0;
    static void M()
    {
        MD(() => ref i);
        MD(() => { return ref i; });
        MD(delegate { return ref i; });
1183 1184
    }
}
1185 1186
";

J
Jared Parsons 已提交
1187
            CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
        }


        [Fact]
        public void RefLambdaInferenceDelegateCreation()
        {
            var text = @"
delegate ref int D();

class C
{
    static int i = 0;
    static void M()
    {
        var d = new D(() => ref i);
        d = new D(() => { return ref i; });
        d = new D(delegate { return ref i; });
    }
}
";

J
Jared Parsons 已提交
1209
            CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
        }

        [Fact]
        public void RefLambdaInferenceOverloadedDelegateType()
        {
            var text = @"
delegate ref int D();
delegate int E();

class C
{
    static void M(D d) { }
    static void M(E e) { }

    static int i = 0;
    static void M()
    {
        M(() => ref i);
        M(() => { return ref i; });
        M(delegate { return ref i; });
        M(() => i);
        M(() => { return i; });
        M(delegate { return i; });
    }
}
";

J
Jared Parsons 已提交
1237
            CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
        }

        [Fact]
        public void RefLambdaInferenceArgumentBadRefReturn()
        {
            var text = @"
delegate int E();

class C
{
    static void ME(E e) { }

    static int i = 0;
    static void M()
    {
        ME(() => ref i);
        ME(() => { return ref i; });
        ME(delegate { return ref i; });
    }
}
";

J
Jared Parsons 已提交
1260
            CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
1261
                // (11,22): error CS8149: By-reference returns may only be used in by-reference returning methods.
1262 1263
                //         ME(() => ref i);
                Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "i").WithLocation(11, 22),
1264
                // (12,20): error CS8149: By-reference returns may only be used in by-reference returning methods.
1265 1266
                //         ME(() => { return ref i; });
                Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(12, 20),
1267
                // (13,23): error CS8149: By-reference returns may only be used in by-reference returning methods.
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
                //         ME(delegate { return ref i; });
                Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(13, 23));
        }

        [Fact]
        public void RefLambdaInferenceDelegateCreationBadRefReturn()
        {
            var text = @"
delegate int E();

class C
{
    static int i = 0;
    static void M()
    {
        var e = new E(() => ref i);
        e = new E(() => { return ref i; });
        e = new E(delegate { return ref i; });
    }
}
";

J
Jared Parsons 已提交
1290
            CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
1291
                // (9,33): error CS8149: By-reference returns may only be used in by-reference returning methods.
1292 1293
                //         var e = new E(() => ref i);
                Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "i").WithLocation(9, 33),
1294
                // (10,27): error CS8149: By-reference returns may only be used in by-reference returning methods.
1295 1296
                //         e = new E(() => { return ref i; });
                Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(10, 27),
1297
                // (11,30): error CS8149: By-reference returns may only be used in by-reference returning methods.
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
                //         e = new E(delegate { return ref i; });
                Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(11, 30));
        }

        [Fact]
        public void RefLambdaInferenceMixedByValueAndByRefReturns()
        {
            var text = @"
delegate ref int D();
delegate int E();

class C
{
    static void MD(D e) { }
    static void ME(E e) { }

    static int i = 0;
    static void M()
    {
        MD(() => {
            if (i == 0)
            {
                return ref i;
            }
            return i;
        });
        ME(() => {
            if (i == 0)
            {
                return ref i;
            }
            return i;
        });
    }
}
";

J
Jared Parsons 已提交
1335
            CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
1336
                // (18,13): error CS8150: By-value returns may only be used in by-value returning methods.
1337 1338
                //             return i;
                Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(18, 13),
1339
                // (23,17): error CS8149: By-reference returns may only be used in by-reference returning methods.
1340 1341 1342 1343 1344
                //                 return ref i;
                Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(23, 17));
        }

        [WorkItem(1112875, "DevDiv")]
J
Jared Parsons 已提交
1345
        [WorkItem(1112875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112875")]
1346 1347 1348
        [Fact]
        public void Bug1112875_1()
        {
J
Jared Parsons 已提交
1349
            var comp = CreateCompilation(@"
1350 1351 1352 1353 1354 1355 1356
using System;
 
class Program
{
    static void Main()
    {
        ICloneable c = """";
1357
        Goo(() => (c.Clone()), null);
1358 1359
    }
 
1360 1361
    static void Goo(Action x, string y) { }
    static void Goo(Func<object> x, object y) { Console.WriteLine(42); }
1362 1363 1364 1365 1366 1367
}", options: TestOptions.ReleaseExe);
            comp.VerifyDiagnostics();

            CompileAndVerify(comp, expectedOutput: "42");
        }

J
Jared Parsons 已提交
1368
        [WorkItem(1112875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112875")]
1369 1370 1371
        [Fact]
        public void Bug1112875_2()
        {
J
Jared Parsons 已提交
1372
            var comp = CreateCompilation(@"
1373 1374 1375 1376 1377 1378 1379 1380 1381
class Program
{
    void M()
    {
        var d = new System.Action(() => (new object()));
    }
}
");
            comp.VerifyDiagnostics(
1382
                // (6,41): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
1383 1384 1385
                //         var d = new System.Action(() => (new object()));
                Diagnostic(ErrorCode.ERR_IllegalStatement, "(new object())").WithLocation(6, 41));
        }
1386 1387 1388 1389 1390

        [WorkItem(1830, "https://github.com/dotnet/roslyn/issues/1830")]
        [Fact]
        public void FuncOfVoid()
        {
J
Jared Parsons 已提交
1391
            var comp = CreateCompilation(@"
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
using System;
class Program
{
    void M1<T>(Func<T> f) {}
    void Main(string[] args)
    {
        M1(() => { return System.Console.Beep(); });
    }
}
");
            comp.VerifyDiagnostics(
                // (8,27): error CS4029: Cannot return an expression of type 'void'
                //         M1(() => { return System.Console.Beep(); });
                Diagnostic(ErrorCode.ERR_CantReturnVoid, "System.Console.Beep()").WithLocation(8, 27)
                );
        }
1408

J
Jared Parsons 已提交
1409
        [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")]
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
        public void ParameterReference_01()
        {
            var src = @"
using System;

class Program
{
    static Func<Program, string> stuff()
    {
        return a => a.
    }
}
";
J
Jared Parsons 已提交
1423
            var compilation = CreateCompilation(src);
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
            compilation.VerifyDiagnostics(
    // (8,23): error CS1001: Identifier expected
    //         return a => a.
    Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(8, 23),
    // (8,23): error CS1002: ; expected
    //         return a => a.
    Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 23)
                );

            var tree = compilation.SyntaxTrees.Single();
            var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single();

            Assert.Equal("a.", node.Parent.ToString().Trim());

            var semanticModel = compilation.GetSemanticModel(tree);
            var symbolInfo = semanticModel.GetSymbolInfo(node);

            Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString());
        }

J
Jared Parsons 已提交
1444
        [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")]
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
        public void ParameterReference_02()
        {
            var src = @"
using System;

class Program
{
    static void stuff()
    {
        Func<Program, string> l = a => a.
    }
}
";
J
Jared Parsons 已提交
1458
            var compilation = CreateCompilation(src);
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
            compilation.VerifyDiagnostics(
    // (8,42): error CS1001: Identifier expected
    //         Func<Program, string> l = a => a.
    Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(8, 42),
    // (8,42): error CS1002: ; expected
    //         Func<Program, string> l = a => a.
    Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 42)
                );

            var tree = compilation.SyntaxTrees.Single();
            var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single();

            Assert.Equal("a.", node.Parent.ToString().Trim());

            var semanticModel = compilation.GetSemanticModel(tree);
            var symbolInfo = semanticModel.GetSymbolInfo(node);

            Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString());
        }

J
Jared Parsons 已提交
1479
        [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")]
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
        public void ParameterReference_03()
        {
            var src = @"
using System;

class Program
{
    static void stuff()
    {
         M1(a => a.);
    }

    static void M1(Func<Program, string> l){}
}
";
J
Jared Parsons 已提交
1495
            var compilation = CreateCompilation(src);
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
            compilation.VerifyDiagnostics(
    // (8,20): error CS1001: Identifier expected
    //          M1(a => a.);
    Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 20)
                );

            var tree = compilation.SyntaxTrees.Single();
            var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single();

            Assert.Equal("a.", node.Parent.ToString().Trim());

            var semanticModel = compilation.GetSemanticModel(tree);
            var symbolInfo = semanticModel.GetSymbolInfo(node);

            Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString());
        }

J
Jared Parsons 已提交
1513
        [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")]
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
        public void ParameterReference_04()
        {
            var src = @"
using System;

class Program
{
    static void stuff()
    {
        var l = (Func<Program, string>) (a => a.);
    }
}
";
J
Jared Parsons 已提交
1527
            var compilation = CreateCompilation(src);
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
            compilation.VerifyDiagnostics(
    // (8,49): error CS1001: Identifier expected
    //         var l = (Func<Program, string>) (a => a.);
    Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 49)
                );

            var tree = compilation.SyntaxTrees.Single();
            var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single();

            Assert.Equal("a.", node.Parent.ToString().Trim());

            var semanticModel = compilation.GetSemanticModel(tree);
            var symbolInfo = semanticModel.GetSymbolInfo(node);

            Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString());
        }
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559

        [Fact]
        [WorkItem(3826, "https://github.com/dotnet/roslyn/issues/3826")]
        public void ExpressionTreeSelfAssignmentShouldError()
        {
            var source = @"
using System;
using System.Linq.Expressions;

class Program
{
    static void Main()
    {
        Expression<Func<int, int>> x = y => y = y;
    }
}";
J
Jared Parsons 已提交
1560
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
1561 1562 1563 1564 1565 1566 1567 1568
            compilation.VerifyDiagnostics(
                // (9,45): warning CS1717: Assignment made to same variable; did you mean to assign something else?
                //         Expression<Func<int, int>> x = y => y = y;
                Diagnostic(ErrorCode.WRN_AssignmentToSelf, "y = y").WithLocation(9, 45),
                // (9,45): error CS0832: An expression tree may not contain an assignment operator
                //         Expression<Func<int, int>> x = y => y = y;
                Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "y = y").WithLocation(9, 45));
        }
1569

1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
        [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
        public void RefStructExpressionTree()
        {
            var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
    public void Method1()
    {
        Method((Class1 c) => c.Method2(default(Struct1)));
    }

    public void Method2(Struct1 s1) { }

    public static void Method<T>(Expression<Action<T>> expression) { }
}

public ref struct Struct1 { }
";
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
                // (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
                //         Method((Class1 c) => c.Method2(default(Struct1)));
                Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default(Struct1)").WithArguments("Struct1").WithLocation(8, 40));
        }

        [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
        public void RefStructDefaultExpressionTree()
        {
            var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
    public void Method1()
    {
        Method((Class1 c) => c.Method2(default));
    }

    public void Method2(Struct1 s1) { }

    public static void Method<T>(Expression<Action<T>> expression) { }
}

public ref struct Struct1 { }
";
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
                // (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
                //         Method((Class1 c) => c.Method2(default));
                Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("Struct1").WithLocation(8, 40));
        }

        [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
        public void RefStructDefaultCastExpressionTree()
        {
            var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
    public void Method1()
    {
        Method((Class1 c) => c.Method2((Struct1) default));
    }

    public void Method2(Struct1 s1) { }

    public static void Method<T>(Expression<Action<T>> expression) { }
}

public ref struct Struct1 { }
";
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
                // (8,50): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
                //         Method((Class1 c) => c.Method2((Struct1) default));
                Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("Struct1").WithLocation(8, 50));
        }

        [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
        public void RefStructNewExpressionTree()
        {
            var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
    public void Method1()
    {
        Method((Class1 c) => c.Method2(new Struct1()));
    }

    public void Method2(Struct1 s1) { }

    public static void Method<T>(Expression<Action<T>> expression) { }
}

public ref struct Struct1 { }
";
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
                // (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
                //         Method((Class1 c) => c.Method2(new Struct1()));
                Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "new Struct1()").WithArguments("Struct1").WithLocation(8, 40));
        }

        [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
        public void RefStructParamExpressionTree()
        {
            var text = @"
using System.Linq.Expressions;

public delegate void Delegate1(Struct1 s);
public class Class1
{
    public void Method1()
    {
        Method((Struct1 s) => Method2());
    }

    public void Method2() { }

    public static void Method(Expression<Delegate1> expression) { }
}

public ref struct Struct1 { }
";
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
                // (9,25): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
                //         Method((Struct1 s) => Method2());
                Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "s").WithArguments("Struct1").WithLocation(9, 25));
        }

        [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
        public void RefStructParamLambda()
        {
            var text = @"
public delegate void Delegate1(Struct1 s);
public class Class1
{
    public void Method1()
    {
        Method((Struct1 s) => Method2());
    }

    public void Method2() { }

    public static void Method(Delegate1 expression) { }
}

public ref struct Struct1 { }
";
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics();
        }

        [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
        public void TypedReferenceExpressionTree()
        {
            var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
    public void Method1()
    {
        Method(() => Method2(default));
    }

    public void Method2(TypedReference tr) { }

    public static void Method(Expression<Action> expression) { }
}
";
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
                // (8,30): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'.
                //         Method(() => Method2(default));
                Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("TypedReference").WithLocation(8, 30));
        }

        [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
        public void TypedReferenceParamExpressionTree()
        {
            var text = @"
using System;
using System.Linq.Expressions;
public delegate void Delegate1(TypedReference tr);
public class Class1
{
    public void Method1()
    {
        Method((TypedReference tr) => Method2());
    }

    public void Method2() { }

    public static void Method(Expression<Delegate1> expression) { }
}
";
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
                // (9,32): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'.
                //         Method((TypedReference tr) => Method2());
                Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "tr").WithArguments("TypedReference").WithLocation(9, 32));
        }

1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
        [Fact, WorkItem(5363, "https://github.com/dotnet/roslyn/issues/5363")]
        public void ReturnInferenceCache_Dynamic_vs_Object_01()
        {
            var source =
@"
using System;
using System.Collections;
using System.Collections.Generic;

public static class Program
{
    public static void Main(string[] args)
    {
        IEnumerable<dynamic> dynX = null;

        // CS1061 'object' does not contain a definition for 'Text'...
        // tooltip on 'var' shows IColumn instead of IEnumerable<dynamic>
        var result = dynX.Select(_ => _.Text);
    }

    public static IColumn Select<TResult>(this IColumn source, Func<object, TResult> selector)
    {
        throw new NotImplementedException();
    }

    public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector)
    {
        System.Console.WriteLine(""Select<T, S>"");
        return null;
    }
}

public interface IColumn { }
";
J
Jared Parsons 已提交
1806
            var compilation = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseExe);
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
            CompileAndVerify(compilation, expectedOutput: "Select<T, S>");
        }

        [Fact, WorkItem(5363, "https://github.com/dotnet/roslyn/issues/5363")]
        public void ReturnInferenceCache_Dynamic_vs_Object_02()
        {
            var source =
@"
using System;
using System.Collections;
using System.Collections.Generic;

public static class Program
{
    public static void Main(string[] args)
    {
        IEnumerable<dynamic> dynX = null;

        // CS1061 'object' does not contain a definition for 'Text'...
        // tooltip on 'var' shows IColumn instead of IEnumerable<dynamic>
        var result = dynX.Select(_ => _.Text);
    }

    public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector)
    {
        System.Console.WriteLine(""Select<T, S>"");
        return null;
    }

    public static IColumn Select<TResult>(this IColumn source, Func<object, TResult> selector)
    {
        throw new NotImplementedException();
    }
}

public interface IColumn { }
";
J
Jared Parsons 已提交
1844
            var compilation = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseExe);
1845 1846
            CompileAndVerify(compilation, expectedOutput: "Select<T, S>");
        }
1847

1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
        [Fact, WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
        public void SyntaxAndSemanticErrorInLambda()
        {
            var source =
@"
using System;
class C
{
    public static void Main(string[] args)
    {
        Action a = () => { new X().ToString() };
        a();
    }
}
";
J
Jared Parsons 已提交
1863
            CreateCompilation(source).VerifyDiagnostics(
1864 1865 1866 1867 1868 1869 1870 1871 1872
                // (7,47): error CS1002: ; expected
                //         Action a = () => { new X().ToString() };
                Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 47),
                // (7,32): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?)
                //         Action a = () => { new X().ToString() };
                Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(7, 32)
                );
        }

1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
        [Fact, WorkItem(4527, "https://github.com/dotnet/roslyn/issues/4527")]
        public void AnonymousMethodExpressionWithoutParameterList()
        {
            var source =
@"
using System;
using System.Threading.Tasks;

namespace RoslynAsyncDelegate
{
    class Program
    {
        static EventHandler MyEvent;

        static void Main(string[] args)
        {
           MyEvent += async delegate { await Task.Delay(0); };
        }
    }
}

";
            var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe);

            var tree = compilation.SyntaxTrees[0];
            var model = compilation.GetSemanticModel(tree);

            var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.AnonymousMethodExpression)).Single();

            Assert.Equal("async delegate { await Task.Delay(0); }", node1.ToString());

            Assert.Equal("void System.EventHandler.Invoke(System.Object sender, System.EventArgs e)", model.GetTypeInfo(node1).ConvertedType.GetMembers("Invoke").Single().ToTestDisplayString());

            var lambdaParameters = ((MethodSymbol)(model.GetSymbolInfo(node1)).Symbol).Parameters;

1908 1909
            Assert.Equal("System.Object <p0>", lambdaParameters[0].ToTestDisplayString());
            Assert.Equal("System.EventArgs <p1>", lambdaParameters[1].ToTestDisplayString());
1910 1911 1912

            CompileAndVerify(compilation);
        }
1913 1914 1915 1916 1917 1918 1919 1920

        [Fact]
        [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
        public void TestLambdaWithError01()
        {
            var source =
@"using System.Linq;
class C { C() { string.Empty.Select(() => { new Unbound1 }); } }";
J
Jared Parsons 已提交
1921
            CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
    // (2,58): error CS1526: A new expression requires (), [], or {} after type
    // class C { C() { string.Empty.Select(() => { new Unbound1 }); } }
    Diagnostic(ErrorCode.ERR_BadNewExpr, "}").WithLocation(2, 58),
    // (2,58): error CS1002: ; expected
    // class C { C() { string.Empty.Select(() => { new Unbound1 }); } }
    Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(2, 58),
    // (2,49): error CS0246: The type or namespace name 'Unbound1' could not be found (are you missing a using directive or an assembly reference?)
    // class C { C() { string.Empty.Select(() => { new Unbound1 }); } }
    Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unbound1").WithArguments("Unbound1").WithLocation(2, 49)
                );
        }

        [Fact]
        [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
        public void TestLambdaWithError02()
        {
            var source =
@"using System.Linq;
class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } }";
J
Jared Parsons 已提交
1941
            CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
    // (2,62): error CS1002: ; expected
    // class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } }
    Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(2, 62),
    // (2,49): error CS0246: The type or namespace name 'Unbound1' could not be found (are you missing a using directive or an assembly reference?)
    // class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } }
    Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unbound1").WithArguments("Unbound1").WithLocation(2, 49)
                );
        }

        [Fact]
        [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
        public void TestLambdaWithError03()
        {
            var source =
@"using System.Linq;
class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }";
J
Jared Parsons 已提交
1958
            CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
    // (2,61): error CS1003: Syntax error, ',' expected
    // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }
    Diagnostic(ErrorCode.ERR_SyntaxError, "Unbound2").WithArguments(",", "").WithLocation(2, 61),
    // (2,52): error CS0103: The name 'Unbound2' does not exist in the current context
    // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }
    Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 52),
    // (2,61): error CS0103: The name 'Unbound2' does not exist in the current context
    // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }
    Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 61),
    // (2,42): error CS0103: The name 'Unbound1' does not exist in the current context
    // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }
    Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 42)
                );
        }

        [Fact]
        [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
        public void TestLambdaWithError04()
        {
            var source =
@"using System.Linq;
class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } }";
J
Jared Parsons 已提交
1981
            CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
    // (2,52): error CS0103: The name 'Unbound2' does not exist in the current context
    // class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } }
    Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 52),
    // (2,42): error CS0103: The name 'Unbound1' does not exist in the current context
    // class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } }
    Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 42)
                );
        }

        [Fact]
        [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
        public void TestLambdaWithError05()
        {
            var source =
@"using System.Linq;
class C { C() { Unbound2.Select(x => Unbound1); } }";
J
Jared Parsons 已提交
1998
            CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
1999 2000 2001 2002 2003 2004 2005 2006
    // (2,17): error CS0103: The name 'Unbound2' does not exist in the current context
    // class C { C() { Unbound2.Select(x => Unbound1); } }
    Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 17),
    // (2,38): error CS0103: The name 'Unbound1' does not exist in the current context
    // class C { C() { Unbound2.Select(x => Unbound1); } }
    Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 38)
                );
        }
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030

        [Fact]
        [WorkItem(4480, "https://github.com/dotnet/roslyn/issues/4480")]
        public void TestLambdaWithError06()
        {
            var source =
@"class Program
{
    static void Main(string[] args)
    {
        // completion should work even in a syntactically invalid lambda
        var handler = new MyDelegateType((s, e) => { e. });
    }
}

public delegate void MyDelegateType(
    object sender,
    MyArgumentType e
);

public class MyArgumentType
{
    public int SomePublicMember;
}";
J
Jared Parsons 已提交
2031
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source)
2032 2033 2034 2035 2036 2037
                .VerifyDiagnostics(
                //         var handler = new MyDelegateType((s, e) => { e. });
                Diagnostic(ErrorCode.ERR_IdentifierExpected, "}").WithLocation(6, 57),
                // (6,57): error CS1002: ; expected
                //         var handler = new MyDelegateType((s, e) => { e. });
                Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(6, 57)
2038
                );
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
            var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
            Assert.Equal("e", eReference.ToString());
            var typeInfo = sm.GetTypeInfo(eReference);
            Assert.Equal("MyArgumentType", typeInfo.Type.Name);
            Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
            Assert.NotEmpty(typeInfo.Type.GetMembers("SomePublicMember"));
        }
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079

        [Fact]
        [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")]
        [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
        public void TestLambdaWithError07()
        {
            var source =
@"using System;
using System.Collections.Generic;

public static class Program
{
    public static void Main()
    {
        var parameter = new List<string>();
        var result = parameter.FirstOrDefault(x => x. );
    }
}

public static class Enumerable
{
    public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
    {
        return default(TSource);
    }

    public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, TSource defaultValue)
    {
        return default(TSource);
    }
}";
J
Jared Parsons 已提交
2080
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
                // (9,55): error CS1001: Identifier expected
                //         var result = parameter.FirstOrDefault(x => x. );
                Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(9, 55)
                );
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
            var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
            Assert.Equal("x", eReference.ToString());
            var typeInfo = sm.GetTypeInfo(eReference);
            Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
            Assert.Equal("String", typeInfo.Type.Name);
            Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
        }

        [Fact]
        [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")]
        [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
        public void TestLambdaWithError08()
        {
            var source =
@"using System;
using System.Collections.Generic;

public static class Program
{
    public static void Main()
    {
        var parameter = new List<string>();
        var result = parameter.FirstOrDefault(x => x. );
    }
}

public static class Enumerable
{
    public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, params TSource[] defaultValue)
    {
        return default(TSource);
    }

    public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, params TSource[] defaultValue)
    {
        return default(TSource);
}
}";
J
Jared Parsons 已提交
2126
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
                // (9,55): error CS1001: Identifier expected
                //         var result = parameter.FirstOrDefault(x => x. );
                Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(9, 55)
                );
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
            var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
            Assert.Equal("x", eReference.ToString());
            var typeInfo = sm.GetTypeInfo(eReference);
            Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
            Assert.Equal("String", typeInfo.Type.Name);
            Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
        }

        [Fact]
        [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")]
        [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
        public void TestLambdaWithError09()
        {
            var source =
@"using System;

public static class Program
{
    public static void Main()
    {
        var parameter = new MyList<string>();
        var result = parameter.FirstOrDefault(x => x. );
    }
}

public class MyList<TSource>
{
    public TSource FirstOrDefault(TSource defaultValue)
    {
        return default(TSource);
    }

    public TSource FirstOrDefault(Func<TSource, bool> predicate, TSource defaultValue)
    {
        return default(TSource);
    }
}
";
J
Jared Parsons 已提交
2172
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201
                // (8,55): error CS1001: Identifier expected
                //         var result = parameter.FirstOrDefault(x => x. );
                Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 55)
                );
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
            var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
            Assert.Equal("x", eReference.ToString());
            var typeInfo = sm.GetTypeInfo(eReference);
            Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
            Assert.Equal("String", typeInfo.Type.Name);
            Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
        }

        [Fact]
        [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")]
        [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
        public void TestLambdaWithError10()
        {
            var source =
@"using System;

public static class Program
{
    public static void Main()
    {
        var parameter = new MyList<string>();
        var result = parameter.FirstOrDefault(x => x. );
P
Pilchie 已提交
2202 2203
    }
}
2204

2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
public class MyList<TSource>
{
    public TSource FirstOrDefault(params TSource[] defaultValue)
    {
        return default(TSource);
    }

    public TSource FirstOrDefault(Func<TSource, bool> predicate, params TSource[] defaultValue)
    {
        return default(TSource);
    }
}
";
J
Jared Parsons 已提交
2218
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
                // (8,55): error CS1001: Identifier expected
                //         var result = parameter.FirstOrDefault(x => x. );
                Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 55)
                );
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
            var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
            Assert.Equal("x", eReference.ToString());
            var typeInfo = sm.GetTypeInfo(eReference);
            Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
            Assert.Equal("String", typeInfo.Type.Name);
            Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
        }
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251

        [Fact]
        [WorkItem(557, "https://github.com/dotnet/roslyn/issues/557")]
        public void TestLambdaWithError11()
        {
            var source =
@"using System.Linq;

public static class Program
{
    public static void Main()
    {
        var x = new {
            X = """".Select(c => c.
            Y = 0,
        };
    }
}
";
J
Jared Parsons 已提交
2252
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
            var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
            Assert.Equal("c", eReference.ToString());
            var typeInfo = sm.GetTypeInfo(eReference);
            Assert.Equal(TypeKind.Struct, typeInfo.Type.TypeKind);
            Assert.Equal("Char", typeInfo.Type.Name);
            Assert.NotEmpty(typeInfo.Type.GetMembers("IsHighSurrogate")); // check it is the char we know and love
        }

        [Fact]
        [WorkItem(5498, "https://github.com/dotnet/roslyn/issues/5498")]
        public void TestLambdaWithError12()
        {
            var source =
@"using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        var z = args.Select(a => a.
2276
        var goo = 
2277 2278
    }
}";
J
Jared Parsons 已提交
2279
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
            var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
            Assert.Equal("a", eReference.ToString());
            var typeInfo = sm.GetTypeInfo(eReference);
            Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
            Assert.Equal("String", typeInfo.Type.Name);
            Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
        }
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331

        [WorkItem(5498, "https://github.com/dotnet/roslyn/issues/5498")]
        [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
        [Fact]
        public void TestLambdaWithError13()
        {
            // These tests ensure we attempt to perform type inference and bind a lambda expression
            // argument even when there are too many or too few arguments to an invocation, in the
            // case when there is more than one method in the method group.
            // See https://github.com/dotnet/roslyn/issues/11901 for the case of one method in the group
            var source =
@"using System;

class Program
{
    static void Main(string[] args)
    {
        Thing<string> t = null;
        t.X1(x => x, 1); // too many args
        t.X2(x => x);    // too few args
        t.M2(string.Empty, x => x, 1); // too many args
        t.M3(string.Empty, x => x); // too few args
    }
}
public class Thing<T>
{
    public void M2<T>(T x, Func<T, T> func) {}
    public void M3<T>(T x, Func<T, T> func, T y) {}

    // Ensure we have more than one method in the method group
    public void M2() {}
    public void M3() {}
}
public static class XThing
{
    public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null;
    public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null;

    // Ensure we have more than one method in the method group
    public static void X1(this object self) {}
    public static void X2(this object self) {}
}
2332
";
J
Jared Parsons 已提交
2333
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
            {
                var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
                Assert.Equal("x", reference.ToString());
                var typeInfo = sm.GetTypeInfo(reference);
                Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
                Assert.Equal("String", typeInfo.Type.Name);
                Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
            }
        }

        [Fact]
        [WorkItem(11901, "https://github.com/dotnet/roslyn/issues/11901")]
        public void TestLambdaWithError15()
        {
            // These tests ensure we attempt to perform type inference and bind a lambda expression
            // argument even when there are too many or too few arguments to an invocation, in the
            // case when there is exactly one method in the method group.
            var source =
@"using System;

class Program
{
    static void Main(string[] args)
    {
        Thing<string> t = null;
        t.X1(x => x, 1); // too many args
        t.X2(x => x);    // too few args
        t.M2(string.Empty, x => x, 1); // too many args
        t.M3(string.Empty, x => x); // too few args
    }
}
public class Thing<T>
{
    public void M2<T>(T x, Func<T, T> func) {}
    public void M3<T>(T x, Func<T, T> func, T y) {}
}
public static class XThing
{
    public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null;
    public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null;
}
";
J
Jared Parsons 已提交
2379
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
            {
                var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
                Assert.Equal("x", reference.ToString());
                var typeInfo = sm.GetTypeInfo(reference);
                Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
                Assert.Equal("String", typeInfo.Type.Name);
                Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
            }
        }

        [Fact]
        [WorkItem(11901, "https://github.com/dotnet/roslyn/issues/11901")]
        public void TestLambdaWithError16()
        {
            // These tests ensure we use the substituted method to bind a lambda expression
            // argument even when there are too many or too few arguments to an invocation, in the
            // case when there is exactly one method in the method group.
            var source =
@"using System;

class Program
{
    static void Main(string[] args)
    {
        Thing<string> t = null;
        t.X1<string>(x => x, 1); // too many args
        t.X2<string>(x => x);    // too few args
        t.M2<string>(string.Empty, x => x, 1); // too many args
        t.M3<string>(string.Empty, x => x); // too few args
    }
}
public class Thing<T>
{
    public void M2<T>(T x, Func<T, T> func) {}
    public void M3<T>(T x, Func<T, T> func, T y) {}
}
public static class XThing
{
    public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null;
    public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null;
}
";
J
Jared Parsons 已提交
2425
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
            {
                var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
                Assert.Equal("x", reference.ToString());
                var typeInfo = sm.GetTypeInfo(reference);
                Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
                Assert.Equal("String", typeInfo.Type.Name);
                Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
            }
        }

        [Fact]
        [WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")]
        public void TestLambdaWithError17()
        {
            var source =
@"using System;

class Program
{
    static void Main(string[] args)
    {
        Ma(action: (x, y) => x.ToString(), t: string.Empty);
        Mb(action: (x, y) => x.ToString(), t: string.Empty);
    }
    static void Ma<T>(T t, Action<T, T, int> action) { }
    static void Mb<T>(T t, Action<T, T, int> action) { }
    static void Mb() { }
}
";
J
Jared Parsons 已提交
2458
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
            {
                var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
                Assert.Equal("x", reference.ToString());
                var typeInfo = sm.GetTypeInfo(reference);
                Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
                Assert.Equal("String", typeInfo.Type.Name);
                Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
            }
        }

        [Fact]
        [WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")]
        public void TestLambdaWithError18()
        {
            var source =
@"using System;

class Program
{
    static void Main(string[] args)
    {
        Ma(string.Empty, (x, y) => x.ToString());
        Mb(string.Empty, (x, y) => x.ToString());
    }
    static void Ma<T>(T t, Action<T, T, int> action) { }
    static void Mb<T>(T t, Action<T, T, int> action) { }
    static void Mb() { }
}
";
J
Jared Parsons 已提交
2491
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
            {
                var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
                Assert.Equal("x", reference.ToString());
                var typeInfo = sm.GetTypeInfo(reference);
                Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
                Assert.Equal("String", typeInfo.Type.Name);
                Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
            }
        }

        [Fact]
        [WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")]
        public void TestLambdaWithError19()
        {
            var source =
@"using System;
using System.Linq.Expressions;

class Program
{
    static void Main(string[] args)
    {
        Ma(string.Empty, (x, y) => x.ToString());
        Mb(string.Empty, (x, y) => x.ToString());
        Mc(string.Empty, (x, y) => x.ToString());
    }
    static void Ma<T>(T t, Expression<Action<T, T, int>> action) { }
    static void Mb<T>(T t, Expression<Action<T, T, int>> action) { }
    static void Mb<T>(T t, Action<T, T, int> action) { }
    static void Mc<T>(T t, Expression<Action<T, T, int>> action) { }
    static void Mc() { }
}
2527
";
J
Jared Parsons 已提交
2528
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
            {
                var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
                Assert.Equal("x", reference.ToString());
                var typeInfo = sm.GetTypeInfo(reference);
                Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
                Assert.Equal("String", typeInfo.Type.Name);
                Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
            }
        }
2541

2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579
        // See MaxParameterListsForErrorRecovery.
        [Fact]
        public void BuildArgumentsForErrorRecovery_ManyOverloads()
        {
            BuildArgumentsForErrorRecovery_ManyOverloads_Internal(Binder.MaxParameterListsForErrorRecovery - 1, tooMany: false);
            BuildArgumentsForErrorRecovery_ManyOverloads_Internal(Binder.MaxParameterListsForErrorRecovery, tooMany: true);
        }

        private void BuildArgumentsForErrorRecovery_ManyOverloads_Internal(int n, bool tooMany)
        {
            var builder = new StringBuilder();
            builder.AppendLine("using System;");
            for (int i = 0; i < n; i++)
            {
                builder.AppendLine($"class C{i} {{ }}");
            }
            builder.Append(
@"class A { }
class B { }
class C
{
    void M()
    {
        F(1, (t, a, b, c) => { });
        var o = this[(a, b, c) => { }];
    }
");
            // Too few parameters.
            AppendLines(builder, n, i => $"    void F<T>(T t, Action<T, A, C{i}> a) {{ }}");
            AppendLines(builder, n, i => $"    object this[Action<A, C{i}> a] => {i}");
            // Type inference failure.
            AppendLines(builder, n, i => $"    void F<T, U>(T t, Action<T, U, C{i}> a) where U : T {{ }}");
            // Too many parameters.
            AppendLines(builder, n, i => $"    void F<T>(T t, Action<T, A, B, C, C{i}> a) {{ }}");
            AppendLines(builder, n, i => $"    object this[Action<A, B, C, C{i}> a] => {i}");
            builder.AppendLine("}");

            var source = builder.ToString();
J
Jared Parsons 已提交
2580
            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
2581 2582 2583 2584 2585 2586 2587 2588
            var tree = compilation.SyntaxTrees[0];
            var sm = compilation.GetSemanticModel(tree);
            var lambdas = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().ToArray();

            // F(1, (t, a, b, c) => { });
            var lambda = lambdas[0];
            var parameters = lambda.ParameterList.Parameters;
            var parameter = (ParameterSymbol)sm.GetDeclaredSymbol(parameters[0]);
2589
            Assert.False(parameter.Type.IsErrorType());
2590 2591
            Assert.Equal("System.Int32 t", parameter.ToTestDisplayString());
            parameter = (ParameterSymbol)sm.GetDeclaredSymbol(parameters[1]);
2592
            Assert.False(parameter.Type.IsErrorType());
2593 2594
            Assert.Equal("A a", parameter.ToTestDisplayString());
            parameter = (ParameterSymbol)sm.GetDeclaredSymbol(parameters[3]);
2595
            Assert.Equal(tooMany, parameter.Type.IsErrorType());
2596 2597 2598 2599 2600 2601
            Assert.Equal(tooMany ? "? c" : "C c", parameter.ToTestDisplayString());

            // var o = this[(a, b, c) => { }];
            lambda = lambdas[1];
            parameters = lambda.ParameterList.Parameters;
            parameter = (ParameterSymbol)sm.GetDeclaredSymbol(parameters[0]);
2602
            Assert.False(parameter.Type.IsErrorType());
2603 2604
            Assert.Equal("A a", parameter.ToTestDisplayString());
            parameter = (ParameterSymbol)sm.GetDeclaredSymbol(parameters[2]);
2605
            Assert.Equal(tooMany, parameter.Type.IsErrorType());
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
            Assert.Equal(tooMany ? "? c" : "C c", parameter.ToTestDisplayString());
        }

        private static void AppendLines(StringBuilder builder, int n, Func<int, string> getLine)
        {
            for (int i = 0; i < n; i++)
            {
                builder.AppendLine(getLine(i));
            }
        }

2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631
        [Fact]
        [WorkItem(13797, "https://github.com/dotnet/roslyn/issues/13797")]
        public void DelegateAsAction()
        {
            var source = @"
using System;

public static class C
{
    public static void M() => Dispatch(delegate { });

    public static T Dispatch<T>(Func<T> func) => default(T);

    public static void Dispatch(Action func) { }
}";
J
Jared Parsons 已提交
2632
            var comp = CreateCompilation(source);
2633 2634
            CompileAndVerify(comp);
        }
2635 2636

        [Fact, WorkItem(278481, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=278481")]
2637
        public void LambdaReturningNull_1()
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663
        {
            var src = @"
public static class ExtensionMethods
{
    public static System.Linq.IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
        this System.Linq.IQueryable<TOuter> outerValues,
        System.Linq.IQueryable<TInner> innerValues,
        System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector,
        System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector,
        System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> fullResultSelector,
        System.Linq.Expressions.Expression<System.Func<TOuter, TResult>> partialResultSelector,
        System.Collections.Generic.IEqualityComparer<TKey> comparer)
    { return null; }

    public static System.Linq.IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
        this System.Linq.IQueryable<TOuter> outerValues, 
        System.Linq.IQueryable<TInner> innerValues, 
        System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector, 
        System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector, 
        System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> fullResultSelector, 
        System.Linq.Expressions.Expression<System.Func<TOuter, TResult>> partialResultSelector)
    {
        System.Console.WriteLine(""1""); 
        return null; 
    }

2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
    public static System.Collections.Generic.IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
        this System.Collections.Generic.IEnumerable<TOuter> outerValues, 
        System.Linq.IQueryable<TInner> innerValues, 
        System.Func<TOuter, TKey> outerKeySelector, 
        System.Func<TInner, TKey> innerKeySelector, 
        System.Func<TOuter, TInner, TResult> fullResultSelector, 
        System.Func<TOuter, TResult> partialResultSelector)
    {
        System.Console.WriteLine(""2""); 
        return null; 
    }

2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
    public static System.Collections.Generic.IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
        this System.Collections.Generic.IEnumerable<TOuter> outerQueryable,
        System.Collections.Generic.IEnumerable<TInner> innerQueryable,
        System.Func<TOuter, TKey> outerKeySelector,
        System.Func<TInner, TKey> innerKeySelector,
        System.Func<TOuter, TInner, TResult> resultSelector)
    { return null; }
}

partial class C
{
    public static void Main()
    {
        System.Linq.IQueryable<A> outerValue = null;
        System.Linq.IQueryable<B> innerValues = null;

        outerValue.LeftOuterJoin(innerValues,
                    co => co.id,
                    coa => coa.id,
                    (co, coa) => null,
                    co => co);
    }
}

class A
{
    public int id=2;
}

class B
{
    public int id = 2;
}";
J
Jared Parsons 已提交
2709
            var comp = CreateCompilationWithMscorlib40AndSystemCore(src, options: TestOptions.DebugExe);
2710 2711
            CompileAndVerify(comp, expectedOutput: "1");
        }
2712

2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
        [Fact, WorkItem(296550, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=296550")]
        public void LambdaReturningNull_2()
        {
            var src = @"
class Test1<T>
    {
        public void M1(System.Func<T> x) {}
        public void M1<S>(System.Func<S> x) {}
        public void M2<S>(System.Func<S> x) {}
        public void M2(System.Func<T> x) {}
    }

    class Test2 : Test1<System.>
    {
        void Main()
        {
            M1(()=> null);
            M2(()=> null);
        }
    }
";
J
Jared Parsons 已提交
2734
            var comp = CreateCompilation(src, options: TestOptions.DebugDll);
2735 2736 2737 2738 2739 2740 2741 2742

            comp.VerifyDiagnostics(
                // (10,32): error CS1001: Identifier expected
                //     class Test2 : Test1<System.>
                Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(10, 32)
                );
        }

2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
        [Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")]
        public void LambdaSquigglesArea()
        {
            var src = @"
class C
{
    void M()
    {
        System.Func<bool, System.Action<bool>> x = x1 => x2 =>
        {
            error();
        };
    }
}
";
J
Jared Parsons 已提交
2758
            var comp = CreateCompilation(src);
2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783
            comp.VerifyDiagnostics(
                // (8,13): error CS0103: The name 'error' does not exist in the current context
                //             error();
                Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13),
                // (6,58): 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
                //         System.Func<bool, System.Action<bool>> x = x1 => x2 =>
                Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "x2 =>").WithArguments("lambda expression").WithLocation(6, 58)
                );
        }

        [Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")]
        public void LambdaSquigglesAreaInAsync()
        {
            var src = @"
class C
{
    void M()
    {
        System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 =>
        {
            error();
        };
    }
}
";
J
Jared Parsons 已提交
2784
            var comp = CreateCompilation(src);
2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
            comp.VerifyDiagnostics(
                // (8,13): error CS0103: The name 'error' does not exist in the current context
                //             error();
                Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13),
                // (6,93): error CS4010: Cannot convert async lambda expression to delegate type 'Task<Action<bool>>'. An async lambda expression may return void, Task or Task<T>, none of which are convertible to 'Task<Action<bool>>'.
                //         System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 =>
                Diagnostic(ErrorCode.ERR_CantConvAsyncAnonFuncReturns, "x2 =>").WithArguments("lambda expression", "System.Threading.Tasks.Task<System.Action<bool>>").WithLocation(6, 93),
                // (6,90): 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.
                //         System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 =>
                Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(6, 90)
                );
        }

        [Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")]
        public void DelegateSquigglesArea()
        {
            var src = @"
class C
{
    void M()
    {
        System.Func<bool, System.Action<bool>> x = x1 => delegate(bool x2)
        {
            error();
        };
    }
}
";
J
Jared Parsons 已提交
2813
            var comp = CreateCompilation(src);
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
            comp.VerifyDiagnostics(
                // (8,13): error CS0103: The name 'error' does not exist in the current context
                //             error();
                Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13),
                // (6,58): 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
                //         System.Func<bool, System.Action<bool>> x = x1 => delegate(bool x2)
                Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "delegate(bool x2)").WithArguments("lambda expression").WithLocation(6, 58)
                );
        }

        [Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")]
        public void DelegateWithoutArgumentsSquigglesArea()
        {
            var src = @"
class C
{
    void M()
    {
        System.Func<bool, System.Action> x = x1 => delegate
        {
            error();
        };
    }
}
";
J
Jared Parsons 已提交
2839
            var comp = CreateCompilation(src);
2840 2841 2842 2843 2844 2845 2846 2847 2848 2849
            comp.VerifyDiagnostics(
                // (8,13): error CS0103: The name 'error' does not exist in the current context
                //             error();
                Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13),
                // (6,52): 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
                //         System.Func<bool, System.Action> x = x1 => delegate
                Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "delegate").WithArguments("lambda expression").WithLocation(6, 52)
                );
        }

2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895
        [Fact]
        public void ThrowExpression_Lambda()
        {
            var src = @"using System;
class C
{
    public static void Main()
    {
        Action a = () => throw new Exception(""1"");
        try
        {
            a();
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message);
        }
        Func<int, int> b = x => throw new Exception(""2"");
        try
        {
            b(0);
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message);
        }
        b = (int x) => throw new Exception(""3"");
        try
        {
            b(0);
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message);
        }
        b = (x) => throw new Exception(""4"");
        try
        {
            b(0);
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message);
        }
    }
}";
J
Jared Parsons 已提交
2896
            var comp = CreateCompilationWithMscorlib40AndSystemCore(src, options: TestOptions.DebugExe);
2897 2898
            CompileAndVerify(comp, expectedOutput: "1234");
        }
2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915

        [Fact, WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
        public void InMalformedEmbeddedStatement_01()
        {
            var source = @"
class Program
{
    void method1()
    {
        if (method2())
            .Any(b => b.ContentType, out var chars)
        {
        }
    }
}
";
            var tree = SyntaxFactory.ParseSyntaxTree(source);
J
Jared Parsons 已提交
2916
            var comp = CreateCompilation(tree);
2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957

            ExpressionSyntax contentType = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "ContentType").Single();

            var model = comp.GetSemanticModel(tree);
            Assert.Equal("ContentType", contentType.ToString());
            Assert.Null(model.GetSymbolInfo(contentType).Symbol);
            Assert.Equal(TypeKind.Error, model.GetTypeInfo(contentType).Type.TypeKind);

            ExpressionSyntax b = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b").Single();

            model = comp.GetSemanticModel(tree);
            Assert.Equal("b", b.ToString());
            ISymbol symbol = model.GetSymbolInfo(b).Symbol;
            Assert.Equal(SymbolKind.Parameter, symbol.Kind);
            Assert.Equal("? b", symbol.ToTestDisplayString());
            Assert.Equal(TypeKind.Error, model.GetTypeInfo(b).Type.TypeKind);

            ParameterSyntax parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single();

            model = comp.GetSemanticModel(tree);
            symbol = model.GetDeclaredSymbol(parameterSyntax);
            Assert.Equal(SymbolKind.Parameter, symbol.Kind);
            Assert.Equal("? b", symbol.ToTestDisplayString());
        }

        [Fact, WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
        public void InMalformedEmbeddedStatement_02()
        {
            var source = @"
class Program
{
    void method1()
    {
        if (method2())
            .Any(b => b.ContentType, out var chars)
        {
        }
    }
}
";
            var tree = SyntaxFactory.ParseSyntaxTree(source);
J
Jared Parsons 已提交
2958
            var comp = CreateCompilation(tree);
2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977

            ExpressionSyntax contentType = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "ContentType").Single();

            var model = comp.GetSemanticModel(tree);
            Assert.Equal("ContentType", contentType.ToString());
            var lambda = (MethodSymbol)model.GetEnclosingSymbol(contentType.SpanStart);
            Assert.Equal(MethodKind.AnonymousFunction, lambda.MethodKind);

            ExpressionSyntax b = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b").Single();

            model = comp.GetSemanticModel(tree);
            Assert.Equal("b", b.ToString());
            lambda = (MethodSymbol)model.GetEnclosingSymbol(b.SpanStart);
            Assert.Equal(MethodKind.AnonymousFunction, lambda.MethodKind);

            model = comp.GetSemanticModel(tree);
            ParameterSyntax parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single();
            Assert.Equal("void Program.method1()", model.GetEnclosingSymbol(parameterSyntax.SpanStart).ToTestDisplayString());
        }
C
Charles Stoner 已提交
2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102

        [Fact]
        public void ShadowNames_Local()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
    static void M()
    {
        Action a1 = () => { object x = 0; }; // local
        Action<string> a2 = x => { }; // parameter
        Action<string> a3 = (string x) => { }; // parameter
        object x = null;
        Action a4 = () => { void x() { } }; // method
        Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
    }
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (9,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Action a1 = () => { object x = 0; }; // local
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 36),
                // (10,29): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Action<string> a2 = x => { }; // parameter
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 29),
                // (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Action<string> a3 = (string x) => { }; // parameter
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37),
                // (13,34): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Action a4 = () => { void x() { } }; // method
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(13, 34),
                // (14,38): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
                //         Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
                Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(14, 38));

            comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
            comp.VerifyDiagnostics();

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }

        [Fact]
        public void ShadowNames_Parameter()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
    static Action<object> F = (object x) =>
    {
        Action a1 = () => { object x = 0; }; // local
        Action<string> a2 = x => { }; // parameter
        Action<string> a3 = (string x) => { }; // parameter
        Action a4 = () => { void x() { } }; // method
        Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
    };
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (9,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Action a1 = () => { object x = 0; }; // local
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 36),
                // (10,29): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Action<string> a2 = x => { }; // parameter
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 29),
                // (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Action<string> a3 = (string x) => { }; // parameter
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37),
                // (13,38): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
                //         Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
                Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 38));

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }

        [Fact]
        public void ShadowNames_TypeParameter()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
    static void M<x>()
    {
        Action a1 = () => { object x = 0; }; // local
        Action<string> a2 = x => { }; // parameter
        Action<string> a3 = (string x) => { }; // parameter
        Action a4 = () => { void x() { } }; // method
        Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
    }
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (9,36): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
                //         Action a1 = () => { object x = 0; }; // local
                Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 36),
                // (10,29): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
                //         Action<string> a2 = x => { }; // parameter
                Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 29),
                // (11,37): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
                //         Action<string> a3 = (string x) => { }; // parameter
                Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(11, 37),
                // (12,34): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
                //         Action a4 = () => { void x() { } }; // method
                Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(12, 34),
                // (13,38): error CS1948: The range variable 'x' cannot have the same name as a method type parameter
                //         Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
                Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(13, 38));

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }

C
Charles Stoner 已提交
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140
        [Fact]
        public void ShadowNames_QueryParameter()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
    static void Main(string[] args)
    {
        _ = from x in args select (Action)(() => { object x = 0; }); // local
        _ = from x in args select (Action<string>)(x => { }); // parameter
        _ = from x in args select (Action<string>)((string x) => { }); // parameter
        _ = from x in args select (Action)(() => { void x() { } }); // method
        _ = from x in args select (Action)(() => { _ = from x in new[] { 1, 2, 3 } select x; }); // range variable
    }
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (9,59): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         _ = from x in args select (Action)(() => { object x = 0; }); // local
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 59),
                // (10,52): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         _ = from x in args select (Action<string>)(x => { }); // parameter
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 52),
                // (11,60): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         _ = from x in args select (Action<string>)((string x) => { }); // parameter
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 60),
                // (13,61): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
                //         _ = from x in args select (Action)(() => { _ = from x in new[] { 1, 2, 3 } select x; }); // range variable
                Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 61));

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }

C
Charles Stoner 已提交
3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252
        [Fact]
        public void ShadowNames_Local_Delegate()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
    static void M()
    {
        object x = null;
        Action a1 = delegate() { object x = 0; }; // local
        Action<string> a2 = delegate(string x) { }; // parameter
        Action a3 = delegate() { void x() { } }; // method
        Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
    }
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (10,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Action a1 = delegate() { object x = 0; }; // local
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 41),
                // (11,45): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Action<string> a2 = delegate(string x) { }; // parameter
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 45),
                // (12,39): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Action a3 = delegate() { void x() { } }; // method
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 39),
                // (13,43): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
                //         Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
                Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 43));

            comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
            comp.VerifyDiagnostics();

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }

        [Fact]
        public void ShadowNames_Parameter_Delegate()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
    static Action<object> F = (object x) =>
    {
        Action a1 = delegate() { object x = 0; }; // local
        Action<string> a2 = delegate(string x) { }; // parameter
        Action a3 = delegate() { void x() { } }; // method
        Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
    };
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (9,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Action a1 = delegate() { object x = 0; }; // local
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 41),
                // (10,45): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Action<string> a2 = delegate(string x) { }; // parameter
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 45),
                // (12,43): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
                //         Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
                Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 43));

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }

        [Fact]
        public void ShadowNames_TypeParameter_Delegate()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
    static void M<x>()
    {
        Action a1 = delegate() { object x = 0; }; // local
        Action<string> a2 = delegate(string x) { }; // parameter
        Action a3 = delegate() { void x() { } }; // method
        Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
    }
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (9,41): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
                //         Action a1 = delegate() { object x = 0; }; // local
                Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 41),
                // (10,45): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
                //         Action<string> a2 = delegate(string x) { }; // parameter
                Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 45),
                // (11,39): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
                //         Action a3 = delegate() { void x() { } }; // method
                Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(11, 39),
                // (12,43): error CS1948: The range variable 'x' cannot have the same name as a method type parameter
                //         Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
                Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(12, 43));

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }

C
Charles Stoner 已提交
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
        [Fact]
        public void ShadowNames_LambdaInsideLambda()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
    static void M<T>(object x)
    {
        Action a1 = () =>
        {
            Action b1 = () => { object x = 1; }; // local
            Action<string> b2 = (string x) => { }; // parameter
        };
        Action a2 = () =>
        {
            Action b3 = () => { object T = 3; }; // local
            Action<string> b4 = T => { }; // parameter
        };
    }
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (10,40): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //             Action b1 = () => { object x = 1; }; // local
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 40),
                // (11,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //             Action<string> b2 = (string x) => { }; // parameter
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 41),
                // (15,40): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
                //             Action b3 = () => { object T = 3; }; // local
                Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(15, 40),
                // (16,33): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
                //             Action<string> b4 = T => { }; // parameter
                Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(16, 33));

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }

C
Charles Stoner 已提交
3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347
        [Fact]
        public void ShadowNames_Underscore_01()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
    static void M()
    {
        Func<int, Func<int, int>> f = _ => _ => _;
    }
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (8,44): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Func<int, Func<int, int>> f = _ => _ => _;
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(8, 44));

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }

        [Fact]
        public void ShadowNames_Underscore_02()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
    static void M()
    {
        Func<int, int, int> f = (_, _) => 0;
    }
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            verifyDiagnostics();

            comp = CreateCompilation(source);
            verifyDiagnostics();

            void verifyDiagnostics()
            {
                comp.VerifyDiagnostics(
                    // (8,37): error CS0100: The parameter name '_' is a duplicate
                    //         Func<int, int, int> f = (_, _) => 0;
                    Diagnostic(ErrorCode.ERR_DuplicateParamName, "_").WithArguments("_").WithLocation(8, 37));
            }
        }

C
Charles Stoner 已提交
3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404
        [Fact]
        public void ShadowNames_Nested_01()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
    static void M()
    {
        Func<int, Func<int, Func<int, int>>> f = x => x => x => x;
    }
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (8,55): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Func<int, Func<int, Func<int, int>>> f = x => x => x => x;
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 55),
                // (8,60): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Func<int, Func<int, Func<int, int>>> f = x => x => x => x;
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 60));

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }

        [Fact]
        public void ShadowNames_Nested_02()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
    static void M()
    {
        Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _;
    }
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (8,87): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _;
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 87),
                // (8,94): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _;
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(8, 94),
                // (8,97): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //         Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _;
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(8, 97));

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }

C
Charles Stoner 已提交
3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483
        [Fact]
        public void ShadowNames_LambdaInsideLocalFunction_01()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
    static void M()
    {
        void F1()
        {
            object x = null;
            Action a1 = () => { int x = 0; };
        }
        void F2<T>()
        {
            Action a2 = () => { int T = 0; };
        }
    }
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //             Action a1 = () => { int x = 0; };
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37),
                // (15,37): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
                //             Action a2 = () => { int T = 0; };
                Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(15, 37));

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }

        [Fact]
        public void ShadowNames_LambdaInsideLocalFunction_02()
        {
            var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
    static void M<T>()
    {
        object x = null;
        void F()
        {
            Action<int> a1 = (int x) =>
            {
                Action b1 = () => { int T = 0; };
            };
            Action a2 = () =>
            {
                int x = 0;
                Action<int> b2 = (int T) => { };
            };
        }
    }
}";
            var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
            comp.VerifyDiagnostics(
                // (11,35): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //             Action<int> a1 = (int x) =>
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 35),
                // (13,41): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
                //                 Action b1 = () => { int T = 0; };
                Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(13, 41),
                // (17,21): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                //                 int x = 0;
                Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(17, 21),
                // (18,39): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
                //                 Action<int> b2 = (int T) => { };
                Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(18, 39));

            comp = CreateCompilation(source);
            comp.VerifyDiagnostics();
        }
3484 3485
    }
}