CodeGenFunctionPointersTests.cs 412.0 KB
Newer Older
1 2 3
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
4 5 6
#nullable enable

using System;
F
Fredric Silberberg 已提交
7
using System.Collections.Generic;
8
using System.Collections.Immutable;
F
Fredric Silberberg 已提交
9
using System.IO;
F
Fredric Silberberg 已提交
10
using System.Linq;
F
Fredric Silberberg 已提交
11 12 13 14
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
15 16
using Microsoft.Cci;
using Microsoft.CodeAnalysis.CSharp.Symbols;
F
Fredric Silberberg 已提交
17
using Microsoft.CodeAnalysis.CSharp.Syntax;
18
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
19
using Microsoft.CodeAnalysis.PooledObjects;
20
using Microsoft.CodeAnalysis.Test.Utilities;
F
Fredric Silberberg 已提交
21
using Roslyn.Test.Utilities;
22
using Xunit;
F
Fredric Silberberg 已提交
23
using static Microsoft.CodeAnalysis.CSharp.UnitTests.FunctionPointerUtilities;
24 25 26 27 28

namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
    public class CodeGenFunctionPointersTests : CSharpTestBase
    {
F
Fredric Silberberg 已提交
29
        private CompilationVerifier CompileAndVerifyFunctionPointers(
30
                CSharpTestSource sources,
31 32 33 34 35 36
                MetadataReference[]? references = null,
                Action<ModuleSymbol>? symbolValidator = null,
                string? expectedOutput = null,
                TargetFramework targetFramework = TargetFramework.Standard,
                CSharpCompilationOptions? options = null,
                bool overrideUnmanagedSupport = false)
37
        {
38
            var comp = CreateCompilation(
39
                sources,
40
                references,
41
                parseOptions: TestOptions.Regular9,
42 43
                options: options ?? (expectedOutput is null ? TestOptions.UnsafeReleaseDll : TestOptions.UnsafeReleaseExe),
                targetFramework: targetFramework);
44 45 46 47

            if (overrideUnmanagedSupport) comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();

            return CompileAndVerify(comp, symbolValidator: symbolValidator, expectedOutput: expectedOutput, verify: Verification.Skipped);
48 49
        }

50
        private static CSharpCompilation CreateCompilationWithFunctionPointers(CSharpTestSource source, IEnumerable<MetadataReference>? references = null, CSharpCompilationOptions? options = null)
51 52 53 54
        {
            return CreateCompilation(source, references: references, options: options ?? TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9);
        }

55
        private CompilationVerifier CompileAndVerifyFunctionPointersWithIl(string source, string ilStub, Action<ModuleSymbol>? symbolValidator = null, string? expectedOutput = null)
F
Fredric Silberberg 已提交
56
        {
57 58
            var comp = CreateCompilationWithIL(source, ilStub, parseOptions: TestOptions.Regular9, options: expectedOutput is null ? TestOptions.UnsafeReleaseDll : TestOptions.UnsafeReleaseExe);
            return CompileAndVerify(comp, expectedOutput: expectedOutput, symbolValidator: symbolValidator, verify: Verification.Skipped);
F
Fredric Silberberg 已提交
59 60
        }

61
        private static CSharpCompilation CreateCompilationWithFunctionPointersAndIl(string source, string ilStub, IEnumerable<MetadataReference>? references = null, CSharpCompilationOptions? options = null)
F
Fredric Silberberg 已提交
62
        {
63
            return CreateCompilationWithIL(source, ilStub, references: references, options: options ?? TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9);
F
Fredric Silberberg 已提交
64 65
        }

66 67 68
        [Theory]
        [InlineData("", CallingConvention.Default)]
        [InlineData("managed", CallingConvention.Default)]
69 70 71 72
        [InlineData("unmanaged[Cdecl]", CallingConvention.CDecl)]
        [InlineData("unmanaged[Thiscall]", CallingConvention.ThisCall)]
        [InlineData("unmanaged[Stdcall]", CallingConvention.Standard)]
        [InlineData("unmanaged[Fastcall]", CallingConvention.FastCall)]
73 74 75 76
        [InlineData("unmanaged[@Cdecl]", CallingConvention.CDecl)]
        [InlineData("unmanaged[@Thiscall]", CallingConvention.ThisCall)]
        [InlineData("unmanaged[@Stdcall]", CallingConvention.Standard)]
        [InlineData("unmanaged[@Fastcall]", CallingConvention.FastCall)]
77
        [InlineData("unmanaged", CallingConvention.Unmanaged)]
78 79
        internal void CallingConventions(string conventionString, CallingConvention expectedConvention)
        {
F
Fredric Silberberg 已提交
80
            var verifier = CompileAndVerifyFunctionPointers($@"
81 82
class C
{{
83
    public unsafe delegate* {conventionString}<string, int> M() => throw null;
84
}}", symbolValidator: symbolValidator, overrideUnmanagedSupport: true);
85

F
Fredric Silberberg 已提交
86
            symbolValidator(GetSourceModule(verifier));
F
Fredric Silberberg 已提交
87

88 89 90 91 92 93 94 95 96 97 98 99
            void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
                var m = c.GetMethod("M");
                var funcPtr = m.ReturnType;

                VerifyFunctionPointerSymbol(funcPtr, expectedConvention,
                    (RefKind.None, IsSpecialType(SpecialType.System_Int32)),
                    (RefKind.None, IsSpecialType(SpecialType.System_String)));
            }
        }

F
Fredric Silberberg 已提交
100 101 102
        [Fact]
        public void MultipleCallingConventions()
        {
103
            var comp = CompileAndVerifyFunctionPointers(@"
F
Fredric Silberberg 已提交
104 105 106
#pragma warning disable CS0168
unsafe class C
{
107 108
    public delegate* unmanaged[Thiscall, Stdcall]<void> M() => throw null;
}", symbolValidator: symbolValidator, overrideUnmanagedSupport: true);
F
Fredric Silberberg 已提交
109

110 111 112 113 114 115
            void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
                var m = c.GetMethod("M");
                var funcPtr = m.ReturnType;

116
                AssertEx.Equal("delegate* unmanaged[Thiscall, Stdcall]<System.Void modopt(System.Runtime.CompilerServices.CallConvThiscall) modopt(System.Runtime.CompilerServices.CallConvStdcall)>", funcPtr.ToTestDisplayString());
117 118
                Assert.Equal(CallingConvention.Unmanaged, ((FunctionPointerTypeSymbol)funcPtr).Signature.CallingConvention);
            }
F
Fredric Silberberg 已提交
119 120
        }

121 122 123
        [Fact]
        public void RefParameters()
        {
F
Fredric Silberberg 已提交
124
            var verifier = CompileAndVerifyFunctionPointers(@"
125 126
class C
{
127 128
    public unsafe void M(delegate*<ref C, ref string, ref int[]> param1) => throw null;
}", symbolValidator: symbolValidator);
129

F
Fredric Silberberg 已提交
130
            symbolValidator(GetSourceModule(verifier));
F
Fredric Silberberg 已提交
131

132 133 134 135 136 137 138 139 140 141 142 143 144
            static void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
                var m = c.GetMethod("M");
                var funcPtr = m.ParameterTypesWithAnnotations[0].Type;

                VerifyFunctionPointerSymbol(funcPtr, CallingConvention.Default,
                    (RefKind.Ref, IsArrayType(IsSpecialType(SpecialType.System_Int32))),
                    (RefKind.Ref, IsTypeName("C")),
                    (RefKind.Ref, IsSpecialType(SpecialType.System_String)));
            }
        }

145 146 147
        [Fact]
        public void OutParameters()
        {
F
Fredric Silberberg 已提交
148
            var verifier = CompileAndVerifyFunctionPointers(@"
149 150 151 152 153
class C
{
    public unsafe void M(delegate*<out C, out string, ref int[]> param1) => throw null;
}", symbolValidator: symbolValidator);

F
Fredric Silberberg 已提交
154
            symbolValidator(GetSourceModule(verifier));
F
Fredric Silberberg 已提交
155

156 157 158 159 160 161 162 163 164 165 166 167 168
            static void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
                var m = c.GetMethod("M");
                var funcPtr = m.ParameterTypesWithAnnotations[0].Type;

                VerifyFunctionPointerSymbol(funcPtr, CallingConvention.Default,
                    (RefKind.Ref, IsArrayType(IsSpecialType(SpecialType.System_Int32))),
                    (RefKind.Out, IsTypeName("C")),
                    (RefKind.Out, IsSpecialType(SpecialType.System_String)));
            }
        }

169 170 171
        [Fact]
        public void NestedFunctionPointers()
        {
F
Fredric Silberberg 已提交
172
            var verifier = CompileAndVerifyFunctionPointers(@"
173 174
public class C
{
175
    public unsafe delegate* unmanaged[Cdecl]<delegate* unmanaged[Stdcall]<int, void>, void> M(delegate*<C, delegate*<S>> param1) => throw null;
176 177 178
}
public struct S
{
179
}", symbolValidator: symbolValidator);
F
Fredric Silberberg 已提交
180

F
Fredric Silberberg 已提交
181
            symbolValidator(GetSourceModule(verifier));
F
Fredric Silberberg 已提交
182

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
            static void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
                var m = c.GetMethod("M");
                var returnType = m.ReturnType;

                VerifyFunctionPointerSymbol(returnType, CallingConvention.CDecl,
                    (RefKind.None, IsVoidType()),
                    (RefKind.None, IsFunctionPointerTypeSymbol(CallingConvention.Standard,
                        (RefKind.None, IsVoidType()),
                        (RefKind.None, IsSpecialType(SpecialType.System_Int32)))
                        ));

                var paramType = m.Parameters[0].Type;
                VerifyFunctionPointerSymbol(paramType, CallingConvention.Default,
                    (RefKind.None, IsFunctionPointerTypeSymbol(CallingConvention.Default,
                        (RefKind.None, IsTypeName("S")))),
                    (RefKind.None, IsTypeName("C")));
            }
        }

        [Fact]
        public void InModifier()
        {
F
Fredric Silberberg 已提交
207
            var verifier = CompileAndVerifyFunctionPointers(@"
208 209
public class C
{
210 211
    public unsafe void M(delegate*<in string, in int, ref readonly bool> param) {}
}", symbolValidator: symbolValidator);
212

F
Fredric Silberberg 已提交
213
            symbolValidator(GetSourceModule(verifier));
F
Fredric Silberberg 已提交
214

215 216 217 218 219 220 221 222 223 224 225 226 227
            static void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
                var m = c.GetMethod("M");
                var paramType = m.Parameters[0].Type;

                VerifyFunctionPointerSymbol(paramType, CallingConvention.Default,
                    (RefKind.RefReadOnly, IsSpecialType(SpecialType.System_Boolean)),
                    (RefKind.In, IsSpecialType(SpecialType.System_String)),
                    (RefKind.In, IsSpecialType(SpecialType.System_Int32)));
            }
        }

F
Fredric Silberberg 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
        [Fact]
        public void BadReturnModReqs()
        {
            var il = @"
.class public auto ansi beforefieldinit C
       extends [mscorlib]System.Object
{
    .field public method int32 modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)& *() 'Field1'
    .field public method int32& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) *() 'Field2'
    .field public method int32& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) modreq([mscorlib]System.Runtime.InteropServices.InAttribute) *() 'Field3'
    .field public method int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) *() 'Field4'
    .field public method int32 modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) *() 'Field5'
    .field public method int32 modreq([mscorlib]System.Runtime.InteropServices.InAttribute)& *() 'Field6'
    .field public method int32 modreq([mscorlib]System.Object)& *() 'Field7'
    .field public method int32& modreq([mscorlib]System.Object) *() 'Field8'
F
Fredric Silberberg 已提交
243
    .field static public method method int32 modreq([mscorlib]System.Object) *() *() 'Field9'
F
Fredric Silberberg 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
}
";

            var source = @"
class D
{
    void M(C c)
    {
        ref int i1 = ref c.Field1();
        ref int i2 = ref c.Field2();
        c.Field1 = c.Field1;
        c.Field2 = c.Field2;
    }
}";

            var comp = CreateCompilationWithFunctionPointersAndIl(source, il);

            comp.VerifyDiagnostics(
262
                // (6,26): error CS0570: 'delegate*<int>' is not supported by the language
F
Fredric Silberberg 已提交
263
                //         ref int i1 = ref c.Field1();
264 265 266 267 268 269 270 271
                Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field1()").WithArguments("delegate*<int>").WithLocation(6, 26),
                // (6,28): error CS0570: 'C.Field1' is not supported by the language
                //         ref int i1 = ref c.Field1();
                Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(6, 28),
                // (7,26): error CS0570: 'delegate*<int>' is not supported by the language
                //         ref int i2 = ref c.Field2();
                Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field2()").WithArguments("delegate*<int>").WithLocation(7, 26),
                // (7,28): error CS0570: 'C.Field2' is not supported by the language
F
Fredric Silberberg 已提交
272
                //         ref int i2 = ref c.Field2();
273
                Diagnostic(ErrorCode.ERR_BindToBogus, "Field2").WithArguments("C.Field2").WithLocation(7, 28),
F
Fredric Silberberg 已提交
274
                // (8,11): error CS0570: 'C.Field1' is not supported by the language
F
Fredric Silberberg 已提交
275
                //         c.Field1 = c.Field1;
F
Fredric Silberberg 已提交
276 277
                Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(8, 11),
                // (8,22): error CS0570: 'C.Field1' is not supported by the language
F
Fredric Silberberg 已提交
278
                //         c.Field1 = c.Field1;
F
Fredric Silberberg 已提交
279 280
                Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(8, 22),
                // (9,11): error CS0570: 'C.Field2' is not supported by the language
F
Fredric Silberberg 已提交
281
                //         c.Field2 = c.Field2;
F
Fredric Silberberg 已提交
282 283
                Diagnostic(ErrorCode.ERR_BindToBogus, "Field2").WithArguments("C.Field2").WithLocation(9, 11),
                // (9,22): error CS0570: 'C.Field2' is not supported by the language
F
Fredric Silberberg 已提交
284
                //         c.Field2 = c.Field2;
F
Fredric Silberberg 已提交
285
                Diagnostic(ErrorCode.ERR_BindToBogus, "Field2").WithArguments("C.Field2").WithLocation(9, 22)
F
Fredric Silberberg 已提交
286 287 288 289
            );

            var c = comp.GetTypeByMetadataName("C");

F
Fredric Silberberg 已提交
290 291 292
            for (int i = 1; i <= 9; i++)
            {
                var field = c.GetField($"Field{i}");
293 294 295 296 297 298 299 300
                Assert.True(field.HasUseSiteError);
                Assert.True(field.HasUnsupportedMetadata);
                Assert.Equal(TypeKind.FunctionPointer, field.Type.TypeKind);
                var signature = ((FunctionPointerTypeSymbol)field.Type).Signature;
                Assert.True(signature.HasUseSiteError);
                Assert.True(signature.HasUnsupportedMetadata);
                Assert.True(field.Type.HasUseSiteError);
                Assert.True(field.Type.HasUnsupportedMetadata);
F
Fredric Silberberg 已提交
301
            }
F
Fredric Silberberg 已提交
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
        }

        [Fact]
        public void BadParamModReqs()
        {
            var il = @"
.class public auto ansi beforefieldinit C
       extends [mscorlib]System.Object
{
    .field public method void *(int32& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) modreq([mscorlib]System.Runtime.InteropServices.InAttribute)) 'Field1'
    .field public method void *(int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)) 'Field2'
    .field public method void *(int32 modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)& modreq([mscorlib]System.Runtime.InteropServices.InAttribute)) 'Field3'
    .field public method void *(int32 modreq([mscorlib]System.Runtime.InteropServices.InAttribute)& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)) 'Field4'
    .field public method void *(int32 modreq([mscorlib]System.Runtime.InteropServices.InAttribute)&) 'Field5'
    .field public method void *(int32 modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)&) 'Field6'
    .field public method void *(int32& modreq([mscorlib]System.Object)) 'Field7'
    .field public method void *(int32 modreq([mscorlib]System.Object)&) 'Field8'
F
Fredric Silberberg 已提交
319
    .field public method void *(method void *(int32 modreq([mscorlib]System.Object))) 'Field9'
F
Fredric Silberberg 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
}
";

            var source = @"
class D
{
    void M(C c)
    {
        int i = 1;
        c.Field1(ref i);
        c.Field1(in i);
        c.Field1(out i);
        c.Field1 = c.Field1;
    }
}";

            var comp = CreateCompilationWithFunctionPointersAndIl(source, il);
            comp.VerifyDiagnostics(
338
                // (7,9): error CS0570: 'delegate*<in int, void>' is not supported by the language
F
Fredric Silberberg 已提交
339
                //         c.Field1(ref i);
340 341 342 343 344
                Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field1(ref i)").WithArguments("delegate*<in int, void>").WithLocation(7, 9),
                // (7,11): error CS0570: 'C.Field1' is not supported by the language
                //         c.Field1(ref i);
                Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(7, 11),
                // (8,9): error CS0570: 'delegate*<in int, void>' is not supported by the language
F
Fredric Silberberg 已提交
345
                //         c.Field1(in i);
346 347 348 349 350 351 352 353
                Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field1(in i)").WithArguments("delegate*<in int, void>").WithLocation(8, 9),
                // (8,11): error CS0570: 'C.Field1' is not supported by the language
                //         c.Field1(in i);
                Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(8, 11),
                // (9,9): error CS0570: 'delegate*<in int, void>' is not supported by the language
                //         c.Field1(out i);
                Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field1(out i)").WithArguments("delegate*<in int, void>").WithLocation(9, 9),
                // (9,11): error CS0570: 'C.Field1' is not supported by the language
F
Fredric Silberberg 已提交
354
                //         c.Field1(out i);
355
                Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(9, 11),
F
Fredric Silberberg 已提交
356
                // (10,11): error CS0570: 'C.Field1' is not supported by the language
F
Fredric Silberberg 已提交
357
                //         c.Field1 = c.Field1;
F
Fredric Silberberg 已提交
358 359
                Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(10, 11),
                // (10,22): error CS0570: 'C.Field1' is not supported by the language
F
Fredric Silberberg 已提交
360
                //         c.Field1 = c.Field1;
F
Fredric Silberberg 已提交
361
                Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(10, 22)
F
Fredric Silberberg 已提交
362 363 364 365
            );

            var c = comp.GetTypeByMetadataName("C");

F
Fredric Silberberg 已提交
366 367 368
            for (int i = 1; i <= 9; i++)
            {
                var field = c.GetField($"Field{i}");
369 370 371 372 373 374 375 376
                Assert.True(field.HasUseSiteError);
                Assert.True(field.HasUnsupportedMetadata);
                Assert.Equal(TypeKind.FunctionPointer, field.Type.TypeKind);
                var signature = ((FunctionPointerTypeSymbol)field.Type).Signature;
                Assert.True(signature.HasUseSiteError);
                Assert.True(signature.HasUnsupportedMetadata);
                Assert.True(field.Type.HasUseSiteError);
                Assert.True(field.Type.HasUnsupportedMetadata);
F
Fredric Silberberg 已提交
377
            }
F
Fredric Silberberg 已提交
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
        }

        [Fact]
        public void ValidModReqsAndOpts()
        {
            var il = @"
.class public auto ansi beforefieldinit C
       extends [mscorlib]System.Object
{
    .field static public method int32& modopt([mscorlib]System.Runtime.InteropServices.OutAttribute) modreq([mscorlib]System.Runtime.InteropServices.InAttribute) *() 'Field1'
    .field static public method int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modopt([mscorlib]System.Runtime.InteropServices.OutAttribute) *() 'Field2'
    .field static public method void *(int32& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) modopt([mscorlib]System.Runtime.InteropServices.InAttribute)) 'Field3'
    .field static public method void *(int32& modopt([mscorlib]System.Runtime.InteropServices.OutAttribute) modreq([mscorlib]System.Runtime.InteropServices.InAttribute)) 'Field4'
    .field static public method void *(int32& modopt([mscorlib]System.Runtime.InteropServices.InAttribute) modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)) 'Field5'
    .field static public method void *(int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modopt([mscorlib]System.Runtime.InteropServices.OutAttribute)) 'Field6'
}
";

            var source = @"
using System;
unsafe class D
{
    static int i = 1;
    static ref readonly int M()
    {
        return ref i;
    }
    static void MIn(in int param)
    {
        Console.Write(param);
    }
    static void MOut(out int param)
    {
        param = i;
    }

    static void Main()
    {
        TestRefReadonly();
        TestOut();
        TestIn();
    }

    static void TestRefReadonly()
    {
        C.Field1 = &M;
        ref readonly int local1 = ref C.Field1();
        Console.Write(local1);
        i = 2;
        Console.Write(local1);

        C.Field2 = &M;
        i = 3;
        ref readonly int local2 = ref C.Field2();
        Console.Write(local2);
        i = 4;
        Console.Write(local2);
    }

    static void TestOut()
    {
        C.Field3 = &MOut;
        i = 5;
        C.Field3(out int local);
        Console.Write(local);

        C.Field5 = &MOut;
        i = 6;
        C.Field5(out local);
        Console.Write(local);
    }

    static void TestIn()
    {
        i = 7;
        C.Field4 = &MIn;
        C.Field4(in i);

        i = 8;
        C.Field6 = &MIn;
        C.Field6(in i);
    }
}";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, expectedOutput: "12345678");

            verifier.VerifyIL("D.TestRefReadonly", @"
{
  // Code size       87 (0x57)
  .maxstack  2
  IL_0000:  ldftn      ""ref readonly int D.M()""
469 470 471
  IL_0006:  stsfld     ""delegate*<ref readonly int> C.Field1""
  IL_000b:  ldsfld     ""delegate*<ref readonly int> C.Field1""
  IL_0010:  calli      ""delegate*<ref readonly int>""
F
Fredric Silberberg 已提交
472 473 474 475 476 477 478 479
  IL_0015:  dup
  IL_0016:  ldind.i4
  IL_0017:  call       ""void System.Console.Write(int)""
  IL_001c:  ldc.i4.2
  IL_001d:  stsfld     ""int D.i""
  IL_0022:  ldind.i4
  IL_0023:  call       ""void System.Console.Write(int)""
  IL_0028:  ldftn      ""ref readonly int D.M()""
480
  IL_002e:  stsfld     ""delegate*<ref readonly int> C.Field2""
F
Fredric Silberberg 已提交
481 482
  IL_0033:  ldc.i4.3
  IL_0034:  stsfld     ""int D.i""
483 484
  IL_0039:  ldsfld     ""delegate*<ref readonly int> C.Field2""
  IL_003e:  calli      ""delegate*<ref readonly int>""
F
Fredric Silberberg 已提交
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
  IL_0043:  dup
  IL_0044:  ldind.i4
  IL_0045:  call       ""void System.Console.Write(int)""
  IL_004a:  ldc.i4.4
  IL_004b:  stsfld     ""int D.i""
  IL_0050:  ldind.i4
  IL_0051:  call       ""void System.Console.Write(int)""
  IL_0056:  ret
}
");
            verifier.VerifyIL("D.TestOut", @"
{
  // Code size       75 (0x4b)
  .maxstack  2
  .locals init (int V_0, //local
500 501
                delegate*<out int, void> V_1,
                delegate*<out int, void> V_2)
F
Fredric Silberberg 已提交
502
  IL_0000:  ldftn      ""void D.MOut(out int)""
503
  IL_0006:  stsfld     ""delegate*<out int, void> C.Field3""
F
Fredric Silberberg 已提交
504 505
  IL_000b:  ldc.i4.5
  IL_000c:  stsfld     ""int D.i""
506
  IL_0011:  ldsfld     ""delegate*<out int, void> C.Field3""
F
Fredric Silberberg 已提交
507 508 509
  IL_0016:  stloc.1
  IL_0017:  ldloca.s   V_0
  IL_0019:  ldloc.1
510
  IL_001a:  calli      ""delegate*<out int, void>""
F
Fredric Silberberg 已提交
511 512 513
  IL_001f:  ldloc.0
  IL_0020:  call       ""void System.Console.Write(int)""
  IL_0025:  ldftn      ""void D.MOut(out int)""
514
  IL_002b:  stsfld     ""delegate*<out int, void> C.Field5""
F
Fredric Silberberg 已提交
515 516
  IL_0030:  ldc.i4.6
  IL_0031:  stsfld     ""int D.i""
517
  IL_0036:  ldsfld     ""delegate*<out int, void> C.Field5""
F
Fredric Silberberg 已提交
518 519 520
  IL_003b:  stloc.2
  IL_003c:  ldloca.s   V_0
  IL_003e:  ldloc.2
521
  IL_003f:  calli      ""delegate*<out int, void>""
F
Fredric Silberberg 已提交
522 523 524 525 526 527 528 529 530
  IL_0044:  ldloc.0
  IL_0045:  call       ""void System.Console.Write(int)""
  IL_004a:  ret
}
");
            verifier.VerifyIL("D.TestIn", @"
{
  // Code size       69 (0x45)
  .maxstack  2
531 532
  .locals init (delegate*<in int, void> V_0,
                delegate*<in int, void> V_1)
F
Fredric Silberberg 已提交
533 534 535
  IL_0000:  ldc.i4.7
  IL_0001:  stsfld     ""int D.i""
  IL_0006:  ldftn      ""void D.MIn(in int)""
536 537
  IL_000c:  stsfld     ""delegate*<in int, void> C.Field4""
  IL_0011:  ldsfld     ""delegate*<in int, void> C.Field4""
F
Fredric Silberberg 已提交
538 539 540
  IL_0016:  stloc.0
  IL_0017:  ldsflda    ""int D.i""
  IL_001c:  ldloc.0
541
  IL_001d:  calli      ""delegate*<in int, void>""
F
Fredric Silberberg 已提交
542 543 544
  IL_0022:  ldc.i4.8
  IL_0023:  stsfld     ""int D.i""
  IL_0028:  ldftn      ""void D.MIn(in int)""
545 546
  IL_002e:  stsfld     ""delegate*<in int, void> C.Field6""
  IL_0033:  ldsfld     ""delegate*<in int, void> C.Field6""
F
Fredric Silberberg 已提交
547 548 549
  IL_0038:  stloc.1
  IL_0039:  ldsflda    ""int D.i""
  IL_003e:  ldloc.1
550
  IL_003f:  calli      ""delegate*<in int, void>""
F
Fredric Silberberg 已提交
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
  IL_0044:  ret
}
");

            var c = ((CSharpCompilation)verifier.Compilation).GetTypeByMetadataName("C");
            var field = c.GetField("Field1");
            VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
                (RefKind.RefReadOnly, IsSpecialType(SpecialType.System_Int32)));

            field = c.GetField("Field2");
            VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
                (RefKind.RefReadOnly, IsSpecialType(SpecialType.System_Int32)));

            field = c.GetField("Field3");
            VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
                (RefKind.None, IsVoidType()),
                (RefKind.Out, IsSpecialType(SpecialType.System_Int32)));

            field = c.GetField("Field4");
            VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
                (RefKind.None, IsVoidType()),
                (RefKind.In, IsSpecialType(SpecialType.System_Int32)));

            field = c.GetField("Field5");
            VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
                (RefKind.None, IsVoidType()),
                (RefKind.Out, IsSpecialType(SpecialType.System_Int32)));

            field = c.GetField("Field6");
            VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
                (RefKind.None, IsVoidType()),
                (RefKind.In, IsSpecialType(SpecialType.System_Int32)));
        }

        [Fact]
        public void RefReadonlyIsDoneByRef()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    private static int i = 0;
    static ref readonly int GetI() => ref i;
    static void Main()
    {
        delegate*<ref readonly int> d = &GetI;
        ref readonly int local = ref d();
        Console.Write(local);
        i = 1;
        Console.Write(local);
    }
}
", expectedOutput: "01");

            verifier.VerifyIL("C.Main", @"
{
  // Code size       31 (0x1f)
  .maxstack  2
  IL_0000:  ldftn      ""ref readonly int C.GetI()""
610
  IL_0006:  calli      ""delegate*<ref readonly int>""
F
Fredric Silberberg 已提交
611 612 613 614 615 616 617 618 619 620 621 622
  IL_000b:  dup
  IL_000c:  ldind.i4
  IL_000d:  call       ""void System.Console.Write(int)""
  IL_0012:  ldc.i4.1
  IL_0013:  stsfld     ""int C.i""
  IL_0018:  ldind.i4
  IL_0019:  call       ""void System.Console.Write(int)""
  IL_001e:  ret
}
");
        }

623 624 625
        [Fact]
        public void NestedPointerTypes()
        {
F
Fredric Silberberg 已提交
626
            var verifier = CompileAndVerifyFunctionPointers(@"
627 628
public class C
{
629
    public unsafe delegate* unmanaged[Cdecl]<ref delegate*<ref readonly string>, void> M(delegate*<in delegate* unmanaged[Stdcall]<delegate*<void>>, delegate*<int>> param) => throw null;
630
}", symbolValidator: symbolValidator);
631

F
Fredric Silberberg 已提交
632
            symbolValidator(GetSourceModule(verifier));
F
Fredric Silberberg 已提交
633

634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
            static void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
                var m = c.GetMethod("M");
                var returnType = m.ReturnType;
                var paramType = m.Parameters[0].Type;

                VerifyFunctionPointerSymbol(returnType, CallingConvention.CDecl,
                    (RefKind.None, IsVoidType()),
                    (RefKind.Ref,
                     IsFunctionPointerTypeSymbol(CallingConvention.Default,
                        (RefKind.RefReadOnly, IsSpecialType(SpecialType.System_String)))));

                VerifyFunctionPointerSymbol(paramType, CallingConvention.Default,
                    (RefKind.None,
                     IsFunctionPointerTypeSymbol(CallingConvention.Default,
                        (RefKind.None, IsSpecialType(SpecialType.System_Int32)))),
                    (RefKind.In,
                     IsFunctionPointerTypeSymbol(CallingConvention.Standard,
                        (RefKind.None,
                         IsFunctionPointerTypeSymbol(CallingConvention.Default,
                            (RefKind.None, IsVoidType()))))));
            }
        }

        [Fact]
        public void RandomModOptsFromIl()
        {
            var ilSource = @"
.class public auto ansi beforefieldinit Test1
       extends[mscorlib] System.Object
{
    .method public hidebysig instance void  M(method bool modopt([mscorlib]System.Runtime.InteropServices.OutAttribute)& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modopt([mscorlib]System.Runtime.InteropServices.ComImport) *(int32 modopt([mscorlib]System.Runtime.InteropServices.AllowReversePInvokeCallsAttribute)& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modopt([mscorlib]System.Runtime.InteropServices.PreserveSigAttribute)) param) cil managed
    {
      // Code size       2 (0x2)
      .maxstack  8
      IL_0000:  nop
      IL_0001:  ret
    } // end of method Test::M
}
";

676
            var compilation = CreateCompilationWithIL(source: "", ilSource, parseOptions: TestOptions.Regular9);
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
            var testClass = compilation.GetTypeByMetadataName("Test1")!;

            var m = testClass.GetMethod("M");
            Assert.NotNull(m);
            var param = (FunctionPointerTypeSymbol)m.Parameters[0].Type;
            VerifyFunctionPointerSymbol(param, CallingConvention.Default,
                (RefKind.RefReadOnly, IsSpecialType(SpecialType.System_Boolean)),
                (RefKind.In, IsSpecialType(SpecialType.System_Int32)));

            var returnModifiers = param.Signature.ReturnTypeWithAnnotations.CustomModifiers;
            verifyMod(1, "OutAttribute", returnModifiers);

            var returnRefModifiers = param.Signature.RefCustomModifiers;
            verifyMod(2, "ComImport", returnRefModifiers);

            var paramModifiers = param.Signature.ParameterTypesWithAnnotations[0].CustomModifiers;
            verifyMod(1, "AllowReversePInvokeCallsAttribute", paramModifiers);

            var paramRefModifiers = param.Signature.Parameters[0].RefCustomModifiers;
            verifyMod(2, "PreserveSigAttribute", paramRefModifiers);

            static void verifyMod(int length, string expectedTypeName, ImmutableArray<CustomModifier> customMods)
            {
                Assert.Equal(length, customMods.Length);
                var firstMod = customMods[0];
                Assert.True(firstMod.IsOptional);
                Assert.Equal(expectedTypeName, ((CSharpCustomModifier)firstMod).ModifierSymbol.Name);

                if (length > 1)
                {
                    Assert.Equal(2, customMods.Length);
                    var inMod = customMods[1];
                    Assert.False(inMod.IsOptional);
                    Assert.True(((CSharpCustomModifier)inMod).ModifierSymbol.IsWellKnownTypeInAttribute());
                }
            }
        }

        [Fact]
        public void MultipleFunctionPointerArguments()
        {
F
Fredric Silberberg 已提交
718
            var verifier = CompileAndVerifyFunctionPointers(@"
719
public unsafe class C
720 721 722 723 724 725 726
{
	public void M(delegate*<ref int, ref bool> param1,
                  delegate*<ref int, ref bool> param2,
                  delegate*<ref int, ref bool> param3,
                  delegate*<ref int, ref bool> param4,
                  delegate*<ref int, ref bool> param5) {}
                     
727
}", symbolValidator: symbolValidator);
728

F
Fredric Silberberg 已提交
729
            symbolValidator(GetSourceModule(verifier));
F
Fredric Silberberg 已提交
730

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
            static void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
                var m = c.GetMethod("M");

                foreach (var param in m.Parameters)
                {
                    VerifyFunctionPointerSymbol(param.Type, CallingConvention.Default,
                        (RefKind.Ref, IsSpecialType(SpecialType.System_Boolean)),
                        (RefKind.Ref, IsSpecialType(SpecialType.System_Int32)));
                }
            }
        }

        [Fact]
        public void FunctionPointersInProperties()
        {
F
Fredric Silberberg 已提交
748
            var verifier = CompileAndVerifyFunctionPointers(@"
749
public unsafe class C
750 751
{
    public delegate*<string, void> Prop1 { get; set; }
752
    public delegate* unmanaged[Stdcall]<int> Prop2 { get => throw null; set => throw null; }
F
Fredric Silberberg 已提交
753
}", symbolValidator: symbolValidator);
754

F
Fredric Silberberg 已提交
755
            symbolValidator(GetSourceModule(verifier));
F
Fredric Silberberg 已提交
756 757

            verifier.VerifyIL("C.Prop1.get", expectedIL: @"
758 759 760 761
{
  // Code size        7 (0x7)
  .maxstack  1
  IL_0000:  ldarg.0
762
  IL_0001:  ldfld      ""delegate*<string, void> C.<Prop1>k__BackingField""
763 764 765 766
  IL_0006:  ret
}
");

F
Fredric Silberberg 已提交
767
            verifier.VerifyIL("C.Prop1.set", expectedIL: @"
768 769 770 771 772
{
  // Code size        8 (0x8)
  .maxstack  2
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
773
  IL_0002:  stfld      ""delegate*<string, void> C.<Prop1>k__BackingField""
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
  IL_0007:  ret
}
");

            static void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");

                validateProperty((PropertySymbol)c.GetProperty((string)"Prop1"), IsFunctionPointerTypeSymbol(CallingConvention.Default,
                    (RefKind.None, IsVoidType()),
                    (RefKind.None, IsSpecialType(SpecialType.System_String))));

                validateProperty(c.GetProperty("Prop2"), IsFunctionPointerTypeSymbol(CallingConvention.Standard,
                    (RefKind.None, IsSpecialType(SpecialType.System_Int32))));

                static void validateProperty(PropertySymbol property, Action<TypeSymbol> verifier)
                {
                    verifier(property.Type);
                    verifier(property.GetMethod.ReturnType);
                    verifier(property.SetMethod.GetParameterType(0));
                }
            }
        }

        [Fact]
        public void FunctionPointersInFields()
        {
F
Fredric Silberberg 已提交
801
            var verifier = CompileAndVerifyFunctionPointers(@"
802
public unsafe class C
803 804
{
    public readonly delegate*<C, C> _field;
805
}", symbolValidator: symbolValidator);
806

F
Fredric Silberberg 已提交
807
            symbolValidator(GetSourceModule(verifier));
F
Fredric Silberberg 已提交
808

809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
            static void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
                VerifyFunctionPointerSymbol(c.GetField("_field").Type, CallingConvention.Default,
                    (RefKind.None, IsTypeName("C")),
                    (RefKind.None, IsTypeName("C")));
            }
        }

        [Fact]
        public void CustomModifierOnReturnType()
        {
            var ilSource = @"
.class public auto ansi beforefieldinit C
       extends[mscorlib] System.Object
{
    .method public hidebysig newslot virtual instance method bool modopt([mscorlib]System.Object)& *(int32&)  M() cil managed
    {
      // Code size       2 (0x2)
      .maxstack  8
      IL_0000:  nop
      IL_0001:  ret
    } // end of method C::M

    .method public hidebysig specialname rtspecialname 
            instance void  .ctor() cil managed
    {
      // Code size       8 (0x8)
      .maxstack  8
      IL_0000:  ldarg.0
      IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
      IL_0006:  nop
      IL_0007:  ret
    } // end of method C::.ctor
}
";

            var source = @"
class D : C
{
849
    public unsafe override delegate*<ref int, ref bool> M() => throw null;
850 851
}";

F
Fredric Silberberg 已提交
852 853
            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub: ilSource, symbolValidator: symbolValidator);

F
Fredric Silberberg 已提交
854
            symbolValidator(GetSourceModule(verifier));
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873

            static void symbolValidator(ModuleSymbol module)
            {
                var d = module.GlobalNamespace.GetMember<NamedTypeSymbol>("D");
                var m = d.GetMethod("M");

                var returnTypeWithAnnotations = ((FunctionPointerTypeSymbol)m.ReturnType).Signature.ReturnTypeWithAnnotations;
                Assert.Equal(1, returnTypeWithAnnotations.CustomModifiers.Length);
                Assert.Equal(SpecialType.System_Object, returnTypeWithAnnotations.CustomModifiers[0].Modifier.SpecialType);
            }
        }

        [Fact]
        public void UnsupportedCallingConventionInMetadata()
        {
            var ilSource = @"
.class public auto ansi beforefieldinit C
       extends [mscorlib]System.Object
{
F
Fredric Silberberg 已提交
874
    .field public method vararg void*() 'Field'
875
    .field private method vararg void *() '<Prop>k__BackingField'
876 877 878 879 880 881 882 883 884 885 886 887 888 889
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) 
    .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) 
    
    .method public hidebysig specialname rtspecialname 
            instance void  .ctor() cil managed
    {
      // Code size       8 (0x8)
      .maxstack  8
      IL_0000:  ldarg.0
      IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
      IL_0006:  nop
      IL_0007:  ret
    } // end of method C::.ctor
    
890
    .method public hidebysig specialname instance method vararg void *() 
891 892 893 894 895 896
            get_Prop() cil managed
    {
      .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) 
      // Code size       7 (0x7)
      .maxstack  8
      IL_0000:  ldarg.0
897
      IL_0001:  ldfld      method vararg void *() C::'<Prop>k__BackingField'
898 899 900 901
      IL_0006:  ret
    } // end of method C::get_Prop
    
    .method public hidebysig specialname instance void 
902
            set_Prop(method  vararg void *() 'value') cil managed
903 904 905 906 907 908
    {
      .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) 
      // Code size       8 (0x8)
      .maxstack  8
      IL_0000:  ldarg.0
      IL_0001:  ldarg.1
909
      IL_0002:  stfld      method vararg void *() C::'<Prop>k__BackingField'
910 911 912
      IL_0007:  ret
    } // end of method C::set_Prop
    
913
    .property instance method vararg void *()
914 915
            Prop()
    {
916 917
      .get instance method vararg void *() C::get_Prop()
      .set instance void C::set_Prop(method vararg void *())
918 919 920 921
    } // end of property C::Prop
} // end of class C
";

F
Fredric Silberberg 已提交
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
            var source = @"
unsafe class D
{
    void M(C c)
    {
        c.Field(__arglist(1, 2));
        c.Field(1, 2, 3);
        c.Field();
        c.Field = c.Field;
        c.Prop();
        c.Prop = c.Prop;
    }
}
";

            var comp = CreateCompilationWithFunctionPointersAndIl(source, ilSource);
            comp.VerifyDiagnostics(
939
                // (6,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
F
Fredric Silberberg 已提交
940
                //         c.Field(__arglist(1, 2));
941 942
                Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(6, 11),
                // (7,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
F
Fredric Silberberg 已提交
943
                //         c.Field(1, 2, 3);
944 945
                Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(7, 11),
                // (8,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
F
Fredric Silberberg 已提交
946
                //         c.Field();
947 948
                Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(8, 11),
                // (9,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
F
Fredric Silberberg 已提交
949
                //         c.Field = c.Field;
950 951
                Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(9, 11),
                // (9,21): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
F
Fredric Silberberg 已提交
952
                //         c.Field = c.Field;
953 954
                Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(9, 21),
                // (10,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
F
Fredric Silberberg 已提交
955
                //         c.Prop();
956 957
                Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Prop").WithArguments("delegate* unmanaged[]<void>").WithLocation(10, 11),
                // (11,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
F
Fredric Silberberg 已提交
958
                //         c.Prop = c.Prop;
959 960
                Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Prop").WithArguments("delegate* unmanaged[]<void>").WithLocation(11, 11),
                // (11,20): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
F
Fredric Silberberg 已提交
961
                //         c.Prop = c.Prop;
962
                Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Prop").WithArguments("delegate* unmanaged[]<void>").WithLocation(11, 20)
F
Fredric Silberberg 已提交
963
            );
964 965 966 967

            var c = comp.GetTypeByMetadataName("C");
            var prop = c.GetProperty("Prop");

968
            VerifyFunctionPointerSymbol(prop.Type, CallingConvention.ExtraArguments,
969
                (RefKind.None, IsVoidType()));
F
Fredric Silberberg 已提交
970 971 972 973 974

            Assert.True(prop.Type.HasUseSiteError);

            var field = c.GetField("Field");

F
Fredric Silberberg 已提交
975 976
            var type = (FunctionPointerTypeSymbol)field.Type;
            VerifyFunctionPointerSymbol(type, CallingConvention.ExtraArguments,
F
Fredric Silberberg 已提交
977 978
                (RefKind.None, IsVoidType()));

F
Fredric Silberberg 已提交
979 980
            Assert.True(type.HasUseSiteError);
            Assert.True(type.Signature.IsVararg);
981 982
        }

983 984 985 986 987 988 989 990
        [Fact]
        public void StructWithFunctionPointerThatReferencesStruct()
        {
            CompileAndVerifyFunctionPointers(@"
unsafe struct S
{
    public delegate*<S, S> Field;
    public delegate*<S, S> Property { get; set; }
F
Fredric Silberberg 已提交
991
}");
992 993
        }

994 995 996 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 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        [Fact]
        public void CalliOnParameter()
        {
            var ilStub = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static 
        method void *() LoadPtr () cil managed 
    {
        nop
        ldftn void Program::Called()
        ret
    } // end of method Program::Main

    .method private hidebysig static 
        void Called () cil managed 
    {
        nop
        ldstr ""Called""
        call void [mscorlib]System.Console::WriteLine(string)
        nop
        ret
    } // end of Program::Called

    .method public hidebysig specialname rtspecialname
        instance void .ctor() cil managed
    {
            ldarg.0
            call instance void[mscorlib] System.Object::.ctor()
            nop
            ret
    } // end of Program::.ctor
}
";

            var source = @"
class Caller
{
    public unsafe static void Main()
    {
        Call(Program.LoadPtr());
    }

    public unsafe static void Call(delegate*<void> ptr)
    {
        ptr();
    }
}";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: "Called");
            verifier.VerifyIL("Caller.Call(delegate*<void>)", @"
{
  // Code size        7 (0x7)
  .maxstack  1
  IL_0000:  ldarg.0
F
Fredric Silberberg 已提交
1051
  IL_0001:  calli      ""delegate*<void>""
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
  IL_0006:  ret
}");
        }

        [Fact]
        public void CalliOnFieldNoArgs()
        {
            var ilStub = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static 
        method void *() LoadPtr () cil managed 
    {
        nop
        ldftn void Program::Called()
        ret
    } // end of method Program::Main

    .method private hidebysig static 
        void Called () cil managed 
    {
        nop
        ldstr ""Called""
        call void [mscorlib]System.Console::WriteLine(string)
        nop
        ret
    } // end of Program::Called

    .method public hidebysig specialname rtspecialname
        instance void .ctor() cil managed
    {
            ldarg.0
            call instance void[mscorlib] System.Object::.ctor()
            nop
            ret
    } // end of Program::.ctor
}
";

            var source = @"
unsafe class Caller
{
    static delegate*<void> _field;

    public unsafe static void Main()
    {
        _field = Program.LoadPtr();
        Call();
    }

    public unsafe static void Call()
    {
        _field();
    }
}";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: "Called");
            verifier.VerifyIL("Caller.Call()", @"
{
  // Code size       11 (0xb)
  .maxstack  1
  IL_0000:  ldsfld     ""delegate*<void> Caller._field""
F
Fredric Silberberg 已提交
1116
  IL_0005:  calli      ""delegate*<void>""
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
  IL_000a:  ret
}");
        }

        [Fact]
        public void CalliOnFieldArgs()
        {
            var ilStub = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static 
        method void *(string) LoadPtr () cil managed 
    {
        nop
        ldftn void Program::Called(string)
        ret
    } // end of method Program::Main

    .method private hidebysig static 
        void Called (string arg) cil managed 
    {
        nop
        ldarg.0
        call void [mscorlib]System.Console::WriteLine(string)
        nop
        ret
    } // end of Program::Called

    .method public hidebysig specialname rtspecialname
        instance void .ctor() cil managed
    {
            ldarg.0
            call instance void[mscorlib] System.Object::.ctor()
            nop
            ret
    } // end of Program::.ctor
}
";

            var source = @"
unsafe class Caller
{
    static delegate*<string, void> _field;

    public unsafe static void Main()
    {
        _field = Program.LoadPtr();
        Call();
    }

    public unsafe static void Call()
    {
        _field(""Called"");
    }
}";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: "Called");
            verifier.VerifyIL("Caller.Call()", @"
{
  // Code size       18 (0x12)
  .maxstack  2
1180 1181
  .locals init (delegate*<string, void> V_0)
  IL_0000:  ldsfld     ""delegate*<string, void> Caller._field""
1182 1183 1184
  IL_0005:  stloc.0
  IL_0006:  ldstr      ""Called""
  IL_000b:  ldloc.0
1185
  IL_000c:  calli      ""delegate*<string, void>""
1186 1187 1188 1189
  IL_0011:  ret
}");
        }

F
Fredric Silberberg 已提交
1190
        [Theory]
1191 1192 1193
        [InlineData("Cdecl", "Cdecl")]
        [InlineData("Stdcall", "StdCall")]
        public void UnmanagedCallingConventions(string unmanagedConvention, string enumConvention)
1194
        {
C
Charles Stoner 已提交
1195
            // Use IntPtr Marshal.GetFunctionPointerForDelegate<TDelegate>(TDelegate delegate) to
F
Fredric Silberberg 已提交
1196
            // get a function pointer around a native calling convention
1197 1198 1199 1200
            var source = $@" 
using System;
using System.Runtime.InteropServices;
public unsafe class UnmanagedFunctionPointer 
1201
{{
1202 1203 1204 1205
    [UnmanagedFunctionPointer(CallingConvention.{enumConvention})]
    private delegate string CombineStrings(string s1, string s2);
    
    private static string CombineStringsImpl(string s1, string s2)
1206
    {{
1207 1208
        return s1 + s2;
    }}
1209

1210
    public static delegate* unmanaged[{unmanagedConvention}]<string, string, string> GetFuncPtr()
1211
    {{
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
        var ptr = Marshal.GetFunctionPointerForDelegate((CombineStrings)CombineStringsImpl);
        GC.KeepAlive(ptr);
        return (delegate* unmanaged[{unmanagedConvention}]<string, string, string>)ptr;
    }}
}}
class Caller
{{
    public unsafe static void Main()
    {{
        Call(UnmanagedFunctionPointer.GetFuncPtr());
    }}
1223

1224
    public unsafe static void Call(delegate* unmanaged[{unmanagedConvention}]<string, string, string> ptr)
1225
    {{
1226 1227 1228
        Console.WriteLine(ptr(""Hello"", "" World""));
    }}
}}";
F
Fredric Silberberg 已提交
1229

1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
            var verifier = CompileAndVerifyFunctionPointers(source, expectedOutput: "Hello World");
            verifier.VerifyIL($"Caller.Call", $@"
{{
  // Code size       24 (0x18)
  .maxstack  3
  .locals init (delegate* unmanaged[{unmanagedConvention}]<string, string, string> V_0)
  IL_0000:  ldarg.0
  IL_0001:  stloc.0
  IL_0002:  ldstr      ""Hello""
  IL_0007:  ldstr      "" World""
  IL_000c:  ldloc.0
  IL_000d:  calli      ""delegate* unmanaged[{unmanagedConvention}]<string, string, string>""
  IL_0012:  call       ""void System.Console.WriteLine(string)""
  IL_0017:  ret
}}");
        }
1246

F
Fredric Silberberg 已提交
1247
        [Fact]
1248 1249 1250 1251
        public void FastCall()
        {
            // Use IntPtr Marshal.GetFunctionPointerForDelegate<TDelegate>(TDelegate delegate) to
            // get a function pointer around a native calling convention
F
Fredric Silberberg 已提交
1252
            var source = @" 
F
Fredric Silberberg 已提交
1253
using System;
1254 1255
using System.Runtime.InteropServices;
public unsafe class UnmanagedFunctionPointer 
F
Fredric Silberberg 已提交
1256
{
1257 1258 1259 1260
    [UnmanagedFunctionPointer(CallingConvention.FastCall)]
    private delegate string CombineStrings(string s1, string s2);
    
    private static string CombineStringsImpl(string s1, string s2)
F
Fredric Silberberg 已提交
1261
    {
1262
        return s1 + s2;
F
Fredric Silberberg 已提交
1263
    }
1264 1265

    public static delegate* unmanaged[Fastcall]<string, string, string> GetFuncPtr()
F
Fredric Silberberg 已提交
1266
    {
1267 1268 1269
        var ptr = Marshal.GetFunctionPointerForDelegate((CombineStrings)CombineStringsImpl);
        GC.KeepAlive(ptr);
        return (delegate* unmanaged[Fastcall]<string, string, string>)ptr;
F
Fredric Silberberg 已提交
1270 1271
    }
}
1272
class Caller
F
Fredric Silberberg 已提交
1273
{
1274
    public unsafe static void Main()
F
Fredric Silberberg 已提交
1275
    {
F
Fredric Silberberg 已提交
1276
        Call(UnmanagedFunctionPointer.GetFuncPtr());
F
Fredric Silberberg 已提交
1277
    }
1278

1279
    public unsafe static void Call(delegate* unmanaged[Fastcall]<string, string, string> ptr)
F
Fredric Silberberg 已提交
1280
    {
F
Fredric Silberberg 已提交
1281
        Console.WriteLine(ptr(""Hello"", "" World""));
F
Fredric Silberberg 已提交
1282 1283
    }
}";
1284

F
Fredric Silberberg 已提交
1285 1286 1287
            // Fastcall is only supported by Mono on Windows x86, which we do not have a test leg for.
            // Therefore, we just verify that the emitted IL is what we expect.
            var verifier = CompileAndVerifyFunctionPointers(source);
1288
            verifier.VerifyIL($"Caller.Call(delegate* unmanaged[Fastcall]<string, string, string>)", @"
1289
{
F
Fredric Silberberg 已提交
1290 1291
  // Code size       24 (0x18)
  .maxstack  3
1292
  .locals init (delegate* unmanaged[Fastcall]<string, string, string> V_0)
1293
  IL_0000:  ldarg.0
F
Fredric Silberberg 已提交
1294 1295 1296 1297
  IL_0001:  stloc.0
  IL_0002:  ldstr      ""Hello""
  IL_0007:  ldstr      "" World""
  IL_000c:  ldloc.0
1298
  IL_000d:  calli      ""delegate* unmanaged[Fastcall]<string, string, string>""
F
Fredric Silberberg 已提交
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 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
  IL_0012:  call       ""void System.Console.WriteLine(string)""
  IL_0017:  ret
}");
        }

        [Fact]
        public void ThiscallSimpleReturn()
        {
            var ilSource = @"
.class private auto ansi '<Module>'
{
} // end of class <Module>

.class public sequential ansi sealed beforefieldinit S
    extends [mscorlib]System.ValueType
{
    // Fields
    .field public int32 i

    // Methods
    .method public hidebysig static 
        int32 GetInt (
            valuetype S* s
        ) cil managed 
    {
        // Method begins at RVA 0x2050
        // Code size 12 (0xc)
        .maxstack 1
        .locals init (
            [0] int32
        )

        nop
        ldarg.0
        ldfld int32 S::i
        ret
    } // end of method S::GetInt

    .method public hidebysig static 
        int32 GetReturn (
            valuetype S* s,
            int32 i
        ) cil managed 
    {
        // Method begins at RVA 0x2068
        // Code size 14 (0xe)
        .maxstack 2
        .locals init (
            [0] int32
        )

        nop
        ldarg.0
        ldfld int32 S::i
        ldarg.1
        add
        ret
    } // end of method S::GetReturn

} // end of class S

.class public auto ansi beforefieldinit UnmanagedFunctionPointer
    extends [mscorlib]System.Object
{
    // Nested Types
    .class nested private auto ansi sealed SingleParam
        extends [mscorlib]System.MulticastDelegate
    {
        .custom instance void [mscorlib]System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute::.ctor(valuetype [mscorlib]System.Runtime.InteropServices.CallingConvention) = (
            01 00 04 00 00 00 00 00
        )
        // Methods
        .method public hidebysig specialname rtspecialname 
            instance void .ctor (
                object 'object',
                native int 'method'
            ) runtime managed 
        {
        } // end of method SingleParam::.ctor

        .method public hidebysig newslot virtual 
            instance int32 Invoke (
                valuetype S* s
            ) runtime managed 
        {
        } // end of method SingleParam::Invoke

        .method public hidebysig newslot virtual 
            instance class [mscorlib]System.IAsyncResult BeginInvoke (
                valuetype S* s,
                class [mscorlib]System.AsyncCallback callback,
                object 'object'
            ) runtime managed 
        {
        } // end of method SingleParam::BeginInvoke

        .method public hidebysig newslot virtual 
            instance int32 EndInvoke (
                class [mscorlib]System.IAsyncResult result
            ) runtime managed 
        {
        } // end of method SingleParam::EndInvoke

    } // end of class SingleParam

    .class nested private auto ansi sealed MultipleParams
        extends [mscorlib]System.MulticastDelegate
    {
        .custom instance void [mscorlib]System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute::.ctor(valuetype [mscorlib]System.Runtime.InteropServices.CallingConvention) = (
            01 00 04 00 00 00 00 00
        )
        // Methods
        .method public hidebysig specialname rtspecialname 
            instance void .ctor (
                object 'object',
                native int 'method'
            ) runtime managed 
        {
        } // end of method MultipleParams::.ctor

        .method public hidebysig newslot virtual 
            instance int32 Invoke (
                valuetype S* s,
                int32 i
            ) runtime managed 
        {
        } // end of method MultipleParams::Invoke

        .method public hidebysig newslot virtual 
            instance class [mscorlib]System.IAsyncResult BeginInvoke (
                valuetype S* s,
                int32 i,
                class [mscorlib]System.AsyncCallback callback,
                object 'object'
            ) runtime managed 
        {
        } // end of method MultipleParams::BeginInvoke

        .method public hidebysig newslot virtual 
            instance int32 EndInvoke (
                class [mscorlib]System.IAsyncResult result
            ) runtime managed 
        {
        } // end of method MultipleParams::EndInvoke

    } // end of class MultipleParams


    // Methods
    .method public hidebysig static 
        method unmanaged thiscall int32 *(valuetype S*) GetFuncPtrSingleParam () cil managed 
    {
        // Method begins at RVA 0x2084
        // Code size 37 (0x25)
        .maxstack 2
        .locals init (
            [0] native int,
            [1] native int
        )

        nop
        ldnull
        ldftn int32 S::GetInt(valuetype S*)
        newobj instance void UnmanagedFunctionPointer/SingleParam::.ctor(object, native int)
        call native int [mscorlib]System.Runtime.InteropServices.Marshal::GetFunctionPointerForDelegate<class UnmanagedFunctionPointer/SingleParam>(!!0)
        stloc.0
        ldloc.0
        box [mscorlib]System.IntPtr
        call void [mscorlib]System.GC::KeepAlive(object)
        ldloc.0
        ret
    } // end of method UnmanagedFunctionPointer::GetFuncPtrSingleParam

    .method public hidebysig static 
        method unmanaged thiscall int32 *(valuetype S*, int32) GetFuncPtrMultipleParams () cil managed 
    {
        // Method begins at RVA 0x20b8
        // Code size 37 (0x25)
        .maxstack 2
        .locals init (
            [0] native int,
            [1] native int
        )

        nop
        ldnull
        ldftn int32 S::GetReturn(valuetype S*, int32)
        newobj instance void UnmanagedFunctionPointer/MultipleParams::.ctor(object, native int)
        call native int [mscorlib]System.Runtime.InteropServices.Marshal::GetFunctionPointerForDelegate<class UnmanagedFunctionPointer/MultipleParams>(!!0)
        stloc.0
        ldloc.0
        box [mscorlib]System.IntPtr
        call void [mscorlib]System.GC::KeepAlive(object)
        ldloc.0
        ret
    } // end of method UnmanagedFunctionPointer::GetFuncPtrMultipleParams
} // end of class UnmanagedFunctionPointer
";

            var verifier = CompileAndVerifyFunctionPointersWithIl(@"
using System;
unsafe class C
{
    public static void Main()
    {
        TestSingle();
        TestMultiple();
    }

    public static void TestSingle()
    {
        S s = new S();
        s.i = 1;
        var i = UnmanagedFunctionPointer.GetFuncPtrSingleParam()(&s);
        Console.Write(i);
    }

    public static void TestMultiple()
    {
        S s = new S();
        s.i = 2;
        var i = UnmanagedFunctionPointer.GetFuncPtrMultipleParams()(&s, 3);
        Console.Write(i);
    }
}", ilSource, expectedOutput: @"15");

            verifier.VerifyIL("C.TestSingle()", @"
{
  // Code size       37 (0x25)
  .maxstack  2
  .locals init (S V_0, //s
1530
                delegate* unmanaged[Thiscall]<S*, int> V_1)
F
Fredric Silberberg 已提交
1531 1532 1533 1534 1535
  IL_0000:  ldloca.s   V_0
  IL_0002:  initobj    ""S""
  IL_0008:  ldloca.s   V_0
  IL_000a:  ldc.i4.1
  IL_000b:  stfld      ""int S.i""
1536
  IL_0010:  call       ""delegate* unmanaged[Thiscall]<S*, int> UnmanagedFunctionPointer.GetFuncPtrSingleParam()""
F
Fredric Silberberg 已提交
1537 1538 1539 1540
  IL_0015:  stloc.1
  IL_0016:  ldloca.s   V_0
  IL_0018:  conv.u
  IL_0019:  ldloc.1
1541
  IL_001a:  calli      ""delegate* unmanaged[Thiscall]<S*, int>""
F
Fredric Silberberg 已提交
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
  IL_001f:  call       ""void System.Console.Write(int)""
  IL_0024:  ret
}
");

            verifier.VerifyIL("C.TestMultiple()", @"
{
  // Code size       38 (0x26)
  .maxstack  3
  .locals init (S V_0, //s
1552
                delegate* unmanaged[Thiscall]<S*, int, int> V_1)
F
Fredric Silberberg 已提交
1553 1554 1555 1556 1557
  IL_0000:  ldloca.s   V_0
  IL_0002:  initobj    ""S""
  IL_0008:  ldloca.s   V_0
  IL_000a:  ldc.i4.2
  IL_000b:  stfld      ""int S.i""
1558
  IL_0010:  call       ""delegate* unmanaged[Thiscall]<S*, int, int> UnmanagedFunctionPointer.GetFuncPtrMultipleParams()""
F
Fredric Silberberg 已提交
1559 1560 1561 1562 1563
  IL_0015:  stloc.1
  IL_0016:  ldloca.s   V_0
  IL_0018:  conv.u
  IL_0019:  ldc.i4.3
  IL_001a:  ldloc.1
1564
  IL_001b:  calli      ""delegate* unmanaged[Thiscall]<S*, int, int>""
F
Fredric Silberberg 已提交
1565 1566 1567 1568 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 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 1806 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 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
  IL_0020:  call       ""void System.Console.Write(int)""
  IL_0025:  ret
}
");
        }

        // Fails on .net core due to https://github.com/dotnet/runtime/issues/33129
        [ConditionalFact(typeof(DesktopOnly))]
        public void ThiscallBlittable()
        {
            var ilSource = @"
.class public sequential ansi sealed beforefieldinit IntWrapper
    extends [mscorlib]System.ValueType
{
    // Fields
    .field public int32 i

    // Methods
    .method public hidebysig specialname rtspecialname 
        instance void .ctor (
            int32 i
        ) cil managed 
    {
        // Method begins at RVA 0x2050
        // Code size 9 (0x9)
        .maxstack 8

        nop
        ldarg.0
        ldarg.1
        stfld int32 IntWrapper::i
        ret
    } // end of method IntWrapper::.ctor

} // end of class IntWrapper

.class public sequential ansi sealed beforefieldinit ReturnWrapper
    extends [mscorlib]System.ValueType
{
    // Fields
    .field public int32 i1
    .field public float32 f2

    // Methods
    .method public hidebysig specialname rtspecialname 
        instance void .ctor (
            int32 i1,
            float32 f2
        ) cil managed 
    {
        // Method begins at RVA 0x205a
        // Code size 16 (0x10)
        .maxstack 8

        nop
        ldarg.0
        ldarg.1
        stfld int32 ReturnWrapper::i1
        ldarg.0
        ldarg.2
        stfld float32 ReturnWrapper::f2
        ret
    } // end of method ReturnWrapper::.ctor

} // end of class ReturnWrapper

.class public sequential ansi sealed beforefieldinit S
    extends [mscorlib]System.ValueType
{
    // Fields
    .field public int32 i

    // Methods
    .method public hidebysig static 
        valuetype IntWrapper GetInt (
            valuetype S* s
        ) cil managed 
    {
        // Method begins at RVA 0x206c
        // Code size 17 (0x11)
        .maxstack 1
        .locals init (
            [0] valuetype IntWrapper
        )

        nop
        ldarg.0
        ldfld int32 S::i
        newobj instance void IntWrapper::.ctor(int32)
        ret
    } // end of method S::GetInt

    .method public hidebysig static 
        valuetype ReturnWrapper GetReturn (
            valuetype S* s,
            float32 f
        ) cil managed 
    {
        // Method begins at RVA 0x208c
        // Code size 18 (0x12)
        .maxstack 2
        .locals init (
            [0] valuetype ReturnWrapper
        )

        nop
        ldarg.0
        ldfld int32 S::i
        ldarg.1
        newobj instance void ReturnWrapper::.ctor(int32, float32)
        ret
    } // end of method S::GetReturn

} // end of class S

.class public auto ansi beforefieldinit UnmanagedFunctionPointer
    extends [mscorlib]System.Object
{
    // Nested Types
    .class nested private auto ansi sealed SingleParam
        extends [mscorlib]System.MulticastDelegate
    {
        .custom instance void [mscorlib]System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute::.ctor(valuetype [mscorlib]System.Runtime.InteropServices.CallingConvention) = (
            01 00 04 00 00 00 00 00
        )
        // Methods
        .method public hidebysig specialname rtspecialname 
            instance void .ctor (
                object 'object',
                native int 'method'
            ) runtime managed 
        {
        } // end of method SingleParam::.ctor

        .method public hidebysig newslot virtual 
            instance valuetype IntWrapper Invoke (
                valuetype S* s
            ) runtime managed 
        {
        } // end of method SingleParam::Invoke

        .method public hidebysig newslot virtual 
            instance class [mscorlib]System.IAsyncResult BeginInvoke (
                valuetype S* s,
                class [mscorlib]System.AsyncCallback callback,
                object 'object'
            ) runtime managed 
        {
        } // end of method SingleParam::BeginInvoke

        .method public hidebysig newslot virtual 
            instance valuetype IntWrapper EndInvoke (
                class [mscorlib]System.IAsyncResult result
            ) runtime managed 
        {
        } // end of method SingleParam::EndInvoke

    } // end of class SingleParam

    .class nested private auto ansi sealed MultipleParams
        extends [mscorlib]System.MulticastDelegate
    {
        .custom instance void [mscorlib]System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute::.ctor(valuetype [mscorlib]System.Runtime.InteropServices.CallingConvention) = (
            01 00 04 00 00 00 00 00
        )
        // Methods
        .method public hidebysig specialname rtspecialname 
            instance void .ctor (
                object 'object',
                native int 'method'
            ) runtime managed 
        {
        } // end of method MultipleParams::.ctor

        .method public hidebysig newslot virtual 
            instance valuetype ReturnWrapper Invoke (
                valuetype S* s,
                float32 f
            ) runtime managed 
        {
        } // end of method MultipleParams::Invoke

        .method public hidebysig newslot virtual 
            instance class [mscorlib]System.IAsyncResult BeginInvoke (
                valuetype S* s,
                float32 f,
                class [mscorlib]System.AsyncCallback callback,
                object 'object'
            ) runtime managed 
        {
        } // end of method MultipleParams::BeginInvoke

        .method public hidebysig newslot virtual 
            instance valuetype ReturnWrapper EndInvoke (
                class [mscorlib]System.IAsyncResult result
            ) runtime managed 
        {
        } // end of method MultipleParams::EndInvoke

    } // end of class MultipleParams


    // Methods
    .method public hidebysig static 
        method unmanaged thiscall valuetype IntWrapper *(valuetype S*) GetFuncPtrSingleParam () cil managed 
    {
        // Method begins at RVA 0x20ac
        // Code size 37 (0x25)
        .maxstack 2
        .locals init (
            [0] native int,
            [1] native int
        )

        nop
        ldnull
        ldftn valuetype IntWrapper S::GetInt(valuetype S*)
        newobj instance void UnmanagedFunctionPointer/SingleParam::.ctor(object, native int)
        call native int [mscorlib]System.Runtime.InteropServices.Marshal::GetFunctionPointerForDelegate<class UnmanagedFunctionPointer/SingleParam>(!!0)
        stloc.0
        ldloc.0
        box [mscorlib]System.IntPtr
        call void [mscorlib]System.GC::KeepAlive(object)
        ldloc.0
        ret
    } // end of method UnmanagedFunctionPointer::GetFuncPtrSingleParam

    .method public hidebysig static 
        method unmanaged thiscall valuetype ReturnWrapper *(valuetype S*, float32) GetFuncPtrMultipleParams () cil managed 
    {
        // Method begins at RVA 0x20e0
        // Code size 37 (0x25)
        .maxstack 2
        .locals init (
            [0] native int,
            [1] native int
        )

        nop
        ldnull
        ldftn valuetype ReturnWrapper S::GetReturn(valuetype S*, float32)
        newobj instance void UnmanagedFunctionPointer/MultipleParams::.ctor(object, native int)
        call native int [mscorlib]System.Runtime.InteropServices.Marshal::GetFunctionPointerForDelegate<class UnmanagedFunctionPointer/MultipleParams>(!!0)
        stloc.0
        ldloc.0
        box [mscorlib]System.IntPtr
        call void [mscorlib]System.GC::KeepAlive(object)
        ldloc.0
        ret
    } // end of method UnmanagedFunctionPointer::GetFuncPtrMultipleParams
} // end of class UnmanagedFunctionPointer
";

            var verifier = CompileAndVerifyFunctionPointersWithIl(@"
using System;
unsafe class C
{
    public static void Main()
    {
        TestSingle();
        TestMultiple();
    }

    public static void TestSingle()
    {
        S s = new S();
        s.i = 1;
        var intWrapper = UnmanagedFunctionPointer.GetFuncPtrSingleParam()(&s);
        Console.WriteLine(intWrapper.i);
    }

    public static void TestMultiple()
    {
        S s = new S();
        s.i = 2;
        var returnWrapper = UnmanagedFunctionPointer.GetFuncPtrMultipleParams()(&s, 3.5f);
        Console.Write(returnWrapper.i1);
        Console.Write(returnWrapper.f2);
    }
}", ilSource, expectedOutput: @"
1
23.5
");

            verifier.VerifyIL("C.TestSingle()", @"
{
  // Code size       42 (0x2a)
  .maxstack  2
  .locals init (S V_0, //s
F
Fredric Silberberg 已提交
1854
                delegate* unmanaged[Thiscall]<S*, IntWrapper> V_1)
F
Fredric Silberberg 已提交
1855 1856 1857 1858 1859
  IL_0000:  ldloca.s   V_0
  IL_0002:  initobj    ""S""
  IL_0008:  ldloca.s   V_0
  IL_000a:  ldc.i4.1
  IL_000b:  stfld      ""int S.i""
F
Fredric Silberberg 已提交
1860
  IL_0010:  call       ""delegate* unmanaged[Thiscall]<S*, IntWrapper> UnmanagedFunctionPointer.GetFuncPtrSingleParam()""
F
Fredric Silberberg 已提交
1861 1862 1863 1864
  IL_0015:  stloc.1
  IL_0016:  ldloca.s   V_0
  IL_0018:  conv.u
  IL_0019:  ldloc.1
F
Fredric Silberberg 已提交
1865
  IL_001a:  calli      ""delegate* unmanaged[Thiscall]<S*, IntWrapper>""
F
Fredric Silberberg 已提交
1866 1867 1868
  IL_001f:  ldfld      ""int IntWrapper.i""
  IL_0024:  call       ""void System.Console.WriteLine(int)""
  IL_0029:  ret
F
Fredric Silberberg 已提交
1869 1870
}
");
F
Fredric Silberberg 已提交
1871 1872 1873 1874 1875 1876

            verifier.VerifyIL("C.TestMultiple()", @"
{
  // Code size       58 (0x3a)
  .maxstack  3
  .locals init (S V_0, //s
F
Fredric Silberberg 已提交
1877
                delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper> V_1)
F
Fredric Silberberg 已提交
1878 1879 1880 1881 1882
  IL_0000:  ldloca.s   V_0
  IL_0002:  initobj    ""S""
  IL_0008:  ldloca.s   V_0
  IL_000a:  ldc.i4.2
  IL_000b:  stfld      ""int S.i""
F
Fredric Silberberg 已提交
1883
  IL_0010:  call       ""delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper> UnmanagedFunctionPointer.GetFuncPtrMultipleParams()""
F
Fredric Silberberg 已提交
1884 1885 1886 1887 1888
  IL_0015:  stloc.1
  IL_0016:  ldloca.s   V_0
  IL_0018:  conv.u
  IL_0019:  ldc.r4     3.5
  IL_001e:  ldloc.1
F
Fredric Silberberg 已提交
1889
  IL_001f:  calli      ""delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper>""
F
Fredric Silberberg 已提交
1890 1891 1892 1893 1894 1895
  IL_0024:  dup
  IL_0025:  ldfld      ""int ReturnWrapper.i1""
  IL_002a:  call       ""void System.Console.Write(int)""
  IL_002f:  ldfld      ""float ReturnWrapper.f2""
  IL_0034:  call       ""void System.Console.Write(float)""
  IL_0039:  ret
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
}");
        }

        [Fact]
        public void InvocationOrder()
        {
            var ilStub = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static 
        method void *(string, string) LoadPtr () cil managed 
    {
        nop
        ldftn void Program::Called(string, string)
        ret
    } // end of method Program::Main

    .method private hidebysig static 
        void Called (
            string arg1,
            string arg2) cil managed 
    {
        nop
        ldarg.0
        ldarg.1
        call string [mscorlib]System.String::Concat(string, string)
        call void [mscorlib]System.Console::WriteLine(string)
        nop
        ret
    } // end of Program::Called

    .method public hidebysig specialname rtspecialname
        instance void .ctor() cil managed
    {
        ldarg.0
        call instance void[mscorlib]
        System.Object::.ctor()
        nop
        ret
    } // end of Program::.ctor
}";

            var source = @"
using System;
unsafe class C
{
    static delegate*<string, string, void> Prop
    {
        get
        {
            Console.WriteLine(""Getter"");
            return Program.LoadPtr();
        }
    }

    static delegate*<string, string, void> Method()
    {
        Console.WriteLine(""Method"");
        return Program.LoadPtr();
    }

    static string GetArg(string val)
    {
        Console.WriteLine($""Getting {val}"");
        return val;
    }

    static void PropertyOrder()
    {
        Prop(GetArg(""1""), GetArg(""2""));
    }

    static void MethodOrder()
    {
        Method()(GetArg(""3""), GetArg(""4""));
    }

    static void Main()
    {
        Console.WriteLine(""Property Access"");
        PropertyOrder();
        Console.WriteLine(""Method Access"");
        MethodOrder();
    }
}
";
            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Property Access
Getter
Getting 1
Getting 2
12
Method Access
Method
Getting 3
Getting 4
34");

            verifier.VerifyIL("C.PropertyOrder", expectedIL: @"
{
  // Code size       33 (0x21)
  .maxstack  3
2000 2001
  .locals init (delegate*<string, string, void> V_0)
  IL_0000:  call       ""delegate*<string, string, void> C.Prop.get""
2002 2003 2004 2005 2006 2007
  IL_0005:  stloc.0
  IL_0006:  ldstr      ""1""
  IL_000b:  call       ""string C.GetArg(string)""
  IL_0010:  ldstr      ""2""
  IL_0015:  call       ""string C.GetArg(string)""
  IL_001a:  ldloc.0
2008
  IL_001b:  calli      ""delegate*<string, string, void>""
2009 2010 2011 2012 2013 2014 2015
  IL_0020:  ret
}");

            verifier.VerifyIL("C.MethodOrder()", expectedIL: @"
{
  // Code size       33 (0x21)
  .maxstack  3
2016 2017
  .locals init (delegate*<string, string, void> V_0)
  IL_0000:  call       ""delegate*<string, string, void> C.Method()""
2018 2019 2020 2021 2022 2023
  IL_0005:  stloc.0
  IL_0006:  ldstr      ""3""
  IL_000b:  call       ""string C.GetArg(string)""
  IL_0010:  ldstr      ""4""
  IL_0015:  call       ""string C.GetArg(string)""
  IL_001a:  ldloc.0
2024
  IL_001b:  calli      ""delegate*<string, string, void>""
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 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 2080 2081 2082 2083 2084 2085 2086
  IL_0020:  ret
}");
        }

        [Fact]
        public void ReturnValueUsed()
        {

            var ilStub = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static 
        method string *(string) LoadPtr () cil managed 
    {
        nop
        ldftn string Program::Called(string)
        ret
    } // end of method Program::Main

    .method private hidebysig static 
        string Called (string arg) cil managed 
    {
        nop
        ldstr ""Called""
        call void [mscorlib]System.Console::WriteLine(string)
        ldarg.0
        ret
    } // end of Program::Called

    .method public hidebysig specialname rtspecialname
        instance void .ctor() cil managed
    {
            ldarg.0
            call instance void[mscorlib] System.Object::.ctor()
            nop
            ret
    } // end of Program::.ctor
}
";

            var source = @"
using System;
unsafe class C
{
    static void Main()
    {
        var retValue = Program.LoadPtr()(""Returned"");
        Console.WriteLine(retValue);
    }
}
";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Called
Returned");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       23 (0x17)
  .maxstack  2
2087 2088
  .locals init (delegate*<string, string> V_0)
  IL_0000:  call       ""delegate*<string, string> Program.LoadPtr()""
2089 2090 2091
  IL_0005:  stloc.0
  IL_0006:  ldstr      ""Returned""
  IL_000b:  ldloc.0
2092
  IL_000c:  calli      ""delegate*<string, string>""
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 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
  IL_0011:  call       ""void System.Console.WriteLine(string)""
  IL_0016:  ret
}");
        }

        [Fact]
        public void ReturnValueUnused()
        {

            var ilStub = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static 
        method string *(string) LoadPtr () cil managed 
    {
        nop
        ldftn string Program::Called(string)
        ret
    } // end of method Program::Main

    .method private hidebysig static 
        string Called (string arg) cil managed 
    {
        nop
        ldstr ""Called""
        call void [mscorlib]System.Console::WriteLine(string)
        ldarg.0
        ret
    } // end of Program::Called

    .method public hidebysig specialname rtspecialname
        instance void .ctor() cil managed
    {
            ldarg.0
            call instance void[mscorlib] System.Object::.ctor()
            nop
            ret
    } // end of Program::.ctor
}
";

            var source = @"
using System;
unsafe class C
{
    static void Main()
    {
F
Fredric Silberberg 已提交
2142
        Program.LoadPtr()(""Unused"");
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
        Console.WriteLine(""Constant"");
    }
}
";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Called
Constant");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       29 (0x1d)
  .maxstack  2
2156 2157
  .locals init (delegate*<string, string> V_0)
  IL_0000:  call       ""delegate*<string, string> Program.LoadPtr()""
2158 2159 2160
  IL_0005:  stloc.0
  IL_0006:  ldstr      ""Unused""
  IL_000b:  ldloc.0
2161
  IL_000c:  calli      ""delegate*<string, string>""
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 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 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
  IL_0011:  pop
  IL_0012:  ldstr      ""Constant""
  IL_0017:  call       ""void System.Console.WriteLine(string)""
  IL_001c:  ret
}");
        }

        [Fact]
        public void FunctionPointerReturningFunctionPointer()
        {

            var ilStub = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static 
        method method string *(string) *() LoadPtr () cil managed 
    {
        nop
        ldftn method string *(string) Program::Called1()
        ret
    } // end of method Program::LoadPtr

    .method private hidebysig static 
        method string *(string) Called1 () cil managed 
    {
        nop
        ldstr ""Outer pointer""
        call void [mscorlib]System.Console::WriteLine(string)
        ldftn string Program::Called2(string)
        ret
    } // end of Program::Called1

    .method private hidebysig static 
        string Called2 (string arg) cil managed 
    {
        nop
        ldstr ""Inner pointer""
        call void [mscorlib]System.Console::WriteLine(string)
        ldarg.0
        ret
    } // end of Program::Called2

    .method public hidebysig specialname rtspecialname
        instance void .ctor() cil managed
    {
            ldarg.0
            call instance void[mscorlib] System.Object::.ctor()
            nop
            ret
    } // end of Program::.ctor
}
";

            var source = @"
using System;
unsafe class C
{
    public static void Main()
    {
        var outer = Program.LoadPtr();
        var inner = outer();
        Console.WriteLine(inner(""Returned""));
    }
}";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Outer pointer
Inner pointer
Returned");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
2236
  // Code size       28 (0x1c)
2237
  .maxstack  2
2238 2239 2240
  .locals init (delegate*<string, string> V_0)
  IL_0000:  call       ""delegate*<delegate*<string, string>> Program.LoadPtr()""
  IL_0005:  calli      ""delegate*<delegate*<string, string>>""
2241
  IL_000a:  stloc.0
2242 2243
  IL_000b:  ldstr      ""Returned""
  IL_0010:  ldloc.0
2244
  IL_0011:  calli      ""delegate*<string, string>""
2245 2246
  IL_0016:  call       ""void System.Console.WriteLine(string)""
  IL_001b:  ret
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 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
}");
        }

        [Fact]
        public void UserDefinedConversionParameter()
        {

            var ilStub = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    .field public string '_field'

    // Methods
    .method public hidebysig static 
        method void *(class Program) LoadPtr () cil managed 
    {
        nop
        ldstr ""LoadPtr""
        call void [mscorlib]System.Console::WriteLine(string)
        ldftn void Program::Called(class Program)
        ret
    } // end of method Program::LoadPtr

    .method private hidebysig static 
        void Called (class Program arg1) cil managed 
    {
        nop
        ldarg.0
        ldfld string Program::'_field'
        call void [mscorlib]System.Console::WriteLine(string)
        ret
    } // end of Program::Called

    .method public hidebysig specialname rtspecialname
        instance void .ctor() cil managed
    {
            ldarg.0
            call instance void[mscorlib] System.Object::.ctor()
            nop
            ret
    } // end of Program::.ctor
}
";

            var source = @"
using System;
unsafe class C
{
    public static void Main()
    {
        Program.LoadPtr()(new C());
    }

    public static implicit operator Program(C c)
    {
        var p = new Program();
        p._field = ""Implicit conversion"";
        return p;
    }
}";
            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
LoadPtr
Implicit conversion
");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       23 (0x17)
  .maxstack  2
2317 2318
  .locals init (delegate*<Program, void> V_0)
  IL_0000:  call       ""delegate*<Program, void> Program.LoadPtr()""
2319 2320 2321 2322
  IL_0005:  stloc.0
  IL_0006:  newobj     ""C..ctor()""
  IL_000b:  call       ""Program C.op_Implicit(C)""
  IL_0010:  ldloc.0
2323
  IL_0011:  calli      ""delegate*<Program, void>""
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 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 2379 2380 2381 2382
  IL_0016:  ret
}");
        }

        [Fact]
        public void RefParameter()
        {
            var ilStub = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static 
        method void *(string&) LoadPtr () cil managed 
    {
        nop
        ldftn void Program::Called(string&)
        ret
    } // end of method Program::Main

    .method private hidebysig static 
        void Called (string& arg) cil managed 
    {
        nop
        ldarg.0
        ldstr ""Ref set""
        stind.ref
        ret
    } // end of Program::Called

    .method public hidebysig specialname rtspecialname
        instance void .ctor() cil managed
    {
            ldarg.0
            call instance void[mscorlib] System.Object::.ctor()
            nop
            ret
    } // end of Program::.ctor
}
";

            var source = @"
using System;
unsafe class C
{
    static void Main()
    {
        delegate*<ref string, void> pointer = Program.LoadPtr();
        string str = ""Unset"";
        pointer(ref str);
        Console.WriteLine(str);
    }
}
";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"Ref set");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
2383
  // Code size       27 (0x1b)
2384
  .maxstack  2
2385
  .locals init (string V_0, //str
2386 2387
                delegate*<ref string, void> V_1)
  IL_0000:  call       ""delegate*<ref string, void> Program.LoadPtr()""
2388 2389
  IL_0005:  ldstr      ""Unset""
  IL_000a:  stloc.0
2390
  IL_000b:  stloc.1
2391 2392
  IL_000c:  ldloca.s   V_0
  IL_000e:  ldloc.1
2393
  IL_000f:  calli      ""delegate*<ref string, void>""
2394 2395 2396
  IL_0014:  ldloc.0
  IL_0015:  call       ""void System.Console.WriteLine(string)""
  IL_001a:  ret
2397 2398 2399 2400
}");
        }

        [Fact]
F
Fredric Silberberg 已提交
2401
        public void RefReturnUsedByValue()
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 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 ilStub = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    .field public static string 'field'

    // Methods
    .method public hidebysig static 
        method string& *() LoadPtr () cil managed 
    {
        nop
        ldftn string& Program::Called()
        ret
    } // end of method Program::Main

    .method private hidebysig static 
        string& Called () cil managed 
    {
        nop
        ldsflda string Program::'field'
        ret
    } // end of Program::Called

    .method public hidebysig specialname rtspecialname
        instance void .ctor() cil managed
    {
            ldarg.0
            call instance void[mscorlib] System.Object::.ctor()
            nop
            ret
    } // end of Program::.ctor
}
";

            var source = @"
using System;
unsafe class C
{
    static void Main()
    {
        Program.field = ""Field"";
        delegate*<ref string> pointer = Program.LoadPtr();
        Console.WriteLine(pointer());
    }
}
";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"Field");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       27 (0x1b)
  .maxstack  1
  IL_0000:  ldstr      ""Field""
  IL_0005:  stsfld     ""string Program.field""
2458 2459
  IL_000a:  call       ""delegate*<ref string> Program.LoadPtr()""
  IL_000f:  calli      ""delegate*<ref string>""
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 2491 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
  IL_0014:  ldind.ref
  IL_0015:  call       ""void System.Console.WriteLine(string)""
  IL_001a:  ret
}");
        }

        [Fact]
        public void RefReturnUsed()
        {
            var ilStub = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    .field public static string 'field'

    // Methods
    .method public hidebysig static 
        method string& *() LoadPtr () cil managed 
    {
        nop
        ldftn string& Program::Called()
        ret
    } // end of method Program::Main

    .method private hidebysig static 
        string& Called () cil managed 
    {
        nop
        ldsflda string Program::'field'
        ret
    } // end of Program::Called

    .method public hidebysig specialname rtspecialname
        instance void .ctor() cil managed
    {
            ldarg.0
            call instance void[mscorlib] System.Object::.ctor()
            nop
            ret
    } // end of Program::.ctor
}
";

            var source = @"
using System;
unsafe class C
{
    static void Main()
    {
        Program.LoadPtr()() = ""Field"";
        Console.WriteLine(Program.field);
    }
}
";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"Field");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       27 (0x1b)
  .maxstack  2
2521 2522
  IL_0000:  call       ""delegate*<ref string> Program.LoadPtr()""
  IL_0005:  calli      ""delegate*<ref string>""
2523 2524 2525 2526 2527
  IL_000a:  ldstr      ""Field""
  IL_000f:  stind.ref
  IL_0010:  ldsfld     ""string Program.field""
  IL_0015:  call       ""void System.Console.WriteLine(string)""
  IL_001a:  ret
2528 2529
}
");
2530 2531
        }

F
Fredric Silberberg 已提交
2532 2533 2534 2535 2536 2537 2538 2539 2540 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 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
        [Fact]
        public void ModifiedReceiverInParameter()
        {

            var ilStub = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static 
        method string *(string) LoadPtr1 () cil managed 
    {
        nop
        ldftn string Program::Called1(string)
        ret
    } // end of method Program::LoadPtr1

    .method public hidebysig static 
        method string *(string) LoadPtr2 () cil managed 
    {
        nop
        ldftn string Program::Called2(string)
        ret
    } // end of method Program::LoadPtr2

    .method private hidebysig static 
        string Called1 (string) cil managed 
    {
        nop
        ldstr ""Called Function 1""
        call void [mscorlib]System.Console::WriteLine(string)
        ldarg.0
        call void [mscorlib]System.Console::WriteLine(string)
        ldstr ""Returned From Function 1""
        ret
    } // end of Program::Called1

    .method private hidebysig static 
        string Called2 (string) cil managed 
    {
        nop
        ldstr ""Called Function 2""
        call void [mscorlib]System.Console::WriteLine(string)
        ldarg.0
        call void [mscorlib]System.Console::WriteLine(string)
        ldstr ""Returned From Function 2""
        ret
    } // end of Program::Called2

    .method public hidebysig specialname rtspecialname
        instance void .ctor() cil managed
    {
            ldarg.0
            call instance void[mscorlib] System.Object::.ctor()
            nop
            ret
    } // end of Program::.ctor
}
";

            var source = @"
using System;
unsafe class C
{
    public static void Main()
    {
        var ptr = Program.LoadPtr1();
        Console.WriteLine(ptr((ptr = Program.LoadPtr2())(""Argument To Function 2"")));
        Console.WriteLine(ptr(""Argument To Function 2""));
    }
}";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Called Function 2
Argument To Function 2
Called Function 1
Returned From Function 2
Returned From Function 1
Called Function 2
Argument To Function 2
Returned From Function 2");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       57 (0x39)
  .maxstack  2
2618 2619 2620 2621
  .locals init (delegate*<string, string> V_0, //ptr
                delegate*<string, string> V_1,
                delegate*<string, string> V_2)
  IL_0000:  call       ""delegate*<string, string> Program.LoadPtr1()""
F
Fredric Silberberg 已提交
2622 2623 2624
  IL_0005:  stloc.0
  IL_0006:  ldloc.0
  IL_0007:  stloc.1
2625
  IL_0008:  call       ""delegate*<string, string> Program.LoadPtr2()""
F
Fredric Silberberg 已提交
2626 2627 2628 2629 2630
  IL_000d:  dup
  IL_000e:  stloc.0
  IL_000f:  stloc.2
  IL_0010:  ldstr      ""Argument To Function 2""
  IL_0015:  ldloc.2
2631
  IL_0016:  calli      ""delegate*<string, string>""
F
Fredric Silberberg 已提交
2632
  IL_001b:  ldloc.1
2633
  IL_001c:  calli      ""delegate*<string, string>""
F
Fredric Silberberg 已提交
2634 2635 2636 2637 2638
  IL_0021:  call       ""void System.Console.WriteLine(string)""
  IL_0026:  ldloc.0
  IL_0027:  stloc.1
  IL_0028:  ldstr      ""Argument To Function 2""
  IL_002d:  ldloc.1
2639
  IL_002e:  calli      ""delegate*<string, string>""
F
Fredric Silberberg 已提交
2640 2641 2642 2643 2644
  IL_0033:  call       ""void System.Console.WriteLine(string)""
  IL_0038:  ret
}");
        }

2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671
        [Fact]
        public void Typeof()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
class C
{
    static void Main()
    {
        var t = typeof(delegate*<void>);
        Console.WriteLine(t.ToString());
    }
}
", expectedOutput: "System.IntPtr");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       21 (0x15)
  .maxstack  1
  IL_0000:  ldtoken    ""delegate*<void>""
  IL_0005:  call       ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
  IL_000a:  callvirt   ""string object.ToString()""
  IL_000f:  call       ""void System.Console.WriteLine(string)""
  IL_0014:  ret
}");
        }

F
Fredric Silberberg 已提交
2672 2673 2674 2675 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 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760
        private const string NoPiaInterfaces = @"
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]

[ComImport]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface I1
{
    string GetStr();
}

[ComImport]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58270"")]
public interface I2{}";

        [Fact]
        public void NoPiaInSignature()
        {
            var nopiaReference = CreateCompilation(NoPiaInterfaces).EmitToImageReference(embedInteropTypes: true);

            CompileAndVerifyFunctionPointers(@"
unsafe class C
{
    public delegate*<I2, I1> M() => throw null;
}", references: new[] { nopiaReference }, symbolValidator: symbolValidator);

            void symbolValidator(ModuleSymbol module)
            {
                Assert.Equal(1, module.ReferencedAssemblies.Length);
                Assert.NotEqual(nopiaReference.Display, module.ReferencedAssemblies[0].Name);

                var i1 = module.GlobalNamespace.GetTypeMembers("I1").Single();
                Assert.NotNull(i1);
                Assert.Equal(module, i1.ContainingModule);

                var i2 = module.GlobalNamespace.GetTypeMembers("I2").Single();
                Assert.NotNull(i2);
                Assert.Equal(module, i2.ContainingModule);

                var c = module.GlobalNamespace.GetTypeMembers("C").Single();
                var m = c.GetMethod("M");

                var returnType = (FunctionPointerTypeSymbol)m.ReturnType;
                Assert.Equal(i1, returnType.Signature.ReturnType);
                Assert.Equal(i2, returnType.Signature.ParameterTypesWithAnnotations[0].Type);
            }
        }

        [Fact]
        public void NoPiaInTypeOf()
        {
            var nopiaReference = CreateCompilation(NoPiaInterfaces).EmitToImageReference(embedInteropTypes: true);

            CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    public Type M() => typeof(delegate*<I1, I2>);
}", references: new[] { nopiaReference }, symbolValidator: symbolValidator);

            void symbolValidator(ModuleSymbol module)
            {
                Assert.Equal(1, module.ReferencedAssemblies.Length);
                Assert.NotEqual(nopiaReference.Display, module.ReferencedAssemblies[0].Name);

                var i1 = module.GlobalNamespace.GetTypeMembers("I1").Single();
                Assert.NotNull(i1);
                Assert.Equal(module, i1.ContainingModule);

                var i2 = module.GlobalNamespace.GetTypeMembers("I2").Single();
                Assert.NotNull(i2);
                Assert.Equal(module, i2.ContainingModule);
            }
        }

        [Fact]
        public void NoPiaInCall()
        {
            var nopiaReference = CreateCompilation(NoPiaInterfaces).EmitToImageReference(embedInteropTypes: true);

            var intermediate = CreateCompilation(@"
using System;
public unsafe class C
{
    public delegate*<I1> M() => throw null;
2761
}", references: new[] { nopiaReference }, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll).EmitToImageReference();
F
Fredric Silberberg 已提交
2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782

            CompileAndVerifyFunctionPointers(@"
unsafe class C2
{
    public void M(C c)
    {
        _ = c.M()();
    }
}", references: new[] { nopiaReference, intermediate }, symbolValidator: symbolValidator);

            void symbolValidator(ModuleSymbol module)
            {
                Assert.Equal(2, module.ReferencedAssemblies.Length);
                Assert.DoesNotContain(nopiaReference.Display, module.ReferencedAssemblies.Select(a => a.Name));
                Assert.Equal(intermediate.Display, module.ReferencedAssemblies[1].Name);

                var i1 = module.GlobalNamespace.GetTypeMembers("I1").Single();
                Assert.NotNull(i1);
                Assert.Equal(module, i1.ContainingModule);
            }
        }
2783

F
Fredric Silberberg 已提交
2784
        [Fact]
2785
        public void InternalsVisibleToAccessChecks_01()
F
Fredric Silberberg 已提交
2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797
        {
            var aRef = CreateCompilation(@"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""B"")]
internal class A {}", assemblyName: "A").EmitToImageReference();

            var bRef = CreateCompilation(@"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""C"")]
internal class B
{
    internal unsafe delegate*<A> M() => throw null;
2798
}", references: new[] { aRef }, assemblyName: "B", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll).EmitToImageReference();
F
Fredric Silberberg 已提交
2799 2800 2801 2802 2803 2804 2805 2806

            var cComp = CreateCompilation(@"
internal class C
{
    internal unsafe void CM(B b)
    {
        b.M()();
    }
2807
}", references: new[] { aRef, bRef }, assemblyName: "C", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
F
Fredric Silberberg 已提交
2808 2809 2810 2811 2812 2813 2814

            cComp.VerifyDiagnostics(
                    // (6,9): error CS0122: 'B.M()' is inaccessible due to its protection level
                    //         b.M()();
                    Diagnostic(ErrorCode.ERR_BadAccess, "b.M").WithArguments("B.M()").WithLocation(6, 9));
        }

2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
        [Fact]
        public void InternalsVisibleToAccessChecks_02()
        {
            var aRef = CreateCompilation(@"
using System.Runtime.CompilerServices;
public class A {}", assemblyName: "A").EmitToImageReference();

            var bRef = CreateCompilation(@"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""C"")]
internal class B
{
    internal unsafe delegate*<A> M() => throw null;
2828
}", references: new[] { aRef }, assemblyName: "B", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll).EmitToImageReference();
2829 2830 2831 2832 2833 2834 2835 2836

            var cComp = CreateCompilation(@"
internal class C
{
    internal unsafe void CM(B b)
    {
        b.M()();
    }
2837
}", references: new[] { aRef, bRef }, assemblyName: "C", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
2838 2839 2840 2841

            cComp.VerifyDiagnostics();
        }

F
Fredric Silberberg 已提交
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861
        [Fact]
        public void AddressOf_Initializer_VoidReturnNoParams()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void M() => Console.Write(""1"");
    static void Main()
    {
        delegate*<void> ptr = &M;
        ptr();
    }
}", expectedOutput: "1");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       12 (0xc)
  .maxstack  1
  IL_0000:  ldftn      ""void C.M()""
F
Fredric Silberberg 已提交
2862
  IL_0006:  calli      ""delegate*<void>""
F
Fredric Silberberg 已提交
2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
  IL_000b:  ret
}");
        }

        [Fact]
        public void AddressOf_Initializer_VoidReturnValueParams()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void M(string s, int i) => Console.Write(s + i.ToString());
    static void Main()
    {
        delegate*<string, int, void> ptr = &M;
        ptr(""1"", 2);
    }
}", expectedOutput: "12");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       20 (0x14)
  .maxstack  3
2886
  .locals init (delegate*<string, int, void> V_0)
F
Fredric Silberberg 已提交
2887 2888 2889 2890 2891
  IL_0000:  ldftn      ""void C.M(string, int)""
  IL_0006:  stloc.0
  IL_0007:  ldstr      ""1""
  IL_000c:  ldc.i4.2
  IL_000d:  ldloc.0
2892
  IL_000e:  calli      ""delegate*<string, int, void>""
F
Fredric Silberberg 已提交
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927
  IL_0013:  ret
}");
        }

        [Fact]
        public void AddressOf_Initializer_VoidReturnRefParameters()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void M(ref string s, in int i, out object o)
    {
        Console.Write(s + i.ToString());
        s = ""3"";
        o = ""4"";
    }
    static void Main()
    {
        delegate*<ref string, in int, out object, void> ptr = &M;
        string s = ""1"";
        int i = 2;
        ptr(ref s, in i, out var o);
        Console.Write(s);
        Console.Write(o);
    }
}", expectedOutput: "1234");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       40 (0x28)
  .maxstack  4
  .locals init (string V_0, //s
                int V_1, //i
                object V_2, //o
2928
                delegate*<ref string, in int, out object, void> V_3)
F
Fredric Silberberg 已提交
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938
  IL_0000:  ldftn      ""void C.M(ref string, in int, out object)""
  IL_0006:  ldstr      ""1""
  IL_000b:  stloc.0
  IL_000c:  ldc.i4.2
  IL_000d:  stloc.1
  IL_000e:  stloc.3
  IL_000f:  ldloca.s   V_0
  IL_0011:  ldloca.s   V_1
  IL_0013:  ldloca.s   V_2
  IL_0015:  ldloc.3
2939
  IL_0016:  calli      ""delegate*<ref string, in int, out object, void>""
F
Fredric Silberberg 已提交
2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973
  IL_001b:  ldloc.0
  IL_001c:  call       ""void System.Console.Write(string)""
  IL_0021:  ldloc.2
  IL_0022:  call       ""void System.Console.Write(object)""
  IL_0027:  ret
}");
        }

        [Fact]
        public void AddressOf_Initializer_ReturnStruct()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe struct S
{
    int i;
    public S(int i)
    {
        this.i = i;
    }
    void M() => Console.Write(i);

    static S MakeS(int i) => new S(i); 
    public static void Main()
    {
        delegate*<int, S> ptr = &MakeS;
        ptr(1).M();
    }
}", expectedOutput: "1");

            verifier.VerifyIL("S.Main()", expectedIL: @"
{
  // Code size       23 (0x17)
  .maxstack  2
2974
  .locals init (delegate*<int, S> V_0,
F
Fredric Silberberg 已提交
2975 2976 2977 2978 2979
                S V_1)
  IL_0000:  ldftn      ""S S.MakeS(int)""
  IL_0006:  stloc.0
  IL_0007:  ldc.i4.1
  IL_0008:  ldloc.0
2980
  IL_0009:  calli      ""delegate*<int, S>""
F
Fredric Silberberg 已提交
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
  IL_000e:  stloc.1
  IL_000f:  ldloca.s   V_1
  IL_0011:  call       ""void S.M()""
  IL_0016:  ret
}");
        }

        [Fact]
        public void AddressOf_Initializer_ReturnClass()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    int i;
    public C(int i)
    {
        this.i = i;
    }
    void M() => Console.Write(i);

    static C MakeC(int i) => new C(i); 
    public static void Main()
    {
        delegate*<int, C> ptr = &MakeC;
        ptr(1).M();
    }
}", expectedOutput: "1");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       20 (0x14)
  .maxstack  2
3014
  .locals init (delegate*<int, C> V_0)
F
Fredric Silberberg 已提交
3015 3016 3017 3018
  IL_0000:  ldftn      ""C C.MakeC(int)""
  IL_0006:  stloc.0
  IL_0007:  ldc.i4.1
  IL_0008:  ldloc.0
3019
  IL_0009:  calli      ""delegate*<int, C>""
F
Fredric Silberberg 已提交
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
  IL_000e:  callvirt   ""void C.M()""
  IL_0013:  ret
}");
        }

        [Fact]
        public void AddressOf_Initializer_ContravariantParameters()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void M(object o, void* i) => Console.Write(o.ToString() + (*((int*)i)).ToString());
    static void Main()
    {
        delegate*<string, int*, void> ptr = &M;
        int i = 2;
        ptr(""1"", &i);
    }
}", expectedOutput: "12");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       24 (0x18)
  .maxstack  3
  .locals init (int V_0, //i
3046
                delegate*<string, int*, void> V_1)
F
Fredric Silberberg 已提交
3047 3048 3049 3050 3051 3052 3053 3054
  IL_0000:  ldftn      ""void C.M(object, void*)""
  IL_0006:  ldc.i4.2
  IL_0007:  stloc.0
  IL_0008:  stloc.1
  IL_0009:  ldstr      ""1""
  IL_000e:  ldloca.s   V_0
  IL_0010:  conv.u
  IL_0011:  ldloc.1
3055
  IL_0012:  calli      ""delegate*<string, int*, void>""
F
Fredric Silberberg 已提交
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
  IL_0017:  ret
}");
        }

        [Fact]
        public void AddressOf_Initializer_CovariantReturns()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
public unsafe class C
{
    static string M1() => ""1"";
    static int i = 2;
    static int* M2()
    {
        fixed (int* i1 = &i)
        {
            return i1;
        }
    }

    static void Main()
    {
        delegate*<object> ptr1 = &M1;
        Console.Write(ptr1());
        delegate*<void*> ptr2 = &M2;
        Console.Write(*(int*)ptr2());
    }
}
", expectedOutput: "12");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       34 (0x22)
  .maxstack  1
  IL_0000:  ldftn      ""string C.M1()""
F
Fredric Silberberg 已提交
3092
  IL_0006:  calli      ""delegate*<object>""
F
Fredric Silberberg 已提交
3093 3094
  IL_000b:  call       ""void System.Console.Write(object)""
  IL_0010:  ldftn      ""int* C.M2()""
F
Fredric Silberberg 已提交
3095
  IL_0016:  calli      ""delegate*<void*>""
F
Fredric Silberberg 已提交
3096 3097 3098 3099 3100 3101
  IL_001b:  ldind.i4
  IL_001c:  call       ""void System.Console.Write(int)""
  IL_0021:  ret
}");
        }

3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121
        [Fact]
        public void AddressOf_FunctionPointerConversionReturn()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static string ToStringer(object o) => o.ToString();
    static delegate*<object, string> Returner() => &ToStringer;
    public static void Main()
    {
        delegate*<delegate*<string, object>> ptr = &Returner;
        Console.Write(ptr()(""1""));
    }
}", expectedOutput: "1");

            verifier.VerifyIL("C.Main", @"
{
  // Code size       29 (0x1d)
  .maxstack  2
3122 3123 3124
  .locals init (delegate*<string, object> V_0)
  IL_0000:  ldftn      ""delegate*<object, string> C.Returner()""
  IL_0006:  calli      ""delegate*<delegate*<string, object>>""
3125 3126 3127
  IL_000b:  stloc.0
  IL_000c:  ldstr      ""1""
  IL_0011:  ldloc.0
3128
  IL_0012:  calli      ""delegate*<string, object>""
3129 3130 3131 3132 3133 3134
  IL_0017:  call       ""void System.Console.Write(object)""
  IL_001c:  ret
}
");
        }

3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162
        [Theory]
        [InlineData("in")]
        [InlineData("ref")]
        public void AddressOf_Initializer_Overloads(string refType)
        {
            var verifier = CompileAndVerifyFunctionPointers($@"
using System;
unsafe class C
{{
    static void M(object o) => Console.Write(""object"" + o.ToString());
    static void M(string s) => Console.Write(""string"" + s);
    static void M({refType} string s) {{ Console.Write(""{refType}"" + s); }}
    static void M(int i) => Console.Write(""int"" + i.ToString());
    static void Main()
    {{
        delegate*<string, void> ptr = &M;
        ptr(""1"");
        string s = ""2"";
        delegate*<{refType} string, void> ptr2 = &M;
        ptr2({refType} s);
    }}
}}", expectedOutput: $"string1{refType}2");

            verifier.VerifyIL("C.Main()", expectedIL: $@"
{{
  // Code size       40 (0x28)
  .maxstack  2
  .locals init (string V_0, //s
3163 3164
                delegate*<string, void> V_1,
                delegate*<{refType} string, void> V_2)
3165 3166 3167 3168
  IL_0000:  ldftn      ""void C.M(string)""
  IL_0006:  stloc.1
  IL_0007:  ldstr      ""1""
  IL_000c:  ldloc.1
3169
  IL_000d:  calli      ""delegate*<string, void>""
3170 3171 3172 3173 3174 3175
  IL_0012:  ldstr      ""2""
  IL_0017:  stloc.0
  IL_0018:  ldftn      ""void C.M({refType} string)""
  IL_001e:  stloc.2
  IL_001f:  ldloca.s   V_0
  IL_0021:  ldloc.2
3176
  IL_0022:  calli      ""delegate*<{refType} string, void>""
3177 3178 3179 3180 3181
  IL_0027:  ret
}}
");
        }

F
Fredric Silberberg 已提交
3182
        [Fact]
3183
        public void AddressOf_Initializer_Overloads_Out()
F
Fredric Silberberg 已提交
3184 3185 3186 3187 3188 3189 3190
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void M(object o) => Console.Write(""object"" + o.ToString());
    static void M(string s) => Console.Write(""string"" + s);
3191
    static void M(out string s) { s = ""2""; }
F
Fredric Silberberg 已提交
3192 3193 3194 3195 3196
    static void M(int i) => Console.Write(""int"" + i.ToString());
    static void Main()
    {
        delegate*<string, void> ptr = &M;
        ptr(""1"");
3197 3198 3199
        delegate*<out string, void> ptr2 = &M;
        ptr2(out string s);
        Console.Write(s);
F
Fredric Silberberg 已提交
3200
    }
3201
}", expectedOutput: $"string12");
F
Fredric Silberberg 已提交
3202 3203 3204

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
3205
  // Code size       40 (0x28)
F
Fredric Silberberg 已提交
3206
  .maxstack  2
3207
  .locals init (string V_0, //s
3208 3209
                delegate*<string, void> V_1,
                delegate*<out string, void> V_2)
F
Fredric Silberberg 已提交
3210
  IL_0000:  ldftn      ""void C.M(string)""
3211
  IL_0006:  stloc.1
F
Fredric Silberberg 已提交
3212
  IL_0007:  ldstr      ""1""
3213
  IL_000c:  ldloc.1
3214
  IL_000d:  calli      ""delegate*<string, void>""
3215 3216 3217 3218
  IL_0012:  ldftn      ""void C.M(out string)""
  IL_0018:  stloc.2
  IL_0019:  ldloca.s   V_0
  IL_001b:  ldloc.2
3219
  IL_001c:  calli      ""delegate*<out string, void>""
3220 3221 3222 3223 3224
  IL_0021:  ldloc.0
  IL_0022:  call       ""void System.Console.Write(string)""
  IL_0027:  ret
}
");
F
Fredric Silberberg 已提交
3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243

            var comp = (CSharpCompilation)verifier.Compilation;
            var syntaxTree = comp.SyntaxTrees[0];
            var model = comp.GetSemanticModel(syntaxTree);

            var addressOfs = syntaxTree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().ToArray();

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOfs[0],
                expectedSyntax: "&M",
                expectedType: null,
                expectedConvertedType: "delegate*<System.String, System.Void>",
                expectedSymbol: "void C.M(System.String s)");

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOfs[1],
                expectedSyntax: "&M",
                expectedType: null,
                expectedConvertedType: "delegate*<out modreq(System.Runtime.InteropServices.OutAttribute) System.String, System.Void>",
                expectedSymbol: "void C.M(out System.String s)");

F
Fredric Silberberg 已提交
3244
            string[] expectedMembers = new[] {
F
Fredric Silberberg 已提交
3245 3246 3247 3248 3249 3250 3251 3252
                "void C.M(System.Object o)",
                "void C.M(System.String s)",
                "void C.M(out System.String s)",
                "void C.M(System.Int32 i)"
            };

            AssertEx.Equal(expectedMembers, model.GetMemberGroup(addressOfs[0].Operand).Select(m => m.ToTestDisplayString(includeNonNullable: false)));
            AssertEx.Equal(expectedMembers, model.GetMemberGroup(addressOfs[1].Operand).Select(m => m.ToTestDisplayString(includeNonNullable: false)));
F
Fredric Silberberg 已提交
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
        }

        [Fact]
        public void AddressOf_Initializer_Overloads_NoMostSpecific()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
interface I1 {}
interface I2 {}
static class IHelpers
{
    public static void M(I1 i1) {}
    public static void M(I2 i2) {}
}
class C : I1, I2
{
    unsafe static void Main()
    {
        delegate*<C, void> ptr = &IHelpers.M;
    }
}");
            comp.VerifyDiagnostics(
F
Fredric Silberberg 已提交
3274
                // (13,35): error CS0121: The call is ambiguous between the following methods or properties: 'IHelpers.M(I1)' and 'IHelpers.M(I2)'
F
Fredric Silberberg 已提交
3275
                //         delegate*<C, void> ptr = &IHelpers.M;
F
Fredric Silberberg 已提交
3276
                Diagnostic(ErrorCode.ERR_AmbigCall, "IHelpers.M").WithArguments("IHelpers.M(I1)", "IHelpers.M(I2)").WithLocation(13, 35)
F
Fredric Silberberg 已提交
3277
            );
F
Fredric Silberberg 已提交
3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288

            var syntaxTree = comp.SyntaxTrees[0];
            var model = comp.GetSemanticModel(syntaxTree);

            var addressOf = syntaxTree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOf,
                expectedSyntax: "&IHelpers.M",
                expectedType: null,
                expectedConvertedType: "delegate*<C, System.Void>",
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
F
Fredric Silberberg 已提交
3289
                expectedSymbolCandidates: new[] { "void IHelpers.M(I1 i1)", "void IHelpers.M(I2 i2)" });
F
Fredric Silberberg 已提交
3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312
        }

        [Fact]
        public void AddressOf_Initializer_Overloads_RefNotCovariant()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
    void M1(ref object o) {}
    void M2(in object o) {}
    void M3(out string s) => throw null;
    void M()
    {
        delegate*<ref string, void> ptr1 = &M1;
        delegate*<string, void> ptr2 = &M1;
        delegate*<in string, void> ptr3 = &M2;
        delegate*<string, void> ptr4 = &M2;
        delegate*<out object, void> ptr5 = &M3;
        delegate*<string, void> ptr6 = &M3;
    }
}");

            comp.VerifyDiagnostics(
3313
                // (9,44): error CS8757: No overload for 'M1' matches function pointer 'delegate*<ref string, void>'
F
Fredric Silberberg 已提交
3314
                //         delegate*<ref string, void> ptr1 = &M1;
3315 3316
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<ref string, void>").WithLocation(9, 44),
                // (10,40): error CS8757: No overload for 'M1' matches function pointer 'delegate*<string, void>'
F
Fredric Silberberg 已提交
3317
                //         delegate*<string, void> ptr2 = &M1;
3318 3319
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<string, void>").WithLocation(10, 40),
                // (11,43): error CS8757: No overload for 'M2' matches function pointer 'delegate*<in string, void>'
F
Fredric Silberberg 已提交
3320
                //         delegate*<in string, void> ptr3 = &M2;
3321 3322
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<in string, void>").WithLocation(11, 43),
                // (12,40): error CS8757: No overload for 'M2' matches function pointer 'delegate*<string, void>'
F
Fredric Silberberg 已提交
3323
                //         delegate*<string, void> ptr4 = &M2;
3324 3325
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<string, void>").WithLocation(12, 40),
                // (13,44): error CS8757: No overload for 'M3' matches function pointer 'delegate*<out object, void>'
F
Fredric Silberberg 已提交
3326
                //         delegate*<out object, void> ptr5 = &M3;
3327 3328
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<out object, void>").WithLocation(13, 44),
                // (14,40): error CS8757: No overload for 'M3' matches function pointer 'delegate*<string, void>'
F
Fredric Silberberg 已提交
3329
                //         delegate*<string, void> ptr6 = &M3;
3330
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<string, void>").WithLocation(14, 40)
F
Fredric Silberberg 已提交
3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
            );
        }

        [Fact]
        public void AddressOf_RefsMustMatch()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
    void M1(ref object o) {}
    void M2(in object o) {}
    void M3(out object s) => throw null;
    void M4(object s) => throw null;
    ref object M5() => throw null;
    ref readonly object M6() => throw null;
    object M7() => throw null!;
    void M()
    {
        delegate*<object, void> ptr1 = &M1;
        delegate*<object, void> ptr2 = &M2;
        delegate*<object, void> ptr3 = &M3;
F
Fredric Silberberg 已提交
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
        delegate*<ref object, void> ptr4 = &M2;
        delegate*<ref object, void> ptr5 = &M3;
        delegate*<ref object, void> ptr6 = &M4;
        delegate*<in object, void> ptr7 = &M1;
        delegate*<in object, void> ptr8 = &M3;
        delegate*<in object, void> ptr9 = &M4;
        delegate*<out object, void> ptr10 = &M1;
        delegate*<out object, void> ptr11 = &M2;
        delegate*<out object, void> ptr12 = &M4;
        delegate*<object> ptr13 = &M5;
        delegate*<object> ptr14 = &M6;
        delegate*<ref object> ptr15 = &M6;
        delegate*<ref object> ptr16 = &M7;
        delegate*<ref readonly object> ptr17 = &M5;
        delegate*<ref readonly object> ptr18 = &M7;
F
Fredric Silberberg 已提交
3367 3368 3369 3370
    }
}");

            comp.VerifyDiagnostics(
3371
                // (13,40): error CS8757: No overload for 'M1' matches function pointer 'delegate*<object, void>'
F
Fredric Silberberg 已提交
3372
                //         delegate*<object, void> ptr1 = &M1;
3373 3374
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<object, void>").WithLocation(13, 40),
                // (14,40): error CS8757: No overload for 'M2' matches function pointer 'delegate*<object, void>'
F
Fredric Silberberg 已提交
3375
                //         delegate*<object, void> ptr2 = &M2;
3376 3377
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<object, void>").WithLocation(14, 40),
                // (15,40): error CS8757: No overload for 'M3' matches function pointer 'delegate*<object, void>'
F
Fredric Silberberg 已提交
3378
                //         delegate*<object, void> ptr3 = &M3;
3379 3380
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<object, void>").WithLocation(15, 40),
                // (16,44): error CS8757: No overload for 'M2' matches function pointer 'delegate*<ref object, void>'
F
Fredric Silberberg 已提交
3381
                //         delegate*<ref object, void> ptr4 = &M2;
3382 3383
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<ref object, void>").WithLocation(16, 44),
                // (17,44): error CS8757: No overload for 'M3' matches function pointer 'delegate*<ref object, void>'
F
Fredric Silberberg 已提交
3384
                //         delegate*<ref object, void> ptr5 = &M3;
3385 3386
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<ref object, void>").WithLocation(17, 44),
                // (18,44): error CS8757: No overload for 'M4' matches function pointer 'delegate*<ref object, void>'
F
Fredric Silberberg 已提交
3387
                //         delegate*<ref object, void> ptr6 = &M4;
3388 3389
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M4").WithArguments("M4", "delegate*<ref object, void>").WithLocation(18, 44),
                // (19,43): error CS8757: No overload for 'M1' matches function pointer 'delegate*<in object, void>'
F
Fredric Silberberg 已提交
3390
                //         delegate*<in object, void> ptr7 = &M1;
3391 3392
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<in object, void>").WithLocation(19, 43),
                // (20,43): error CS8757: No overload for 'M3' matches function pointer 'delegate*<in object, void>'
F
Fredric Silberberg 已提交
3393
                //         delegate*<in object, void> ptr8 = &M3;
3394 3395
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<in object, void>").WithLocation(20, 43),
                // (21,43): error CS8757: No overload for 'M4' matches function pointer 'delegate*<in object, void>'
F
Fredric Silberberg 已提交
3396
                //         delegate*<in object, void> ptr9 = &M4;
3397 3398
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M4").WithArguments("M4", "delegate*<in object, void>").WithLocation(21, 43),
                // (22,45): error CS8757: No overload for 'M1' matches function pointer 'delegate*<out object, void>'
F
Fredric Silberberg 已提交
3399
                //         delegate*<out object, void> ptr10 = &M1;
3400 3401
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<out object, void>").WithLocation(22, 45),
                // (23,45): error CS8757: No overload for 'M2' matches function pointer 'delegate*<out object, void>'
F
Fredric Silberberg 已提交
3402
                //         delegate*<out object, void> ptr11 = &M2;
3403 3404
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<out object, void>").WithLocation(23, 45),
                // (24,45): error CS8757: No overload for 'M4' matches function pointer 'delegate*<out object, void>'
F
Fredric Silberberg 已提交
3405
                //         delegate*<out object, void> ptr12 = &M4;
3406
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M4").WithArguments("M4", "delegate*<out object, void>").WithLocation(24, 45),
F
Fredric Silberberg 已提交
3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424
                // (25,36): error CS8758: Ref mismatch between 'C.M5()' and function pointer 'delegate*<object>'
                //         delegate*<object> ptr13 = &M5;
                Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M5").WithArguments("C.M5()", "delegate*<object>").WithLocation(25, 36),
                // (26,36): error CS8758: Ref mismatch between 'C.M6()' and function pointer 'delegate*<object>'
                //         delegate*<object> ptr14 = &M6;
                Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M6").WithArguments("C.M6()", "delegate*<object>").WithLocation(26, 36),
                // (27,40): error CS8758: Ref mismatch between 'C.M6()' and function pointer 'delegate*<object>'
                //         delegate*<ref object> ptr15 = &M6;
                Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M6").WithArguments("C.M6()", "delegate*<object>").WithLocation(27, 40),
                // (28,40): error CS8758: Ref mismatch between 'C.M7()' and function pointer 'delegate*<object>'
                //         delegate*<ref object> ptr16 = &M7;
                Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M7").WithArguments("C.M7()", "delegate*<object>").WithLocation(28, 40),
                // (29,49): error CS8758: Ref mismatch between 'C.M5()' and function pointer 'delegate*<object>'
                //         delegate*<ref readonly object> ptr17 = &M5;
                Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M5").WithArguments("C.M5()", "delegate*<object>").WithLocation(29, 49),
                // (30,49): error CS8758: Ref mismatch between 'C.M7()' and function pointer 'delegate*<object>'
                //         delegate*<ref readonly object> ptr18 = &M7;
                Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M7").WithArguments("C.M7()", "delegate*<object>").WithLocation(30, 49)
F
Fredric Silberberg 已提交
3425 3426 3427 3428
            );
        }

        [Theory]
3429 3430 3431
        [InlineData("unmanaged[Cdecl]", "CDecl")]
        [InlineData("unmanaged[Stdcall]", "Standard")]
        [InlineData("unmanaged[Thiscall]", "ThisCall")]
F
Fredric Silberberg 已提交
3432
        public void AddressOf_CallingConventionMustMatch(string callingConventionKeyword, string callingConvention)
F
Fredric Silberberg 已提交
3433 3434 3435 3436
        {
            var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C
{{
F
Fredric Silberberg 已提交
3437 3438
    static void M1() {{}}
    static void M()
F
Fredric Silberberg 已提交
3439
    {{
F
Fredric Silberberg 已提交
3440
        delegate* {callingConventionKeyword}<void> ptr = &M1;
F
Fredric Silberberg 已提交
3441 3442 3443 3444
    }}
}}");

            comp.VerifyDiagnostics(
F
Fredric Silberberg 已提交
3445 3446 3447
                // (7,41): error CS8786: Calling convention of 'C.M1()' is not compatible with '{callingConvention}'.
                //         delegate* {callingConventionKeyword}<void> ptr = &M1;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M1").WithArguments("C.M1()", callingConvention).WithLocation(7, 33 + callingConventionKeyword.Length));
F
Fredric Silberberg 已提交
3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469
        }

        [Fact]
        public void AddressOf_Assignment()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static string Convert(int i) => i.ToString();
    static void Main()
    {
        delegate*<int, string> ptr;
        ptr = &Convert;
        Console.Write(ptr(1));
    }
}", expectedOutput: "1");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       20 (0x14)
  .maxstack  2
3470
  .locals init (delegate*<int, string> V_0)
F
Fredric Silberberg 已提交
3471 3472 3473 3474
  IL_0000:  ldftn      ""string C.Convert(int)""
  IL_0006:  stloc.0
  IL_0007:  ldc.i4.1
  IL_0008:  ldloc.0
3475
  IL_0009:  calli      ""delegate*<int, string>""
F
Fredric Silberberg 已提交
3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502
  IL_000e:  call       ""void System.Console.Write(string)""
  IL_0013:  ret
}");
        }

        [Fact]
        public void AddressOf_NonStaticMethods()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
public class C
{
    public unsafe void M()
    {
        delegate*<void> ptr1 = &M;
        int? i = null;
        delegate*<int> ptr2 = &i.GetValueOrDefault;
    }
}");

            comp.VerifyDiagnostics(
                // (6,33): error CS8759: Cannot bind function pointer to 'C.M()' because it is not a static method
                //         delegate*<void> ptr1 = &M;
                Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "M").WithArguments("C.M()").WithLocation(6, 33),
                // (8,32): error CS8759: Cannot bind function pointer to 'int?.GetValueOrDefault()' because it is not a static method
                //         delegate*<int> ptr2 = &i.GetValueOrDefault;
                Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "i.GetValueOrDefault").WithArguments("int?.GetValueOrDefault()").WithLocation(8, 32)
            );
F
Fredric Silberberg 已提交
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551

            var syntaxTree = comp.SyntaxTrees[0];
            var model = comp.GetSemanticModel(syntaxTree);

            var declarators = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Initializer!.Value.IsKind(SyntaxKind.AddressOfExpression)).ToArray();
            var addressOfs = declarators.Select(d => d.Initializer!.Value).ToArray();
            Assert.Equal(2, addressOfs.Length);

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOfs[0],
                expectedSyntax: "&M",
                expectedType: null,
                expectedConvertedType: "delegate*<System.Void>",
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
                expectedSymbolCandidates: new[] { "void C.M()" });

            VerifyOperationTreeForNode(comp, model, declarators[0], expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.Void> ptr1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'ptr1 = &M')
  Initializer: 
    IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= &M')
      IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.Void>, IsInvalid, IsImplicit) (Syntax: '&M')
        Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
        Operand: 
          IAddressOfOperation (OperationKind.AddressOf, Type: null, IsInvalid) (Syntax: '&M')
            Reference: 
              IOperation:  (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M')
                Children(1):
                    IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
            ");

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOfs[1],
                expectedSyntax: "&i.GetValueOrDefault",
                expectedType: null,
                expectedConvertedType: "delegate*<System.Int32>",
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
                expectedSymbolCandidates: new[] { "System.Int32 System.Int32?.GetValueOrDefault()", "System.Int32 System.Int32?.GetValueOrDefault(System.Int32 defaultValue)" });

            VerifyOperationTreeForNode(comp, model, declarators[1], expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.Int32> ptr2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'ptr2 = &i.G ... ueOrDefault')
  Initializer: 
    IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= &i.GetValueOrDefault')
      IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.Int32>, IsInvalid, IsImplicit) (Syntax: '&i.GetValueOrDefault')
        Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
        Operand: 
          IAddressOfOperation (OperationKind.AddressOf, Type: null, IsInvalid) (Syntax: '&i.GetValueOrDefault')
            Reference: 
              IOperation:  (OperationKind.None, Type: null, IsInvalid) (Syntax: 'i.GetValueOrDefault')
                Children(1):
                    ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32?, IsInvalid) (Syntax: 'i')
            ");
F
Fredric Silberberg 已提交
3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569
        }

        [Fact]
        public void AddressOf_MultipleInvalidOverloads()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
    static int M(string s) => throw null;
    static int M(ref int i) => throw null;

    static void M1()
    {
        delegate*<int, int> ptr = &M;
    }
}");

            comp.VerifyDiagnostics(
3570
                // (9,35): error CS8757: No overload for 'M' matches function pointer 'delegate*<int, int>'
F
Fredric Silberberg 已提交
3571
                //         delegate*<int, int> ptr = &M;
3572
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M").WithArguments("M", "delegate*<int, int>").WithLocation(9, 35)
F
Fredric Silberberg 已提交
3573
            );
F
Fredric Silberberg 已提交
3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600

            var syntaxTree = comp.SyntaxTrees[0];
            var model = comp.GetSemanticModel(syntaxTree);

            var declarator = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
            var addressOf = declarator.Initializer!.Value;

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOf,
                expectedSyntax: "&M",
                expectedType: null,
                expectedConvertedType: "delegate*<System.Int32, System.Int32>",
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
                expectedSymbolCandidates: new[] { "System.Int32 C.M(System.String s)", "System.Int32 C.M(ref System.Int32 i)" });

            VerifyOperationTreeForNode(comp, model, declarator, expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.Int32, System.Int32> ptr) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'ptr = &M')
  Initializer: 
    IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= &M')
      IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.Int32, System.Int32>, IsInvalid, IsImplicit) (Syntax: '&M')
        Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
        Operand: 
          IAddressOfOperation (OperationKind.AddressOf, Type: null, IsInvalid) (Syntax: '&M')
            Reference: 
              IOperation:  (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M')
                Children(1):
                    IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
");
F
Fredric Silberberg 已提交
3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620
        }

        [Fact]
        public void AddressOf_AmbiguousBestMethod()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
    static void M(string s, object o) {}
    static void M(object o, string s) {}
    static void M1()
    {
        delegate*<string, string, void> ptr = &M;
    }
}");
            comp.VerifyDiagnostics(
                // (8,48): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(string, object)' and 'C.M(object, string)'
                //         delegate*<string, string, void> ptr = &M;
                Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(string, object)", "C.M(object, string)").WithLocation(8, 48)
            );
F
Fredric Silberberg 已提交
3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647

            var syntaxTree = comp.SyntaxTrees[0];
            var model = comp.GetSemanticModel(syntaxTree);

            var declarator = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
            var addressOf = declarator.Initializer!.Value;

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOf,
                expectedSyntax: "&M",
                expectedType: null,
                expectedConvertedType: "delegate*<System.String, System.String, System.Void>",
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
                expectedSymbolCandidates: new[] { "void C.M(System.String s, System.Object o)", "void C.M(System.Object o, System.String s)" });

            VerifyOperationTreeForNode(comp, model, declarator, expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.String, System.String, System.Void> ptr) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'ptr = &M')
  Initializer: 
    IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= &M')
      IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.String, System.String, System.Void>, IsInvalid, IsImplicit) (Syntax: '&M')
        Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
        Operand: 
          IAddressOfOperation (OperationKind.AddressOf, Type: null, IsInvalid) (Syntax: '&M')
            Reference: 
              IOperation:  (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M')
                Children(1):
                    IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
");
F
Fredric Silberberg 已提交
3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661
        }

        [Fact]
        public void AddressOf_AsLvalue()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
    static void M() {}
    static void M1()
    {
        delegate*<void> ptr = &M;
        &M = ptr;
        M2(&M);
F
Fredric Silberberg 已提交
3662
        M2(ref &M);
F
Fredric Silberberg 已提交
3663 3664 3665 3666 3667 3668
        ref delegate*<void> ptr2 = ref &M;
    }
    static void M2(ref delegate*<void> ptr) {}
}");

            comp.VerifyDiagnostics(
F
Fredric Silberberg 已提交
3669
                // (8,9): error CS1656: Cannot assign to 'M' because it is a '&method group'
F
Fredric Silberberg 已提交
3670
                //         &M = ptr;
F
Fredric Silberberg 已提交
3671
                Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "&M").WithArguments("M", "&method group").WithLocation(8, 9),
F
Fredric Silberberg 已提交
3672 3673 3674
                // (9,12): error CS1503: Argument 1: cannot convert from '&method group' to 'ref delegate*<void>'
                //         M2(&M);
                Diagnostic(ErrorCode.ERR_BadArgType, "&M").WithArguments("1", "&method group", "ref delegate*<void>").WithLocation(9, 12),
F
Fredric Silberberg 已提交
3675 3676 3677 3678
                // (10,16): error CS1657: Cannot use 'M' as a ref or out value because it is a '&method group'
                //         M2(ref &M);
                Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "&M").WithArguments("M", "&method group").WithLocation(10, 16),
                // (11,40): error CS1657: Cannot use 'M' as a ref or out value because it is a '&method group'
F
Fredric Silberberg 已提交
3679
                //         ref delegate*<void> ptr2 = ref &M;
F
Fredric Silberberg 已提交
3680
                Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "&M").WithArguments("M", "&method group").WithLocation(11, 40)
F
Fredric Silberberg 已提交
3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703
            );
        }

        [Fact]
        public void AddressOf_MethodParameter()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void M(string s) => Console.Write(s);
    static void Caller(delegate*<string, void> ptr) => ptr(""1"");
    static void Main()
    {
        Caller(&M);
    }
}", expectedOutput: "1");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       12 (0xc)
  .maxstack  1
  IL_0000:  ldftn      ""void C.M(string)""
3704
  IL_0006:  call       ""void C.Caller(delegate*<string, void>)""
F
Fredric Silberberg 已提交
3705 3706 3707 3708 3709
  IL_000b:  ret
}
");
        }

F
Fredric Silberberg 已提交
3710
        [Fact]
3711
        [WorkItem(44489, "https://github.com/dotnet/roslyn/issues/44489")]
F
Fredric Silberberg 已提交
3712 3713 3714 3715 3716 3717 3718
        public void AddressOf_CannotAssignToVoidStar()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
    static void M()
    {
3719 3720
        void* ptr1 = &M;
        void* ptr2 = (void*)&M;
F
Fredric Silberberg 已提交
3721 3722 3723 3724
    }
}");

            comp.VerifyDiagnostics(
3725
                // (6,22): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'void*'.
3726 3727
                //         void* ptr1 = &M;
                Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "&M").WithArguments("M", "void*").WithLocation(6, 22),
3728
                // (7,22): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'void*'.
3729 3730
                //         void* ptr2 = (void*)&M;
                Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "(void*)&M").WithArguments("M", "void*").WithLocation(7, 22)
F
Fredric Silberberg 已提交
3731
            );
3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764

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

            var decls = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray();

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, decls[0].Initializer!.Value,
                expectedSyntax: "&M",
                expectedType: null,
                expectedConvertedType: "System.Void*",
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
                expectedSymbolCandidates: new[] { "void C.M()" });

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, ((CastExpressionSyntax)decls[1].Initializer!.Value).Expression,
                expectedSyntax: "&M",
                expectedType: null,
                expectedConvertedType: null,
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
                expectedSymbolCandidates: new[] { "void C.M()" });
        }

        [Fact]
        [WorkItem(44489, "https://github.com/dotnet/roslyn/issues/44489")]
        public void AddressOf_ToDelegateType()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
using System;
class C
{
    unsafe void M()
    {
        // This actually gets bound as a binary expression: (Action) & M
        Action ptr1 = (Action)&M;
F
Fredric Silberberg 已提交
3765 3766
        Action ptr2 = (Action)(&M);
        Action ptr3 = &M;
3767 3768 3769 3770 3771 3772 3773 3774 3775 3776
    }
}");

            comp.VerifyDiagnostics(
                // (8,24): error CS0119: 'Action' is a type, which is not valid in the given context
                //         Action ptr1 = (Action)&M;
                Diagnostic(ErrorCode.ERR_BadSKunknown, "Action").WithArguments("System.Action", "type").WithLocation(8, 24),
                // (8,24): error CS0119: 'Action' is a type, which is not valid in the given context
                //         Action ptr1 = (Action)&M;
                Diagnostic(ErrorCode.ERR_BadSKunknown, "Action").WithArguments("System.Action", "type").WithLocation(8, 24),
3777
                // (9,23): error CS8811: Cannot convert &method group 'M' to delegate type 'M'.
F
Fredric Silberberg 已提交
3778 3779
                //         Action ptr2 = (Action)(&M);
                Diagnostic(ErrorCode.ERR_CannotConvertAddressOfToDelegate, "(Action)(&M)").WithArguments("M", "System.Action").WithLocation(9, 23),
3780
                // (10,23): error CS8811: Cannot convert &method group 'M' to delegate type 'M'.
F
Fredric Silberberg 已提交
3781 3782
                //         Action ptr3 = &M;
                Diagnostic(ErrorCode.ERR_CannotConvertAddressOfToDelegate, "&M").WithArguments("M", "System.Action").WithLocation(10, 23)
3783 3784 3785 3786 3787 3788 3789 3790
            );


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

            var decls = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray();

F
Fredric Silberberg 已提交
3791 3792 3793 3794 3795 3796 3797 3798
            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, ((CastExpressionSyntax)decls[1].Initializer!.Value).Expression,
                expectedSyntax: "(&M)",
                expectedType: null,
                expectedConvertedType: null,
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
                expectedSymbolCandidates: new[] { "void C.M()" });

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, decls[2].Initializer!.Value,
3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816
                expectedSyntax: "&M",
                expectedType: null,
                expectedConvertedType: "System.Action",
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
                expectedSymbolCandidates: new[] { "void C.M()" });
        }

        [Fact]
        [WorkItem(44489, "https://github.com/dotnet/roslyn/issues/44489")]
        public void AddressOf_ToNonDelegateOrPointerType()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
class C
{
    unsafe void M()
    {
        // This actually gets bound as a binary expression: (C) & M
        C ptr1 = (C)&M;
F
Fredric Silberberg 已提交
3817 3818
        C ptr2 = (C)(&M);
        C ptr3 = &M;
3819 3820 3821 3822 3823 3824 3825 3826 3827 3828
    }
}");

            comp.VerifyDiagnostics(
                // (7,19): error CS0119: 'C' is a type, which is not valid in the given context
                //         C ptr1 = (C)&M;
                Diagnostic(ErrorCode.ERR_BadSKunknown, "C").WithArguments("C", "type").WithLocation(7, 19),
                // (7,19): error CS0119: 'C' is a type, which is not valid in the given context
                //         C ptr1 = (C)&M;
                Diagnostic(ErrorCode.ERR_BadSKunknown, "C").WithArguments("C", "type").WithLocation(7, 19),
3829
                // (8,18): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'C'.
F
Fredric Silberberg 已提交
3830 3831
                //         C ptr2 = (C)(&M);
                Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "(C)(&M)").WithArguments("M", "C").WithLocation(8, 18),
3832
                // (9,18): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'C'.
F
Fredric Silberberg 已提交
3833 3834
                //         C ptr3 = &M;
                Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "&M").WithArguments("M", "C").WithLocation(9, 18)
3835 3836 3837 3838 3839 3840 3841
            );

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

            var decls = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray();

F
Fredric Silberberg 已提交
3842 3843 3844 3845 3846 3847 3848 3849
            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, ((CastExpressionSyntax)decls[1].Initializer!.Value).Expression,
                expectedSyntax: "(&M)",
                expectedType: null,
                expectedConvertedType: null,
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
                expectedSymbolCandidates: new[] { "void C.M()" });

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, decls[2].Initializer!.Value,
3850 3851 3852 3853 3854
                expectedSyntax: "&M",
                expectedType: null,
                expectedConvertedType: "C",
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
                expectedSymbolCandidates: new[] { "void C.M()" });
F
Fredric Silberberg 已提交
3855 3856
        }

F
Fredric Silberberg 已提交
3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887
        [Fact]
        public void AddressOf_ExplicitCastToNonCompatibleFunctionPointerType()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
class C
{
    unsafe void M()
    {
        var ptr = (delegate*<string>)&M;
    }
}
");

            comp.VerifyDiagnostics(
                // (6,19): error CS8757: No overload for 'M' matches function pointer 'delegate*<string>'
                //         var ptr = (delegate*<string>)&M;
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<string>)&M").WithArguments("M", "delegate*<string>").WithLocation(6, 19)
            );

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

            var decls = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray();

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, ((CastExpressionSyntax)decls[0].Initializer!.Value).Expression,
                expectedSyntax: "&M",
                expectedType: null,
                expectedConvertedType: null,
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
                expectedSymbolCandidates: new[] { "void C.M()" });
        }
3888

F
Fredric Silberberg 已提交
3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907
        [Fact]
        public void AddressOf_DisallowedInExpressionTree()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
using System;
using System.Linq.Expressions;
unsafe class C
{
    static string M1(delegate*<string> ptr) => ptr();
    static string M2() => string.Empty;

    static void M()
    {
        Expression<Func<string>> a = () => M1(&M2);
        Expression<Func<string>> b = () => (&M2)();
    }
}");

            comp.VerifyDiagnostics(
3908 3909 3910
                // (11,47): error CS1944: An expression tree may not contain an unsafe pointer operation
                //         Expression<Func<string>> a = () => M1(&M2);
                Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "&M2").WithLocation(11, 47),
3911
                // (11,48): error CS8810: '&' on method groups cannot be used in expression trees
F
Fredric Silberberg 已提交
3912 3913 3914 3915 3916 3917 3918 3919
                //         Expression<Func<string>> a = () => M1(&M2);
                Diagnostic(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, "M2").WithLocation(11, 48),
                // (12,44): error CS0149: Method name expected
                //         Expression<Func<string>> b = () => (&M2)();
                Diagnostic(ErrorCode.ERR_MethodNameExpected, "(&M2)").WithLocation(12, 44)
            );
        }

3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942
        [Fact]
        public void FunctionPointerTypeUsageInExpressionTree()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
using System;
using System.Linq.Expressions;
unsafe class C
{
    void M1(delegate*<void> ptr)
    {
        Expression<Action> a = () => M2(ptr);
    }
    void M2(void* ptr) {}
}
");

            comp.VerifyDiagnostics(
                // (8,41): error CS1944: An expression tree may not contain an unsafe pointer operation
                //         Expression<Action> a = () => M2(ptr);
                Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "ptr").WithLocation(8, 41)
            );
        }

F
Fredric Silberberg 已提交
3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967
        [Fact]
        public void AmbiguousApplicableMethodsAreFilteredForStatic()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
interface I1{}
interface I2
{
    string Prop { get; }
}

public unsafe class C : I1, I2 {
    void M(I1 i) {}
    static void M(I2 i) => Console.Write(i.Prop);
    public static void Main() {
        delegate*<C, void> a = &M;
        a(new C());
    }
    public string Prop { get => ""I2""; }
}", expectedOutput: "I2");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       19 (0x13)
  .maxstack  2
3968
  .locals init (delegate*<C, void> V_0)
F
Fredric Silberberg 已提交
3969 3970 3971 3972
  IL_0000:  ldftn      ""void C.M(I2)""
  IL_0006:  stloc.0
  IL_0007:  newobj     ""C..ctor()""
  IL_000c:  ldloc.0
3973
  IL_000d:  calli      ""delegate*<C, void>""
F
Fredric Silberberg 已提交
3974 3975 3976 3977 3978 3979
  IL_0012:  ret
}
");
        }

        [Fact]
F
Fredric Silberberg 已提交
3980
        public void TypeArgumentNotSpecifiedNotInferred()
F
Fredric Silberberg 已提交
3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
    static void M1<T>(int i) {}
    static T M2<T>() => throw null;

    static void M()
    {
        delegate*<int, void> ptr1 = &C.M1;
        delegate*<string> ptr2 = &C.M2;
    }
}");

            comp.VerifyDiagnostics(
                // (9,38): error CS0411: The type arguments for method 'C.M1<T>(int)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
                //         delegate*<int, void> ptr1 = &C.M1;
                Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "C.M1").WithArguments("C.M1<T>(int)").WithLocation(9, 38),
                // (10,35): error CS0411: The type arguments for method 'C.M2<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
                //         delegate*<string> ptr2 = &C.M2;
                Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "C.M2").WithArguments("C.M2<T>()").WithLocation(10, 35)
            );
        }

        [Fact]
F
Fredric Silberberg 已提交
4006
        public void TypeArgumentSpecifiedOrInferred()
F
Fredric Silberberg 已提交
4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void M1<T>(T t) => Console.Write(t);
    static void Main()
    {
        delegate*<int, void> ptr = &C.M1<int>;
        ptr(1);
        ptr = &C.M1;
        ptr(2);
    }
}", expectedOutput: "12");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       29 (0x1d)
  .maxstack  2
4026
  .locals init (delegate*<int, void> V_0)
F
Fredric Silberberg 已提交
4027 4028 4029 4030
  IL_0000:  ldftn      ""void C.M1<int>(int)""
  IL_0006:  stloc.0
  IL_0007:  ldc.i4.1
  IL_0008:  ldloc.0
4031
  IL_0009:  calli      ""delegate*<int, void>""
F
Fredric Silberberg 已提交
4032 4033 4034 4035
  IL_000e:  ldftn      ""void C.M1<int>(int)""
  IL_0014:  stloc.0
  IL_0015:  ldc.i4.2
  IL_0016:  ldloc.0
4036
  IL_0017:  calli      ""delegate*<int, void>""
F
Fredric Silberberg 已提交
4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053
  IL_001c:  ret
}
");
        }

        [Fact]
        public void ReducedExtensionMethod()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe static class CHelper
{
    public static void M1(this C c) {}
}
unsafe class C
{
    static void M(C c)
    {
F
Fredric Silberberg 已提交
4054 4055
        delegate*<C, void> ptr1 = &c.M1;
        delegate*<void> ptr2 = &c.M1;
F
Fredric Silberberg 已提交
4056 4057 4058 4059
    }
}");

            comp.VerifyDiagnostics(
4060
                // (10,35): error CS8757: No overload for 'M1' matches function pointer 'delegate*<C, void>'
F
Fredric Silberberg 已提交
4061
                //         delegate*<C, void> ptr1 = &c.M1;
4062
                Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&c.M1").WithArguments("M1", "delegate*<C, void>").WithLocation(10, 35),
F
Fredric Silberberg 已提交
4063
                // (11,32): error CS8788: Cannot use an extension method with a receiver as the target of a '&amp;' operator.
F
Fredric Silberberg 已提交
4064
                //         delegate*<void> ptr2 = &c.M1;
F
Fredric Silberberg 已提交
4065
                Diagnostic(ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, "&c.M1").WithLocation(11, 32)
F
Fredric Silberberg 已提交
4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095
            );
        }

        [Fact]
        public void UnreducedExtensionMethod()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
#pragma warning suppress CS0414 // Field never used
using System;
unsafe static class CHelper
{
    public static void M1(this C c) => Console.Write(c.i);
}
unsafe class C
{
    public int i;
    static void Main()
    {
        delegate*<C, void> ptr = &CHelper.M1;
        var c = new C();
        c.i = 1;
        ptr(c);
    }
}", expectedOutput: "1");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       28 (0x1c)
  .maxstack  3
  .locals init (C V_0, //c
4096
                delegate*<C, void> V_1)
F
Fredric Silberberg 已提交
4097 4098 4099 4100 4101 4102 4103 4104 4105
  IL_0000:  ldftn      ""void CHelper.M1(C)""
  IL_0006:  newobj     ""C..ctor()""
  IL_000b:  stloc.0
  IL_000c:  ldloc.0
  IL_000d:  ldc.i4.1
  IL_000e:  stfld      ""int C.i""
  IL_0013:  stloc.1
  IL_0014:  ldloc.0
  IL_0015:  ldloc.1
4106
  IL_0016:  calli      ""delegate*<C, void>""
F
Fredric Silberberg 已提交
4107 4108 4109 4110 4111 4112
  IL_001b:  ret
}
");
        }

        [Fact]
F
Fredric Silberberg 已提交
4113
        public void BadScenariosDontCrash()
F
Fredric Silberberg 已提交
4114 4115 4116 4117 4118 4119 4120 4121 4122 4123
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
    static void M1() {}
    static void M2()
    {
        &delegate*<void> ptr = &M1;
    }
}
F
Fredric Silberberg 已提交
4124
");
F
Fredric Silberberg 已提交
4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137

            comp.VerifyDiagnostics(
                // (7,18): error CS1514: { expected
                //         &delegate*<void> ptr = &M1;
                Diagnostic(ErrorCode.ERR_LbraceExpected, "*").WithLocation(7, 18),
                // (7,19): error CS1525: Invalid expression term '<'
                //         &delegate*<void> ptr = &M1;
                Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(7, 19),
                // (7,20): error CS1525: Invalid expression term 'void'
                //         &delegate*<void> ptr = &M1;
                Diagnostic(ErrorCode.ERR_InvalidExprTerm, "void").WithArguments("void").WithLocation(7, 20),
                // (7,26): error CS0103: The name 'ptr' does not exist in the current context
                //         &delegate*<void> ptr = &M1;
F
Fredric Silberberg 已提交
4138 4139 4140 4141 4142
                Diagnostic(ErrorCode.ERR_NameNotInContext, "ptr").WithArguments("ptr").WithLocation(7, 26)
            );
        }

        [Fact]
F
Fredric Silberberg 已提交
4143
        public void EmptyMethodGroups()
F
Fredric Silberberg 已提交
4144 4145 4146 4147
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
F
Fredric Silberberg 已提交
4148
    static void M1()
F
Fredric Silberberg 已提交
4149
    {
F
Fredric Silberberg 已提交
4150 4151
        delegate*<C, void> ptr1 = &C.NonExistent;
        delegate*<C, void> ptr2 = &NonExistent;
F
Fredric Silberberg 已提交
4152 4153
    }
}
F
Fredric Silberberg 已提交
4154
");
F
Fredric Silberberg 已提交
4155 4156

            comp.VerifyDiagnostics(
F
Fredric Silberberg 已提交
4157 4158 4159 4160 4161 4162
                // (6,38): error CS0117: 'C' does not contain a definition for 'NonExistent'
                //         delegate*<C, void> ptr1 = &C.NonExistent;
                Diagnostic(ErrorCode.ERR_NoSuchMember, "NonExistent").WithArguments("C", "NonExistent").WithLocation(6, 38),
                // (7,36): error CS0103: The name 'NonExistent' does not exist in the current context
                //         delegate*<C, void> ptr2 = &NonExistent;
                Diagnostic(ErrorCode.ERR_NameNotInContext, "NonExistent").WithArguments("NonExistent").WithLocation(7, 36)
F
Fredric Silberberg 已提交
4163 4164 4165 4166 4167 4168
            );
        }

        [Fact]
        public void MultipleApplicableMethods()
        {
C
Charles Stoner 已提交
4169
            // This is analogous to MethodBodyModelTests.MethodGroupToDelegate04, where both methods
F
Fredric Silberberg 已提交
4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186
            // are applicable even though D(delegate*<int, void>) is not compatible.
            var comp = CreateCompilationWithFunctionPointers(@"
public unsafe class Program1
{
    static void Y(long x) { }

    static void D(delegate*<int, void> o) { }
    static void D(delegate*<long, void> o) { }

    void T()
    {
        D(&Y);
    }
}
");

            comp.VerifyDiagnostics(
4187
                // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program1.D(delegate*<int, void>)' and 'Program1.D(delegate*<long, void>)'
F
Fredric Silberberg 已提交
4188
                //         D(&Y);
4189
                Diagnostic(ErrorCode.ERR_AmbigCall, "D").WithArguments("Program1.D(delegate*<int, void>)", "Program1.D(delegate*<long, void>)").WithLocation(11, 9)
F
Fredric Silberberg 已提交
4190 4191 4192
            );
        }

F
Fredric Silberberg 已提交
4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251
        [Fact]
        public void InvalidTopAttributeErrors()
        {

            using var peStream = new MemoryStream();
            var ilBuilder = new BlobBuilder();
            var metadataBuilder = new MetadataBuilder();
            // SignatureAttributes has the following values:
            // 0x00 - default
            // 0x10 - Generic
            // 0x20 - Instance
            // 0x40 - ExplicitThis
            // There is no defined meaning for 0x80, the 8th bit here, so this signature is invalid.
            // ldftn throws an invalid signature exception at runtime, so we error here for function
            // pointers.
            DefineInvalidSignatureAttributeIL(metadataBuilder, ilBuilder, headerToUseForM: new SignatureHeader(SignatureKind.Method, SignatureCallingConvention.Default, ((SignatureAttributes)0x80)));
            WritePEImage(peStream, metadataBuilder, ilBuilder);
            peStream.Position = 0;

            var invalidAttributeReference = MetadataReference.CreateFromStream(peStream);
            var comp = CreateCompilationWithFunctionPointers(@"
using ConsoleApplication;
unsafe class C
{
    static void Main()
    {
        delegate*<void> ptr = &Program.M;
    }
}", references: new[] { invalidAttributeReference });

            comp.VerifyEmitDiagnostics(
                // (7,32): error CS8776: Calling convention of 'Program.M()' is not compatible with 'Default'.
                //         delegate*<void> ptr = &Program.M;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "Program.M").WithArguments("ConsoleApplication.Program.M()", "Default").WithLocation(7, 32)
            );
        }

        [Fact]
        public void MissingAddressOf()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
class C
{
    static void M1() {}
    static unsafe void M2(delegate*<void> b)
    {
        delegate*<void> a = M1;
        M2(M1);
    }
}");

            comp.VerifyDiagnostics(
                // (7,29): error CS8787: Cannot convert method group to function pointer (Are you missing a '&'?)
                //         delegate*<void> a = M1;
                Diagnostic(ErrorCode.ERR_MissingAddressOf, "M1").WithLocation(7, 29),
                // (8,12): error CS8787: Cannot convert method group to function pointer (Are you missing a '&'?)
                //         M2(M1);
                Diagnostic(ErrorCode.ERR_MissingAddressOf, "M1").WithLocation(8, 12)
            );
F
Fredric Silberberg 已提交
4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265

            var syntaxTree = comp.SyntaxTrees[0];
            var model = comp.GetSemanticModel(syntaxTree);

            var variableDeclaratorSyntax = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();

            var methodGroup1 = variableDeclaratorSyntax.Initializer!.Value;
            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, methodGroup1,
                expectedSyntax: "M1",
                expectedType: null,
                expectedConvertedType: "delegate*<System.Void>",
                expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
                expectedSymbolCandidates: new[] { "void C.M1()" });

F
Fredric Silberberg 已提交
4266 4267
            AssertEx.Equal(new[] { "void C.M1()" }, model.GetMemberGroup(methodGroup1).Select(m => m.ToTestDisplayString(includeNonNullable: false)));

F
Fredric Silberberg 已提交
4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278
            VerifyOperationTreeForNode(comp, model, variableDeclaratorSyntax, expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.Void> a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = M1')
  Initializer: 
    IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= M1')
      IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.Void>, IsInvalid, IsImplicit) (Syntax: 'M1')
        Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
        Operand: 
          IOperation:  (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
            Children(1):
                IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M1')
");
F
Fredric Silberberg 已提交
4279 4280
        }

4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301
        [Fact]
        public void NestedFunctionPointerVariantConversion()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    public static void Printer(object o) => Console.Write(o);
    public static void PrintWrapper(delegate*<string, void> printer, string o) => printer(o);
    static void Main()
    {
        delegate*<delegate*<object, void>, string, void> wrapper = &PrintWrapper;
        delegate*<object, void> printer = &Printer;
        wrapper(printer, ""1""); 
    }
}", expectedOutput: "1");

            verifier.VerifyIL("C.Main()", expectedIL: @"
{
  // Code size       27 (0x1b)
  .maxstack  3
4302 4303 4304
  .locals init (delegate*<object, void> V_0, //printer
                delegate*<delegate*<object, void>, string, void> V_1)
  IL_0000:  ldftn      ""void C.PrintWrapper(delegate*<string, void>, string)""
4305 4306 4307 4308 4309 4310
  IL_0006:  ldftn      ""void C.Printer(object)""
  IL_000c:  stloc.0
  IL_000d:  stloc.1
  IL_000e:  ldloc.0
  IL_000f:  ldstr      ""1""
  IL_0014:  ldloc.1
4311
  IL_0015:  calli      ""delegate*<delegate*<object, void>, string, void>""
4312 4313 4314 4315 4316
  IL_001a:  ret
}
");
        }

4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338
        [Fact]
        public void ArraysSupport()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    public static void M(string s) => Console.Write(s);
    public static void Main()
    {
        delegate*<string, void>[] ptrs = new delegate*<string, void>[] { &M, &M };
        for (int i = 0; i < ptrs.Length; i++)
        {
            ptrs[i](i.ToString());
        }
    }
}", expectedOutput: "01");

            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       57 (0x39)
  .maxstack  4
4339
  .locals init (delegate*<string, void>[] V_0, //ptrs
4340
                int V_1, //i
4341
                delegate*<string, void> V_2)
4342
  IL_0000:  ldc.i4.2
4343
  IL_0001:  newarr     ""delegate*<string, void>""
4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362
  IL_0006:  dup
  IL_0007:  ldc.i4.0
  IL_0008:  ldftn      ""void C.M(string)""
  IL_000e:  stelem.i
  IL_000f:  dup
  IL_0010:  ldc.i4.1
  IL_0011:  ldftn      ""void C.M(string)""
  IL_0017:  stelem.i
  IL_0018:  stloc.0
  IL_0019:  ldc.i4.0
  IL_001a:  stloc.1
  IL_001b:  br.s       IL_0032
  IL_001d:  ldloc.0
  IL_001e:  ldloc.1
  IL_001f:  ldelem.i
  IL_0020:  stloc.2
  IL_0021:  ldloca.s   V_1
  IL_0023:  call       ""string int.ToString()""
  IL_0028:  ldloc.2
4363
  IL_0029:  calli      ""delegate*<string, void>""
4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377
  IL_002e:  ldloc.1
  IL_002f:  ldc.i4.1
  IL_0030:  add
  IL_0031:  stloc.1
  IL_0032:  ldloc.1
  IL_0033:  ldloc.0
  IL_0034:  ldlen
  IL_0035:  conv.i4
  IL_0036:  blt.s      IL_001d
  IL_0038:  ret
}
");
        }

F
Fredric Silberberg 已提交
4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445
        [Fact]
        public void ArrayElementRef()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    public static void Print() => Console.Write(1);

    public static void M(delegate*<void>[] a)
    {
        ref delegate*<void> ptr = ref a[0];
        ptr = &Print;
    }
    
    public static void Main()
    {
        var a = new delegate*<void>[1];
        M(a);
        a[0]();
    }
}");

            verifier.VerifyIL("C.M", expectedIL: @"
{
  // Code size       15 (0xf)
  .maxstack  2
  IL_0000:  ldarg.0
  IL_0001:  ldc.i4.0
  IL_0002:  ldelema    ""delegate*<void>""
  IL_0007:  ldftn      ""void C.Print()""
  IL_000d:  stind.i
  IL_000e:  ret
}
");

            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       20 (0x14)
  .maxstack  2
  IL_0000:  ldc.i4.1
  IL_0001:  newarr     ""delegate*<void>""
  IL_0006:  dup
  IL_0007:  call       ""void C.M(delegate*<void>[])""
  IL_000c:  ldc.i4.0
  IL_000d:  ldelem.i
  IL_000e:  calli      ""delegate*<void>""
  IL_0013:  ret
}
");
        }

        [Fact]
        public void FixedSizeBufferOfFunctionPointers()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe struct S
{
    fixed delegate*<void> ptrs[1];
}");

            comp.VerifyDiagnostics(
                // (4,11): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double
                //     fixed delegate*<void> ptrs[1];
                Diagnostic(ErrorCode.ERR_IllegalFixedType, "delegate*<void>").WithLocation(4, 11)
            );
        }

4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461
        [Fact]
        public void IndirectLoadsAndStores()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static delegate*<void> field;
    static void Printer() => Console.Write(1);
    static ref delegate*<void> Getter() => ref field;

    static void Main()
    {
        ref var printer = ref Getter();
        printer = &Printer;
        printer();
F
Fredric Silberberg 已提交
4462
        field();
4463
    }
F
Fredric Silberberg 已提交
4464
}", expectedOutput: "11");
4465 4466 4467

            verifier.VerifyIL(@"C.Main", expectedIL: @"
{
F
Fredric Silberberg 已提交
4468
  // Code size       30 (0x1e)
4469 4470 4471 4472 4473 4474 4475
  .maxstack  3
  IL_0000:  call       ""ref delegate*<void> C.Getter()""
  IL_0005:  dup
  IL_0006:  ldftn      ""void C.Printer()""
  IL_000c:  stind.i
  IL_000d:  ldind.i
  IL_000e:  calli      ""delegate*<void>""
F
Fredric Silberberg 已提交
4476 4477 4478
  IL_0013:  ldsfld     ""delegate*<void> C.field""
  IL_0018:  calli      ""delegate*<void>""
  IL_001d:  ret
4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506
}
");
        }

        [Fact]
        public void Foreach()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    public static void M(string s) => Console.Write(s);
    public static void Main()
    {
        delegate*<string, void>[] ptrs = new delegate*<string, void>[] { &M, &M };
        int i = 0;
        foreach (delegate*<string, void> ptr in ptrs)
        {
            ptr(i++.ToString());
        }
    }
}", expectedOutput: "01");

            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       66 (0x42)
  .maxstack  4
  .locals init (int V_0, //i
4507
                delegate*<string, void>[] V_1,
4508
                int V_2,
4509
                delegate*<string, void> V_3,
4510 4511
                int V_4)
  IL_0000:  ldc.i4.2
4512
  IL_0001:  newarr     ""delegate*<string, void>""
4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539
  IL_0006:  dup
  IL_0007:  ldc.i4.0
  IL_0008:  ldftn      ""void C.M(string)""
  IL_000e:  stelem.i
  IL_000f:  dup
  IL_0010:  ldc.i4.1
  IL_0011:  ldftn      ""void C.M(string)""
  IL_0017:  stelem.i
  IL_0018:  ldc.i4.0
  IL_0019:  stloc.0
  IL_001a:  stloc.1
  IL_001b:  ldc.i4.0
  IL_001c:  stloc.2
  IL_001d:  br.s       IL_003b
  IL_001f:  ldloc.1
  IL_0020:  ldloc.2
  IL_0021:  ldelem.i
  IL_0022:  stloc.3
  IL_0023:  ldloc.0
  IL_0024:  dup
  IL_0025:  ldc.i4.1
  IL_0026:  add
  IL_0027:  stloc.0
  IL_0028:  stloc.s    V_4
  IL_002a:  ldloca.s   V_4
  IL_002c:  call       ""string int.ToString()""
  IL_0031:  ldloc.3
4540
  IL_0032:  calli      ""delegate*<string, void>""
4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554
  IL_0037:  ldloc.2
  IL_0038:  ldc.i4.1
  IL_0039:  add
  IL_003a:  stloc.2
  IL_003b:  ldloc.2
  IL_003c:  ldloc.1
  IL_003d:  ldlen
  IL_003e:  conv.i4
  IL_003f:  blt.s      IL_001f
  IL_0041:  ret
}
");
        }

F
Fredric Silberberg 已提交
4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582
        [Fact]
        public void FieldInitializers()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    delegate*<string, void>[] arr1;
    delegate*<string, void>[] arr2 = new delegate*<string, void>[1];
    static void Print(string s) => Console.Write(s);
    static void Main()
    {
        var c = new C()
        {
            arr1 = new delegate*<string, void>[] { &Print },
            arr2 = { [0] = &Print }
        };

        c.arr1[0](""1"");
        c.arr2[0](""2"");
    }
}", expectedOutput: "12");

            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       82 (0x52)
  .maxstack  5
  .locals init (C V_0,
4583
                delegate*<string, void> V_1)
F
Fredric Silberberg 已提交
4584 4585 4586 4587
  IL_0000:  newobj     ""C..ctor()""
  IL_0005:  stloc.0
  IL_0006:  ldloc.0
  IL_0007:  ldc.i4.1
4588
  IL_0008:  newarr     ""delegate*<string, void>""
F
Fredric Silberberg 已提交
4589 4590 4591 4592
  IL_000d:  dup
  IL_000e:  ldc.i4.0
  IL_000f:  ldftn      ""void C.Print(string)""
  IL_0015:  stelem.i
4593
  IL_0016:  stfld      ""delegate*<string, void>[] C.arr1""
F
Fredric Silberberg 已提交
4594
  IL_001b:  ldloc.0
4595
  IL_001c:  ldfld      ""delegate*<string, void>[] C.arr2""
F
Fredric Silberberg 已提交
4596 4597 4598 4599 4600
  IL_0021:  ldc.i4.0
  IL_0022:  ldftn      ""void C.Print(string)""
  IL_0028:  stelem.i
  IL_0029:  ldloc.0
  IL_002a:  dup
4601
  IL_002b:  ldfld      ""delegate*<string, void>[] C.arr1""
F
Fredric Silberberg 已提交
4602 4603 4604 4605 4606
  IL_0030:  ldc.i4.0
  IL_0031:  ldelem.i
  IL_0032:  stloc.1
  IL_0033:  ldstr      ""1""
  IL_0038:  ldloc.1
4607 4608
  IL_0039:  calli      ""delegate*<string, void>""
  IL_003e:  ldfld      ""delegate*<string, void>[] C.arr2""
F
Fredric Silberberg 已提交
4609 4610 4611 4612 4613
  IL_0043:  ldc.i4.0
  IL_0044:  ldelem.i
  IL_0045:  stloc.1
  IL_0046:  ldstr      ""2""
  IL_004b:  ldloc.1
4614
  IL_004c:  calli      ""delegate*<string, void>""
F
Fredric Silberberg 已提交
4615 4616 4617 4618 4619
  IL_0051:  ret
}
");
        }

4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638
        [Fact]
        public void InitializeFunctionPointerWithNull()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void Main()
    {
         delegate*<string, void>[] ptrs = new delegate*<string, void>[] { null, null, null }; 
         Console.Write(ptrs[0] is null);
    }
}", expectedOutput: "True");

            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       32 (0x20)
  .maxstack  4
  IL_0000:  ldc.i4.3
4639
  IL_0001:  newarr     ""delegate*<string, void>""
4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664
  IL_0006:  dup
  IL_0007:  ldc.i4.0
  IL_0008:  ldc.i4.0
  IL_0009:  conv.u
  IL_000a:  stelem.i
  IL_000b:  dup
  IL_000c:  ldc.i4.1
  IL_000d:  ldc.i4.0
  IL_000e:  conv.u
  IL_000f:  stelem.i
  IL_0010:  dup
  IL_0011:  ldc.i4.2
  IL_0012:  ldc.i4.0
  IL_0013:  conv.u
  IL_0014:  stelem.i
  IL_0015:  ldc.i4.0
  IL_0016:  ldelem.i
  IL_0017:  ldnull
  IL_0018:  ceq
  IL_001a:  call       ""void System.Console.Write(bool)""
  IL_001f:  ret
}
");
        }

F
Fredric Silberberg 已提交
4665
        [Fact]
F
Fredric Silberberg 已提交
4666
        public void InferredArrayInitializer_ParameterVariance()
F
Fredric Silberberg 已提交
4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void Print(object o) => Console.Write(o);
    static void Print(string s) => Console.Write(s);
    static void Main()
    {
        delegate*<string, void> ptr1 = &Print;
        delegate*<object, void> ptr2 = &Print;
        var ptrs = new[] { ptr1, ptr2 }; 
        ptrs[0](""1"");
        ptrs[1](""2"");
    }
}", expectedOutput: "12");

            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       58 (0x3a)
  .maxstack  4
4688 4689 4690
  .locals init (delegate*<string, void> V_0, //ptr1
                delegate*<object, void> V_1, //ptr2
                delegate*<string, void> V_2)
F
Fredric Silberberg 已提交
4691 4692 4693 4694 4695
  IL_0000:  ldftn      ""void C.Print(string)""
  IL_0006:  stloc.0
  IL_0007:  ldftn      ""void C.Print(object)""
  IL_000d:  stloc.1
  IL_000e:  ldc.i4.2
4696
  IL_000f:  newarr     ""delegate*<string, void>""
F
Fredric Silberberg 已提交
4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710
  IL_0014:  dup
  IL_0015:  ldc.i4.0
  IL_0016:  ldloc.0
  IL_0017:  stelem.i
  IL_0018:  dup
  IL_0019:  ldc.i4.1
  IL_001a:  ldloc.1
  IL_001b:  stelem.i
  IL_001c:  dup
  IL_001d:  ldc.i4.0
  IL_001e:  ldelem.i
  IL_001f:  stloc.2
  IL_0020:  ldstr      ""1""
  IL_0025:  ldloc.2
4711
  IL_0026:  calli      ""delegate*<string, void>""
F
Fredric Silberberg 已提交
4712 4713 4714 4715 4716
  IL_002b:  ldc.i4.1
  IL_002c:  ldelem.i
  IL_002d:  stloc.2
  IL_002e:  ldstr      ""2""
  IL_0033:  ldloc.2
4717
  IL_0034:  calli      ""delegate*<string, void>""
F
Fredric Silberberg 已提交
4718 4719 4720 4721 4722 4723
  IL_0039:  ret
}
");
        }

        [Fact]
F
Fredric Silberberg 已提交
4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783
        public void InferredArrayInitializer_ReturnVariance()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static object GetObject() => 1.ToString();
    static string GetString() => 2.ToString();
    static void Print(delegate*<object>[] ptrs)
    {
        Console.Write(""Object"");
        foreach (var ptr in ptrs)
        {
            Console.Write(ptr());
        }
    }
    static void Print(delegate*<string>[] ptrs)
    {
        Console.Write(""String"");
        foreach (var ptr in ptrs)
        {
            Console.Write(ptr());
        }
    }
    static void Main()
    {
        delegate*<object> ptr1 = &GetObject;
        delegate*<string> ptr2 = &GetString;
        Print(new[] { ptr1, ptr2 });
    }
}", expectedOutput: "Object12");

            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       34 (0x22)
  .maxstack  4
  .locals init (delegate*<object> V_0, //ptr1
                delegate*<string> V_1) //ptr2
  IL_0000:  ldftn      ""object C.GetObject()""
  IL_0006:  stloc.0
  IL_0007:  ldftn      ""string C.GetString()""
  IL_000d:  stloc.1
  IL_000e:  ldc.i4.2
  IL_000f:  newarr     ""delegate*<object>""
  IL_0014:  dup
  IL_0015:  ldc.i4.0
  IL_0016:  ldloc.0
  IL_0017:  stelem.i
  IL_0018:  dup
  IL_0019:  ldc.i4.1
  IL_001a:  ldloc.1
  IL_001b:  stelem.i
  IL_001c:  call       ""void C.Print(delegate*<object>[])""
  IL_0021:  ret
}
");
        }

        [Fact]
        public void BestTypeForConditional_ParameterVariance()
F
Fredric Silberberg 已提交
4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void Print(object o) => Console.Write(o + ""Object"");
    static void Print(string s) => Console.Write(s + ""String"");
    static void M(bool b)
    {
        delegate*<object, void> ptr1 = &Print;
        delegate*<string, void> ptr2 = &Print;
F
Fredric Silberberg 已提交
4795
        var ptr3 = b ? ptr1 : ptr2;
F
Fredric Silberberg 已提交
4796
        ptr3(""1"");
F
Fredric Silberberg 已提交
4797 4798
        ptr3 = b ? ptr2 : ptr1;
        ptr3(""2"");
F
Fredric Silberberg 已提交
4799 4800
    }
    static void Main() => M(true);
F
Fredric Silberberg 已提交
4801
}", expectedOutput: "1Object2String");
F
Fredric Silberberg 已提交
4802 4803 4804

            verifier.VerifyIL("C.M", expectedIL: @"
{
F
Fredric Silberberg 已提交
4805
  // Code size       53 (0x35)
F
Fredric Silberberg 已提交
4806
  .maxstack  2
4807 4808 4809
  .locals init (delegate*<object, void> V_0, //ptr1
                delegate*<string, void> V_1, //ptr2
                delegate*<string, void> V_2)
F
Fredric Silberberg 已提交
4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821
  IL_0000:  ldftn      ""void C.Print(object)""
  IL_0006:  stloc.0
  IL_0007:  ldftn      ""void C.Print(string)""
  IL_000d:  stloc.1
  IL_000e:  ldarg.0
  IL_000f:  brtrue.s   IL_0014
  IL_0011:  ldloc.1
  IL_0012:  br.s       IL_0015
  IL_0014:  ldloc.0
  IL_0015:  stloc.2
  IL_0016:  ldstr      ""1""
  IL_001b:  ldloc.2
4822
  IL_001c:  calli      ""delegate*<string, void>""
F
Fredric Silberberg 已提交
4823 4824 4825 4826 4827 4828 4829 4830
  IL_0021:  ldarg.0
  IL_0022:  brtrue.s   IL_0027
  IL_0024:  ldloc.0
  IL_0025:  br.s       IL_0028
  IL_0027:  ldloc.1
  IL_0028:  stloc.2
  IL_0029:  ldstr      ""2""
  IL_002e:  ldloc.2
4831
  IL_002f:  calli      ""delegate*<string, void>""
F
Fredric Silberberg 已提交
4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936
  IL_0034:  ret
}
");
        }

        [Fact]
        public void BestTypeForConditional_ReturnVariance()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static object GetObject() => 1.ToString();
    static string GetString() => 2.ToString();
    static void Print(delegate*<object> ptr)
    {
        Console.Write(ptr());
        Console.Write(""Object"");
    }
    static void Print(delegate*<string> ptr)
    {
        Console.Write(ptr());
        Console.Write(""String"");
    }
    static void M(bool b)
    {
        delegate*<object> ptr1 = &GetObject;
        delegate*<string> ptr2 = &GetString;
        Print(b ? ptr1 : ptr2);
        Print(b ? ptr2 : ptr1);
    }
    static void Main() => M(true);
}", expectedOutput: "1Object2Object");

            verifier.VerifyIL("C.M", expectedIL: @"
{
  // Code size       39 (0x27)
  .maxstack  1
  .locals init (delegate*<object> V_0, //ptr1
                delegate*<string> V_1) //ptr2
  IL_0000:  ldftn      ""object C.GetObject()""
  IL_0006:  stloc.0
  IL_0007:  ldftn      ""string C.GetString()""
  IL_000d:  stloc.1
  IL_000e:  ldarg.0
  IL_000f:  brtrue.s   IL_0014
  IL_0011:  ldloc.1
  IL_0012:  br.s       IL_0015
  IL_0014:  ldloc.0
  IL_0015:  call       ""void C.Print(delegate*<object>)""
  IL_001a:  ldarg.0
  IL_001b:  brtrue.s   IL_0020
  IL_001d:  ldloc.0
  IL_001e:  br.s       IL_0021
  IL_0020:  ldloc.1
  IL_0021:  call       ""void C.Print(delegate*<object>)""
  IL_0026:  ret
}
");
        }

        [Fact]
        public void BestTypeForConditional_NestedParameterVariance()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void Print(object o)
    {
        Console.Write(o);
    }
    static void PrintObject(delegate*<object, void> ptr, string o)
    {
        ptr(o);
    }
    static void PrintString(delegate*<string, void> ptr, string s)
    {
        ptr(s);
    }
    static void Invoke(delegate*<delegate*<object, void>, string, void> ptr, string s)
    {
        Console.Write(""Object"");
        delegate*<object, void> print = &Print;
        ptr(print, s);
    }
    static void Invoke(delegate*<delegate*<string, void>, string, void> ptr, string s)
    {
        Console.Write(""String"");
        delegate*<string, void> print = &Print;
        ptr(print, s);
    }
    static void M(bool b)
    {
        delegate*<delegate*<object, void>, string, void> printObject = &PrintObject;
        delegate*<delegate*<string, void>, string, void> printString = &PrintString;
        Invoke(b ? printObject : printString, ""1"");
    }
    static void Main() => M(true);
}", expectedOutput: "Object1");

            verifier.VerifyIL("C.M", expectedIL: @"
{
  // Code size       32 (0x20)
  .maxstack  2
4937 4938 4939
  .locals init (delegate*<delegate*<object, void>, string, void> V_0, //printObject
                delegate*<delegate*<string, void>, string, void> V_1) //printString
  IL_0000:  ldftn      ""void C.PrintObject(delegate*<object, void>, string)""
F
Fredric Silberberg 已提交
4940
  IL_0006:  stloc.0
4941
  IL_0007:  ldftn      ""void C.PrintString(delegate*<string, void>, string)""
F
Fredric Silberberg 已提交
4942 4943 4944 4945 4946 4947 4948
  IL_000d:  stloc.1
  IL_000e:  ldarg.0
  IL_000f:  brtrue.s   IL_0014
  IL_0011:  ldloc.1
  IL_0012:  br.s       IL_0015
  IL_0014:  ldloc.0
  IL_0015:  ldstr      ""1""
4949
  IL_001a:  call       ""void C.Invoke(delegate*<delegate*<object, void>, string, void>, string)""
F
Fredric Silberberg 已提交
4950
  IL_001f:  ret
F
Fredric Silberberg 已提交
4951 4952 4953 4954
}
");
        }

4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000
        [Fact]
        public void BestTypeForConditional_NestedParameterRef()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void Print(ref object o1, object o2)
    {
        o1 = o2;
    }
    static void PrintObject(delegate*<ref object, object, void> ptr, ref object o, object arg)
    {
        ptr(ref o, arg);
    }
    static void PrintString(delegate*<ref object, string, void> ptr, ref object o, string arg)
    {
        ptr(ref o, arg);
    }
    static void Invoke(delegate*<delegate*<ref object, object, void>, ref object, string, void> ptr, ref object s, object arg)
    {
        Console.Write(""Object"");
        delegate*<ref object, object, void> print = &Print;
        ptr(print, ref s, arg.ToString());
    }
    static void Invoke(delegate*<delegate*<ref object, string, void>, ref object, string, void> ptr, ref object s, string arg)
    {
        Console.Write(""String"");
        delegate*<ref object, string, void> print = &Print;
        ptr(print, ref s, arg);
    }
    static void M(bool b)
    {
        delegate*<delegate*<ref object, object, void>, ref object, string, void> printObject1 = &PrintObject;
        delegate*<delegate*<ref object, string, void>, ref object, string, void> printObject2 = &PrintString;
        object o = null;
        Invoke(b ? printObject1 : printObject2, ref o, ""1"");
        Console.Write(o);
    }
    static void Main() => M(true);
}", expectedOutput: "Object1");

            verifier.VerifyIL("C.M", expectedIL: @"
{
  // Code size       42 (0x2a)
  .maxstack  3
5001 5002
  .locals init (delegate*<delegate*<ref object, object, void>, ref object, string, void> V_0, //printObject1
                delegate*<delegate*<ref object, string, void>, ref object, string, void> V_1, //printObject2
5003
                object V_2) //o
5004
  IL_0000:  ldftn      ""void C.PrintObject(delegate*<ref object, object, void>, ref object, object)""
5005
  IL_0006:  stloc.0
5006
  IL_0007:  ldftn      ""void C.PrintString(delegate*<ref object, string, void>, ref object, string)""
5007 5008 5009 5010 5011 5012 5013 5014 5015 5016
  IL_000d:  stloc.1
  IL_000e:  ldnull
  IL_000f:  stloc.2
  IL_0010:  ldarg.0
  IL_0011:  brtrue.s   IL_0016
  IL_0013:  ldloc.1
  IL_0014:  br.s       IL_0017
  IL_0016:  ldloc.0
  IL_0017:  ldloca.s   V_2
  IL_0019:  ldstr      ""1""
5017
  IL_001e:  call       ""void C.Invoke(delegate*<delegate*<ref object, object, void>, ref object, string, void>, ref object, object)""
5018 5019 5020 5021 5022 5023 5024
  IL_0023:  ldloc.2
  IL_0024:  call       ""void System.Console.Write(object)""
  IL_0029:  ret
}
");
        }

5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050
        [Fact]
        public void DefaultOfFunctionPointerType()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void Main()
    {
        delegate*<void> ptr = default;
        Console.Write(ptr is null);
    }
}", expectedOutput: "True");

            verifier.VerifyIL("C.Main", @"
{
  // Code size       11 (0xb)
  .maxstack  2
  IL_0000:  ldc.i4.0
  IL_0001:  conv.u
  IL_0002:  ldnull
  IL_0003:  ceq
  IL_0005:  call       ""void System.Console.Write(bool)""
  IL_000a:  ret
}
");
F
Fredric Silberberg 已提交
5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065

            var comp = (CSharpCompilation)verifier.Compilation;
            var syntaxTree = comp.SyntaxTrees[0];
            var model = comp.GetSemanticModel(syntaxTree);

            FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model,
                syntaxTree.GetRoot()
                    .DescendantNodes()
                    .OfType<LiteralExpressionSyntax>()
                    .Where(l => l.IsKind(SyntaxKind.DefaultLiteralExpression))
                    .Single(),
                expectedSyntax: "default",
                expectedType: "delegate*<System.Void>",
                expectedSymbol: null,
                expectedSymbolCandidates: null);
5066 5067
        }

5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099
        [Fact]
        public void ParamsArrayOfFunctionPointers()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class C
{
    static void Params(params delegate*<void>[] funcs)
    {
        foreach (var f in funcs)
        {
            f();
        }
    }

    static void Main()
    {
        Params();
    }
}", expectedOutput: "");

            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       12 (0xc)
  .maxstack  1
  IL_0000:  ldc.i4.0
  IL_0001:  newarr     ""delegate*<void>""
  IL_0006:  call       ""void C.Params(params delegate*<void>[])""
  IL_000b:  ret
}
");
        }

5100
        [Fact]
F
Fredric Silberberg 已提交
5101
        public void StackallocOfFunctionPointers()
5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
static unsafe class C
{
    static int Getter(int i) => i;
    static void Print(delegate*<int, int>* p)
    {
        for (int i = 0; i < 3; i++)
            Console.Write(p[i](i));
    }

    static void Main()
    {
        delegate*<int, int>* p = stackalloc delegate*<int, int>[] { &Getter, &Getter, &Getter };
        Print(p);
    }
}
", expectedOutput: "012");

            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       58 (0x3a)
  .maxstack  4
  IL_0000:  ldc.i4.3
  IL_0001:  conv.u
5128
  IL_0002:  sizeof     ""delegate*<int, int>""
5129 5130 5131 5132 5133 5134
  IL_0008:  mul.ovf.un
  IL_0009:  localloc
  IL_000b:  dup
  IL_000c:  ldftn      ""int C.Getter(int)""
  IL_0012:  stind.i
  IL_0013:  dup
5135
  IL_0014:  sizeof     ""delegate*<int, int>""
5136 5137 5138 5139 5140 5141
  IL_001a:  add
  IL_001b:  ldftn      ""int C.Getter(int)""
  IL_0021:  stind.i
  IL_0022:  dup
  IL_0023:  ldc.i4.2
  IL_0024:  conv.i
5142
  IL_0025:  sizeof     ""delegate*<int, int>""
5143 5144 5145 5146
  IL_002b:  mul
  IL_002c:  add
  IL_002d:  ldftn      ""int C.Getter(int)""
  IL_0033:  stind.i
5147
  IL_0034:  call       ""void C.Print(delegate*<int, int>*)""
5148 5149 5150 5151 5152
  IL_0039:  ret
}
");
        }

F
Fredric Silberberg 已提交
5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164
        [Fact]
        public void FunctionPointerCannotBeUsedAsSpanArgument()
        {
            var comp = CreateCompilationWithSpan(@"
using System;
static unsafe class C
{
    static void Main()
    {
        Span<delegate*<int, int>> p = stackalloc delegate*<int, int>[1];
    }
}
5165
", options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9);
F
Fredric Silberberg 已提交
5166 5167

            comp.VerifyDiagnostics(
5168
                // (7,14): error CS0306: The type 'delegate*<int, int>' may not be used as a type argument
F
Fredric Silberberg 已提交
5169
                //         Span<delegate*<int, int>> p = stackalloc delegate*<int, int>[1];
5170
                Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate*<int, int>").WithArguments("delegate*<int, int>").WithLocation(7, 14)
F
Fredric Silberberg 已提交
5171 5172 5173
            );
        }

5174
        [Fact]
5175
        public void RecursivelyUsedTypeInFunctionPointer()
5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
namespace Interop
{
    public unsafe struct PROPVARIANT
    {
        public CAPROPVARIANT ca;
    }
    public unsafe struct CAPROPVARIANT
    {
        public uint cElems;
        public delegate*<PROPVARIANT> pElems;
        public delegate*<PROPVARIANT> pElemsProp { get; }
    }
}");
        }

5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206
        [Fact]
        public void VolatileFunctionPointerField()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static volatile delegate*<void> ptr;
    static void Print() => Console.Write(1);
    static void Main()
    {
        ptr = &Print;
        ptr();
    }
F
Fredric Silberberg 已提交
5207
}", expectedOutput: "1");
5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223

            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       26 (0x1a)
  .maxstack  1
  IL_0000:  ldftn      ""void C.Print()""
  IL_0006:  volatile.
  IL_0008:  stsfld     ""delegate*<void> C.ptr""
  IL_000d:  volatile.
  IL_000f:  ldsfld     ""delegate*<void> C.ptr""
  IL_0014:  calli      ""delegate*<void>""
  IL_0019:  ret
}
");
        }

5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443
        [Fact]
        public void SupportedBinaryOperators()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static (bool, bool, bool, bool, bool, bool) DoCompare(delegate*<void> func_1a, delegate*<string, void> func_1b)
    {
        return (func_1a == func_1b,
                func_1a != func_1b,
                func_1a > func_1b,
                func_1a >= func_1b,
                func_1a < func_1b,
                func_1a <= func_1b);
    }

    static void M(delegate*<void> func_1a, delegate*<string, void> func_1b, delegate*<int> func_2, int* int_1, int* int_2)
    {
        var compareResults = DoCompare(func_1a, func_1b);
        Console.WriteLine(""func_1a == func_1b: "" + compareResults.Item1);
        Console.WriteLine(""func_1a != func_1b: "" + compareResults.Item2);
        Console.WriteLine(""func_1a > func_1b: "" + compareResults.Item3);
        Console.WriteLine(""func_1a >= func_1b: "" + compareResults.Item4);
        Console.WriteLine(""func_1a < func_1b: "" + compareResults.Item5);
        Console.WriteLine(""func_1a <= func_1b: "" + compareResults.Item6);
        Console.WriteLine(""func_1a == func_2: "" + (func_1a == func_2));
        Console.WriteLine(""func_1a != func_2: "" + (func_1a != func_2));
        Console.WriteLine(""func_1a > func_2: "" + (func_1a > func_2));
        Console.WriteLine(""func_1a >= func_2: "" + (func_1a >= func_2));
        Console.WriteLine(""func_1a < func_2: "" + (func_1a < func_2));
        Console.WriteLine(""func_1a <= func_2: "" + (func_1a <= func_2));
        Console.WriteLine(""func_1a == int_1: "" + (func_1a == int_1));
        Console.WriteLine(""func_1a != int_1: "" + (func_1a != int_1));
        Console.WriteLine(""func_1a > int_1: "" + (func_1a > int_1));
        Console.WriteLine(""func_1a >= int_1: "" + (func_1a >= int_1));
        Console.WriteLine(""func_1a < int_1: "" + (func_1a < int_1));
        Console.WriteLine(""func_1a <= int_1: "" + (func_1a <= int_1));
        Console.WriteLine(""func_1a == int_2: "" + (func_1a == int_2));
        Console.WriteLine(""func_1a != int_2: "" + (func_1a != int_2));
        Console.WriteLine(""func_1a > int_2: "" + (func_1a > int_2));
        Console.WriteLine(""func_1a >= int_2: "" + (func_1a >= int_2));
        Console.WriteLine(""func_1a < int_2: "" + (func_1a < int_2));
        Console.WriteLine(""func_1a <= int_2: "" + (func_1a <= int_2));
    }

    static void Main()
    {
        delegate*<void> func_1a = (delegate*<void>)1;
        delegate*<string, void> func_1b = (delegate*<string, void>)1;
        delegate*<int> func_2 = (delegate*<int>)2;
        int* int_1 = (int*)1;
        int* int_2 = (int*)2;
        M(func_1a, func_1b, func_2, int_1, int_2);
    }
}", expectedOutput: @"
func_1a == func_1b: True
func_1a != func_1b: False
func_1a > func_1b: False
func_1a >= func_1b: True
func_1a < func_1b: False
func_1a <= func_1b: True
func_1a == func_2: False
func_1a != func_2: True
func_1a > func_2: False
func_1a >= func_2: False
func_1a < func_2: True
func_1a <= func_2: True
func_1a == int_1: True
func_1a != int_1: False
func_1a > int_1: False
func_1a >= int_1: True
func_1a < int_1: False
func_1a <= int_1: True
func_1a == int_2: False
func_1a != int_2: True
func_1a > int_2: False
func_1a >= int_2: False
func_1a < int_2: True
func_1a <= int_2: True");

            verifier.VerifyIL("C.DoCompare", expectedIL: @"
{
  // Code size       39 (0x27)
  .maxstack  7
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  ceq
  IL_0004:  ldarg.0
  IL_0005:  ldarg.1
  IL_0006:  ceq
  IL_0008:  ldc.i4.0
  IL_0009:  ceq
  IL_000b:  ldarg.0
  IL_000c:  ldarg.1
  IL_000d:  cgt.un
  IL_000f:  ldarg.0
  IL_0010:  ldarg.1
  IL_0011:  clt.un
  IL_0013:  ldc.i4.0
  IL_0014:  ceq
  IL_0016:  ldarg.0
  IL_0017:  ldarg.1
  IL_0018:  clt.un
  IL_001a:  ldarg.0
  IL_001b:  ldarg.1
  IL_001c:  cgt.un
  IL_001e:  ldc.i4.0
  IL_001f:  ceq
  IL_0021:  newobj     ""System.ValueTuple<bool, bool, bool, bool, bool, bool>..ctor(bool, bool, bool, bool, bool, bool)""
  IL_0026:  ret
}
");
        }

        [Theory]
        [InlineData("+")]
        [InlineData("-")]
        [InlineData("*")]
        [InlineData("/")]
        [InlineData("%")]
        [InlineData("<<")]
        [InlineData(">>")]
        [InlineData("&&")]
        [InlineData("||")]
        [InlineData("&")]
        [InlineData("|")]
        [InlineData("^")]
        public void UnsupportedBinaryOps(string op)
        {
            bool isLogical = op == "&&" || op == "||";
            var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C
{{
    static void M(delegate*<void> ptr1, delegate*<void> ptr2, int* ptr3)
    {{
        _ = ptr1 {op} ptr2;
        _ = ptr1 {op} ptr3;
        _ = ptr1 {op} 1;
        {(isLogical ? "" : $@"ptr1 {op}= ptr2;
        ptr1 {op}= ptr3;
        ptr1 {op}= 1;")}
    }}
}}");

            var expectedDiagnostics = ArrayBuilder<DiagnosticDescription>.GetInstance();
            expectedDiagnostics.AddRange(
                // (6,13): error CS0019: Operator 'op' cannot be applied to operands of type 'delegate*<void>' and 'delegate*<void>'
                //         _ = ptr1 op ptr2;
                Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op} ptr2").WithArguments(op, "delegate*<void>", "delegate*<void>").WithLocation(6, 13),
                // (7,13): error CS0019: Operator 'op' cannot be applied to operands of type 'delegate*<void>' and 'int*'
                //         _ = ptr1 op ptr3;
                Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op} ptr3").WithArguments(op, "delegate*<void>", "int*").WithLocation(7, 13),
                // (8,13): error CS0019: Operator 'op' cannot be applied to operands of type 'delegate*<void>' and 'int'
                //         _ = ptr1 op 1;
                Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op} 1").WithArguments(op, "delegate*<void>", "int").WithLocation(8, 13));

            if (!isLogical)
            {
                expectedDiagnostics.AddRange(
                    // (9,9): error CS0019: Operator 'op=' cannot be applied to operands of type 'delegate*<void>' and 'delegate*<void>'
                    //         ptr1 op= ptr2;
                    Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op}= ptr2").WithArguments($"{op}=", "delegate*<void>", "delegate*<void>").WithLocation(9, 9),
                    // (10,9): error CS0019: Operator 'op=' cannot be applied to operands of type 'delegate*<void>' and 'int*'
                    //         ptr1 op= ptr3;
                    Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op}= ptr3").WithArguments($"{op}=", "delegate*<void>", "int*").WithLocation(10, 9),
                    // (11,9): error CS0019: Operator 'op=' cannot be applied to operands of type 'delegate*<void>' and 'int'
                    //         ptr1 op= 1;
                    Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op}= 1").WithArguments($"{op}=", "delegate*<void>", "int").WithLocation(11, 9));
            }

            comp.VerifyDiagnostics(expectedDiagnostics.ToArrayAndFree());
        }

        [Theory]
        [InlineData("+")]
        [InlineData("++")]
        [InlineData("-")]
        [InlineData("--")]
        [InlineData("!")]
        [InlineData("~")]
        public void UnsupportedPrefixUnaryOps(string op)
        {
            var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C
{{
    public static void M(delegate*<void> ptr)
    {{
        _ = {op}ptr;
    }}
}}");

            comp.VerifyDiagnostics(
                // (6,13): error CS0023: Operator 'op' cannot be applied to operand of type 'delegate*<void>'
                //         _ = {op}ptr;
                Diagnostic(ErrorCode.ERR_BadUnaryOp, $"{op}ptr").WithArguments(op, "delegate*<void>").WithLocation(6, 13)
            );
        }

        [Theory]
        [InlineData("++")]
        [InlineData("--")]
        public void UnsupportedPostfixUnaryOps(string op)
        {
            var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C
{{
    public static void M(delegate*<void> ptr)
    {{
        _ = ptr{op};
    }}
}}");

            comp.VerifyDiagnostics(
                // (6,13): error CS0023: Operator 'op' cannot be applied to operand of type 'delegate*<void>'
                //         _ = ptr{op};
                Diagnostic(ErrorCode.ERR_BadUnaryOp, $"ptr{op}").WithArguments(op, "delegate*<void>").WithLocation(6, 13)
            );
        }

F
Fredric Silberberg 已提交
5444
        [Fact]
5445
        public void FunctionPointerReturnTypeConstrainedCallVirtIfRef()
5446
        {
F
Fredric Silberberg 已提交
5447 5448 5449 5450 5451 5452 5453 5454 5455 5456
            var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class C
{
    void M1() {}
    void M<T>(delegate*<ref T> ptr1, delegate*<T> ptr2) where T : C
    {
        ptr1().M1();
        ptr2().M1();
    }
}");
5457

F
Fredric Silberberg 已提交
5458 5459 5460 5461 5462
            verifier.VerifyIL(@"C.M<T>(delegate*<T>, delegate*<T>)", @"
{
  // Code size       34 (0x22)
  .maxstack  1
  IL_0000:  ldarg.1
5463
  IL_0001:  calli      ""delegate*<ref T>""
F
Fredric Silberberg 已提交
5464 5465 5466 5467 5468 5469 5470 5471 5472
  IL_0006:  constrained. ""T""
  IL_000c:  callvirt   ""void C.M1()""
  IL_0011:  ldarg.2
  IL_0012:  calli      ""delegate*<T>""
  IL_0017:  box        ""T""
  IL_001c:  callvirt   ""void C.M1()""
  IL_0021:  ret
}
");
5473 5474
        }

5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512
        [Fact]
        public void NullableAnnotationsInMetadata()
        {
            var source = @"
public unsafe class C
{
    public delegate*<string, object, C> F1;
    public delegate*<string?, object, C> F2;
    public delegate*<string, object?, C> F3;
    public delegate*<string, object, C?> F4;
    public delegate*<string?, object?, C?> F5;
    public delegate*<delegate*<string, int*>, delegate*<string?>, delegate*<void*, string>> F6;
}";

            var comp = CreateCompilationWithFunctionPointers(source, options: WithNonNullTypesTrue(TestOptions.UnsafeReleaseDll));
            comp.VerifyDiagnostics();

            verifySymbolNullabilities(comp.GetTypeByMetadataName("C")!);

            CompileAndVerify(comp, symbolValidator: symbolValidator);

            static void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetTypeMember("C");
                Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 1, 1, 1})", getAttribute("F1"));
                Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 1, 2, 1})", getAttribute("F2"));
                Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 1, 1, 2})", getAttribute("F3"));
                Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 2, 1, 1})", getAttribute("F4"));
                Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 2, 2, 2})", getAttribute("F5"));
                Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 0, 1, 0, 0, 0, 1, 0, 2})", getAttribute("F6"));

                verifySymbolNullabilities(c);

                string getAttribute(string fieldName) => c.GetField(fieldName).GetAttributes().Single().ToString()!;
            }

            static void verifySymbolNullabilities(NamedTypeSymbol c)
            {
5513 5514 5515 5516 5517 5518 5519 5520
                assertExpected("delegate*<System.String!, System.Object!, C!>", "F1");
                assertExpected("delegate*<System.String?, System.Object!, C!>", "F2");
                assertExpected("delegate*<System.String!, System.Object?, C!>", "F3");
                assertExpected("delegate*<System.String!, System.Object!, C?>", "F4");
                assertExpected("delegate*<System.String?, System.Object?, C?>", "F5");
                assertExpected("delegate*<delegate*<System.String!, System.Int32*>, delegate*<System.String?>, delegate*<System.Void*, System.String!>>", "F6");

                void assertExpected(string expectedType, string fieldName)
5521
                {
5522 5523 5524
                    var type = (FunctionPointerTypeSymbol)c.GetField(fieldName).Type;
                    CommonVerifyFunctionPointer(type);
                    Assert.Equal(expectedType, type.ToTestDisplayString(includeNonNullable: true));
5525 5526 5527 5528
                }
            }
        }

5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542
        [Theory]
        [InlineData("delegate*<Z, Z, (Z a, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})")]
        [InlineData("delegate*<(Z a, Z b), Z, Z>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})")]
        [InlineData("delegate*<Z, (Z a, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})")]
        [InlineData("delegate*<(Z c, Z d), (Z e, Z f), (Z a, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b"", ""c"", ""d"", ""e"", ""f""})")]
        [InlineData("delegate*<(Z, Z), (Z, Z), (Z a, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b"", null, null, null, null})")]
        [InlineData("delegate*<(Z, Z), (Z, Z), (Z a, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", null, null, null, null, null})")]
        [InlineData("delegate*<(Z, Z), (Z, Z), (Z, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, ""b"", null, null, null, null})")]
        [InlineData("delegate*<(Z c, Z d), (Z, Z), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, ""c"", ""d"", null, null})")]
        [InlineData("delegate*<(Z c, Z), (Z, Z), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, ""c"", null, null, null})")]
        [InlineData("delegate*<(Z, Z d), (Z, Z), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, null, ""d"", null, null})")]
        [InlineData("delegate*<(Z, Z), (Z e, Z f), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, null, null, ""e"", ""f""})")]
        [InlineData("delegate*<(Z, Z), (Z e, Z), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, null, null, ""e"", null})")]
        [InlineData("delegate*<(Z, Z), (Z, Z f), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, null, null, null, ""f""})")]
5543 5544 5545
        [InlineData("delegate*<(Z a, (Z b, Z c) d), (Z e, Z f)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""e"", ""f"", ""a"", ""d"", ""b"", ""c""})")]
        [InlineData("delegate*<(Z a, Z b), ((Z c, Z d) e, Z f)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""e"", ""f"", ""c"", ""d"", ""a"", ""b""})")]
        [InlineData("delegate*<delegate*<(Z a, Z b), Z>, delegate*<Z, (Z d, Z e)>>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""d"", ""e"", ""a"", ""b""})")]
5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575
        [InlineData("delegate*<(Z, Z), (Z, Z), (Z, Z)>", null)]
        public void TupleNamesInMetadata(string type, string? expectedAttribute)
        {
            var comp = CompileAndVerifyFunctionPointers($@"
#pragma warning disable CS0649 // Unassigned field
unsafe class Z
{{
    public {type} F;
}}
", symbolValidator: symbolValidator);

            void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetTypeMember("Z");

                var field = c.GetField("F");
                if (expectedAttribute == null)
                {
                    Assert.Empty(field.GetAttributes());
                }
                else
                {
                    Assert.Equal(expectedAttribute, field.GetAttributes().Single().ToString());
                }

                CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)field.Type);
                Assert.Equal(type, field.Type.ToTestDisplayString());
            }
        }

5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602
        [Fact]
        public void DynamicTypeAttributeInMetadata()
        {
            var comp = CompileAndVerifyFunctionPointers(@"
#pragma warning disable CS0649 // Unassigned field
unsafe class C
{
    public delegate*<dynamic, dynamic, dynamic> F1;

    public delegate*<object, object, dynamic> F2;
    public delegate*<dynamic, object, object> F3;
    public delegate*<object, dynamic, object> F4;

    public delegate*<object, object, object> F5;

    public delegate*<object, object, ref dynamic> F6;
    public delegate*<ref dynamic, object, object> F7;
    public delegate*<object, ref dynamic, object> F8;

    public delegate*<ref object, ref object, dynamic> F9;
    public delegate*<dynamic, ref object, ref object> F10;
    public delegate*<ref object, dynamic, ref object> F11;

    public delegate*<object, ref readonly dynamic> F12;
    public delegate*<in dynamic, object> F13;

    public delegate*<out dynamic, object> F14;
F
Fredric Silberberg 已提交
5603 5604

    public D<delegate*<dynamic>[], dynamic> F15;
5605 5606

    public delegate*<A<object>.B<dynamic>> F16;
5607
}
F
Fredric Silberberg 已提交
5608
class D<T, U> { }
5609 5610 5611 5612
class A<T>
{
    public class B<U> {}
}
5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639
", symbolValidator: symbolValidator);

            void symbolValidator(ModuleSymbol module)
            {
                var c = module.GlobalNamespace.GetTypeMember("C");

                assertField("F1", "System.Runtime.CompilerServices.DynamicAttribute({false, true, true, true})", "delegate*<dynamic, dynamic, dynamic>");

                assertField("F2", "System.Runtime.CompilerServices.DynamicAttribute({false, true, false, false})", "delegate*<System.Object, System.Object, dynamic>");
                assertField("F3", "System.Runtime.CompilerServices.DynamicAttribute({false, false, true, false})", "delegate*<dynamic, System.Object, System.Object>");
                assertField("F4", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true})", "delegate*<System.Object, dynamic, System.Object>");

                assertField("F5", null, "delegate*<System.Object, System.Object, System.Object>");

                assertField("F6", "System.Runtime.CompilerServices.DynamicAttribute({false, false, true, false, false})", "delegate*<System.Object, System.Object, ref dynamic>");
                assertField("F7", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true, false})", "delegate*<ref dynamic, System.Object, System.Object>");
                assertField("F8", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, true})", "delegate*<System.Object, ref dynamic, System.Object>");

                assertField("F9", "System.Runtime.CompilerServices.DynamicAttribute({false, true, false, false, false, false})", "delegate*<ref System.Object, ref System.Object, dynamic>");
                assertField("F10", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true, false, false})", "delegate*<dynamic, ref System.Object, ref System.Object>");
                assertField("F11", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, false, true})", "delegate*<ref System.Object, dynamic, ref System.Object>");

                assertField("F12", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true, false})", "delegate*<System.Object, ref readonly modreq(System.Runtime.InteropServices.InAttribute) dynamic>");
                assertField("F13", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, true})", "delegate*<in modreq(System.Runtime.InteropServices.InAttribute) dynamic, System.Object>");

                assertField("F14", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, true})", "delegate*<out modreq(System.Runtime.InteropServices.OutAttribute) dynamic, System.Object>");

F
Fredric Silberberg 已提交
5640 5641 5642
                // https://github.com/dotnet/roslyn/issues/44160 tracks fixing this. We're not encoding dynamic correctly for function pointers as type parameters
                assertField("F15", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true})", "D<delegate*<System.Object>[], System.Object>");

5643 5644
                assertField("F16", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true})", "delegate*<A<System.Object>.B<dynamic>>");

5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656
                void assertField(string field, string? expectedAttribute, string expectedType)
                {
                    var f = c.GetField(field);
                    if (expectedAttribute is null)
                    {
                        Assert.Empty(f.GetAttributes());
                    }
                    else
                    {
                        Assert.Equal(expectedAttribute, f.GetAttributes().Single().ToString());
                    }

F
Fredric Silberberg 已提交
5657 5658 5659 5660
                    if (f.Type is FunctionPointerTypeSymbol ptrType)
                    {
                        CommonVerifyFunctionPointer(ptrType);
                    }
5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696
                    Assert.Equal(expectedType, f.Type.ToTestDisplayString());
                }
            }
        }

        [Fact]
        public void DynamicOverriddenWithCustomModifiers()
        {
            var il = @"
.class public A
{
  .method public hidebysig newslot virtual
    instance void M(method class [mscorlib]System.Object modopt([mscorlib]System.Object) & modopt([mscorlib]System.Object) modreq([mscorlib]System.Runtime.InteropServices.InAttribute) *(class [mscorlib]System.Object modopt([mscorlib]System.Object)) a) managed
  {
    .param [1]
    .custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 08 00 00 00 00 00 00 00 00 01 00 01 00 00 ) 
    ret
  }
  .method public hidebysig specialname rtspecialname 
    instance void .ctor () cil managed 
  {
    ldarg.0
    call instance void [mscorlib]System.Object::.ctor()
    ret
  }
}
";

            var source = @"
unsafe class B : A
{
    public override void M(delegate*<dynamic, ref readonly dynamic> a) {}
}";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, symbolValidator: symbolValidator);

F
Fredric Silberberg 已提交
5697
            static void symbolValidator(ModuleSymbol module)
5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718
            {
                var b = module.GlobalNamespace.GetTypeMember("B");

                var m = b.GetMethod("M");
                var param = m.Parameters.Single();
                Assert.Equal("System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, false, true, false, true})", param.GetAttributes().Single().ToString());

                CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)param.Type);
                Assert.Equal("delegate*<dynamic modopt(System.Object), ref readonly modreq(System.Runtime.InteropServices.InAttribute) modopt(System.Object) dynamic modopt(System.Object)>", param.Type.ToTestDisplayString());
            }
        }

        [Fact]
        public void BadDynamicAttributes()
        {
            var il = @"
.class public A
{
  .method public hidebysig static void TooManyFlags(method class [mscorlib]System.Object *(class [mscorlib]System.Object) a)
  {
    .param [1]
F
Fredric Silberberg 已提交
5719
    //{false, true, true, true}
5720 5721 5722 5723 5724 5725
    .custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 ) 
    ret
  }
  .method public hidebysig static void TooFewFlags_MissingParam(method class [mscorlib]System.Object *(class [mscorlib]System.Object) a)
  {
    .param [1]
F
Fredric Silberberg 已提交
5726
    //{false, true}
5727 5728 5729 5730 5731 5732
    .custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) 
    ret
  }
  .method public hidebysig static void TooFewFlags_MissingReturn(method class [mscorlib]System.Object *(class [mscorlib]System.Object) a)
  {
    .param [1]
F
Fredric Silberberg 已提交
5733
    //{false}
5734 5735 5736 5737 5738 5739
    .custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) 
    ret
  }
  .method public hidebysig static void PtrTypeIsTrue(method class [mscorlib]System.Object *(class [mscorlib]System.Object) a)
  {
    .param [1]
F
Fredric Silberberg 已提交
5740
    //{true, true, true}
5741 5742 5743 5744 5745 5746
    .custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 01 01 01 00 00 ) 
    ret
  }
  .method public hidebysig static void NonObjectIsTrue(method class [mscorlib]System.String *(class [mscorlib]System.Object) a)
  {
    .param [1]
F
Fredric Silberberg 已提交
5747
    //{false, true, true}
5748 5749 5750 5751 5752 5753
    .custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 00 01 01 00 00 ) 
    ret
  }
  .method public hidebysig static void RefIsTrue_Return(method class [mscorlib]System.Object& *(class [mscorlib]System.Object) a)
  {
    .param [1]
F
Fredric Silberberg 已提交
5754
    //{false, true, true, true}
5755 5756 5757 5758 5759 5760
    .custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 ) 
    ret
  }
  .method public hidebysig static void RefIsTrue_Param(method class [mscorlib]System.Object *(class [mscorlib]System.Object&) a)
  {
    .param [1]
F
Fredric Silberberg 已提交
5761
    //{false, true, true, true}
5762 5763 5764 5765 5766 5767
    .custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 ) 
    ret
  }
  .method public hidebysig static void ModIsTrue_Return(method class [mscorlib]System.Object modopt([mscorlib]System.Object) *(class [mscorlib]System.Object) a)
  {
    .param [1]
F
Fredric Silberberg 已提交
5768
    //{false, true, true, true}
5769 5770 5771 5772 5773 5774
    .custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 ) 
    ret
  }
  .method public hidebysig static void ModIsTrue_Param(method class [mscorlib]System.Object *(class [mscorlib]System.Object modopt([mscorlib]System.Object)) a)
  {
    .param [1]
F
Fredric Silberberg 已提交
5775
    //{false, true, true, true}
5776 5777 5778 5779 5780 5781
    .custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 ) 
    ret
  }
  .method public hidebysig static void ModIsTrue_RefReturn(method class [mscorlib]System.Object & modopt([mscorlib]System.Object) *(class [mscorlib]System.Object) a)
  {
    .param [1]
F
Fredric Silberberg 已提交
5782
    //{false, false, true, true, true}
5783 5784 5785 5786 5787 5788
    .custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 05 00 00 00 00 00 01 01 01 00 00 ) 
    ret
  }
  .method public hidebysig static void ModIsTrue_RefParam(method class [mscorlib]System.Object *(class [mscorlib]System.Object & modopt([mscorlib]System.Object)) a)
  {
    .param [1]
F
Fredric Silberberg 已提交
5789
    //{false, true, false, true, true}
5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820
    .custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 05 00 00 00 00 01 00 01 01 00 00 ) 
    ret
  }
}
";

            var comp = CreateCompilationWithFunctionPointersAndIl("", il);

            var a = comp.GetTypeByMetadataName("A");

            assert("TooManyFlags", "delegate*<System.Object, System.Object>");
            assert("TooFewFlags_MissingParam", "delegate*<System.Object, System.Object>");
            assert("TooFewFlags_MissingReturn", "delegate*<System.Object, System.Object>");
            assert("PtrTypeIsTrue", "delegate*<System.Object, System.Object>");
            assert("NonObjectIsTrue", "delegate*<System.Object, System.String>");
            assert("RefIsTrue_Return", "delegate*<System.Object, ref System.Object>");
            assert("RefIsTrue_Param", "delegate*<ref System.Object, System.Object>");
            assert("ModIsTrue_Return", "delegate*<System.Object, System.Object modopt(System.Object)>");
            assert("ModIsTrue_Param", "delegate*<System.Object modopt(System.Object), System.Object>");
            assert("ModIsTrue_RefReturn", "delegate*<System.Object, ref modopt(System.Object) System.Object>");
            assert("ModIsTrue_RefParam", "delegate*<ref modopt(System.Object) System.Object, System.Object>");

            void assert(string methodName, string expectedType)
            {
                var method = a.GetMethod(methodName);
                var param = method.Parameters.Single();
                CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)param.Type);
                Assert.Equal(expectedType, param.Type.ToTestDisplayString());
            }
        }

5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969
        [Fact]
        public void BetterFunctionMember_BreakTiesByCustomModifierCount_TypeMods()
        {
            var il = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static 
        void RetModifiers (method void modopt([mscorlib]System.Object) modopt([mscorlib]System.Object) *()) cil managed 
    {
        ldstr ""M""
        call void [mscorlib]System.Console::Write(string)
        ret
    }

    .method public hidebysig static 
        void RetModifiers (method void modopt([mscorlib]System.Object) *()) cil managed 
    {
        ldstr ""L""
        call void [mscorlib]System.Console::Write(string)
        ret
    }

    .method public hidebysig static 
        void ParamModifiers (method void *(int32 modopt([mscorlib]System.Object) modopt([mscorlib]System.Object))) cil managed 
    {
        ldstr ""M""
        call void [mscorlib]System.Console::Write(string)
        ret
    }

    .method public hidebysig static 
        void ParamModifiers (method void *(int32) modopt([mscorlib]System.Object)) cil managed 
    {
        ldstr ""L""
        call void [mscorlib]System.Console::Write(string)
        ret
    }
}";

            var source = @"
unsafe class C
{
    static void Main()
    {
        delegate*<void> ptr1 = null;
        Program.RetModifiers(ptr1);
        delegate*<int, void> ptr2 = null;
        Program.ParamModifiers(ptr2);
    }
}";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, expectedOutput: "LL");
            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       19 (0x13)
  .maxstack  1
  .locals init (delegate*<void> V_0, //ptr1
                delegate*<int, void> V_1) //ptr2
  IL_0000:  ldc.i4.0
  IL_0001:  conv.u
  IL_0002:  stloc.0
  IL_0003:  ldloc.0
  IL_0004:  call       ""void Program.RetModifiers(delegate*<void>)""
  IL_0009:  ldc.i4.0
  IL_000a:  conv.u
  IL_000b:  stloc.1
  IL_000c:  ldloc.1
  IL_000d:  call       ""void Program.ParamModifiers(delegate*<int, void>)""
  IL_0012:  ret
}
            ");
        }

        [Fact]
        public void BetterFunctionMember_BreakTiesByCustomModifierCount_Ref()
        {
            var il = @"
.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static 
        void RetModifiers (method int32 & modopt([mscorlib]System.Object) modopt([mscorlib]System.Object) *()) cil managed 
    {
        ldstr ""M""
        call void [mscorlib]System.Console::Write(string)
        ret
    }

    .method public hidebysig static 
        void RetModifiers (method int32 & modopt([mscorlib]System.Object) *()) cil managed 
    {
        ldstr ""L""
        call void [mscorlib]System.Console::Write(string)
        ret
    }

    .method public hidebysig static 
        void ParamModifiers (method void *(int32 & modopt([mscorlib]System.Object) modopt([mscorlib]System.Object))) cil managed 
    {
        ldstr ""M""
        call void [mscorlib]System.Console::Write(string)
        ret
    }

    .method public hidebysig static 
        void ParamModifiers (method void *(int32 & modopt([mscorlib]System.Object))) cil managed 
    {
        ldstr ""L""
        call void [mscorlib]System.Console::Write(string)
        ret
    }
}
";

            var source = @"
unsafe class C
{
    static void Main()
    {
        delegate*<ref int> ptr1 = null;
        Program.RetModifiers(ptr1);
        delegate*<ref int, void> ptr2 = null;
        Program.ParamModifiers(ptr2);
    }
}";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, expectedOutput: "LL");
            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       19 (0x13)
  .maxstack  1
  .locals init (delegate*<ref int> V_0, //ptr1
                delegate*<ref int, void> V_1) //ptr2
  IL_0000:  ldc.i4.0
  IL_0001:  conv.u
  IL_0002:  stloc.0
  IL_0003:  ldloc.0
  IL_0004:  call       ""void Program.RetModifiers(delegate*<ref int>)""
  IL_0009:  ldc.i4.0
  IL_000a:  conv.u
  IL_000b:  stloc.1
  IL_000c:  ldloc.1
  IL_000d:  call       ""void Program.ParamModifiers(delegate*<ref int, void>)""
  IL_0012:  ret
}
");
F
Fredric Silberberg 已提交
5970
        }
5971

5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243
        [Fact]
        public void Overloading_ReturnTypes()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void M(delegate*<void> ptr) => ptr();
    static void M(delegate*<object> ptr) => Console.WriteLine(ptr());
    static void M(delegate*<string> ptr) => Console.WriteLine(ptr());
    static void Ptr_Void() => Console.WriteLine(""Void"");
    static object Ptr_Obj() => ""Object"";
    static string Ptr_Str() => ""String"";

    static void Main()
    {
        M(&Ptr_Void);
        M(&Ptr_Obj);
        M(&Ptr_Str);
    }
}
", expectedOutput: @"
Void
Object
String");

            verifier.VerifyIL("C.Main", @"
{
  // Code size       34 (0x22)
  .maxstack  1
  IL_0000:  ldftn      ""void C.Ptr_Void()""
  IL_0006:  call       ""void C.M(delegate*<void>)""
  IL_000b:  ldftn      ""object C.Ptr_Obj()""
  IL_0011:  call       ""void C.M(delegate*<object>)""
  IL_0016:  ldftn      ""string C.Ptr_Str()""
  IL_001c:  call       ""void C.M(delegate*<string>)""
  IL_0021:  ret
}
");
        }

        [Fact]
        public void Overloading_ValidReturnRefness()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static object field = ""R"";
    static void M(delegate*<object> ptr) => Console.WriteLine(ptr());
    static void M(delegate*<ref object> ptr)
    {
        Console.Write(field);
        ref var local = ref ptr();
        local = ""ef"";
        Console.WriteLine(field);
    }
    static object Ptr_NonRef() => ""NonRef"";
    static ref object Ptr_Ref() => ref field;

    static void Main()
    {
        M(&Ptr_NonRef);
        M(&Ptr_Ref);
    }
}
", expectedOutput: @"
NonRef
Ref");

            verifier.VerifyIL("C.Main", @"
{
  // Code size       23 (0x17)
  .maxstack  1
  IL_0000:  ldftn      ""object C.Ptr_NonRef()""
  IL_0006:  call       ""void C.M(delegate*<object>)""
  IL_000b:  ldftn      ""ref object C.Ptr_Ref()""
  IL_0011:  call       ""void C.M(delegate*<ref object>)""
  IL_0016:  ret
}
");
        }

        [Fact]
        public void Overloading_InvalidReturnRefness()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C<T>
{
    static void M1(delegate*<ref readonly object> ptr) => throw null;
    static void M1(delegate*<ref object> ptr) => throw null;

    static void M2(C<delegate*<ref readonly object>[]> c) => throw null;
    static void M2(C<delegate*<ref object>[]> c) => throw null;
}
");

            comp.VerifyDiagnostics(
                // (5,17): error CS0111: Type 'C<T>' already defines a member called 'M1' with the same parameter types
                //     static void M1(delegate*<ref object> ptr) => throw null;
                Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M1").WithArguments("M1", "C<T>").WithLocation(5, 17),
                // (8,17): error CS0111: Type 'C<T>' already defines a member called 'M2' with the same parameter types
                //     static void M2(C<delegate*<ref object>[]> c) => throw null;
                Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M2").WithArguments("M2", "C<T>").WithLocation(8, 17)
            );
        }

        [Fact]
        public void Overloading_ReturnNoBetterFunction()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
interface I1 {}
interface I2 {}
unsafe class C : I1, I2
{
    static void M1(delegate*<I1> ptr) => throw null;
    static void M1(delegate*<I2> ptr) => throw null;

    static void M2(delegate*<C> ptr)
    {
        M1(ptr);
    }
}
");

            comp.VerifyDiagnostics(
                // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M1(delegate*<I1>)' and 'C.M1(delegate*<I2>)'
                //         M1(ptr);
                Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("C.M1(delegate*<I1>)", "C.M1(delegate*<I2>)").WithLocation(11, 9)
            );
        }

        [Fact]
        public void Overloading_ParameterTypes()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static void M(delegate*<object, void> ptr) => ptr(""Object"");
    static void M(delegate*<string, void> ptr) => ptr(""String"");

    static void Main()
    {
        delegate*<object, void> ptr1 = &Console.WriteLine;
        delegate*<string, void> ptr2 = &Console.WriteLine;
        M(ptr1);
        M(ptr2);
    }
}
", expectedOutput: @"
Object
String");

            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       25 (0x19)
  .maxstack  2
  .locals init (delegate*<string, void> V_0) //ptr2
  IL_0000:  ldftn      ""void System.Console.WriteLine(object)""
  IL_0006:  ldftn      ""void System.Console.WriteLine(string)""
  IL_000c:  stloc.0
  IL_000d:  call       ""void C.M(delegate*<object, void>)""
  IL_0012:  ldloc.0
  IL_0013:  call       ""void C.M(delegate*<string, void>)""
  IL_0018:  ret
}
");
        }

        [Fact]
        public void Overloading_ValidParameterRefness()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
    static object field = ""R"";
    static void M(delegate*<ref object, void> ptr)
    {
        Console.Write(field);
        ref var local = ref field;
        ptr(ref local);
        Console.WriteLine(field);
    }
    static void M(delegate*<object, void> ptr) => ptr(""NonRef"");

    static void Ptr(ref object param) => param = ""ef"";

    static void Main()
    {
        M(&Console.WriteLine);
        M(&Ptr);
    }
}
", expectedOutput: @"
NonRef
Ref");

            verifier.VerifyIL("C.Main", expectedIL: @"
{
  // Code size       23 (0x17)
  .maxstack  1
  IL_0000:  ldftn      ""void System.Console.WriteLine(object)""
  IL_0006:  call       ""void C.M(delegate*<object, void>)""
  IL_000b:  ldftn      ""void C.Ptr(ref object)""
  IL_0011:  call       ""void C.M(delegate*<ref object, void>)""
  IL_0016:  ret
}
");
        }

        [Theory]
        [InlineData("ref", "out")]
        [InlineData("ref", "in")]
        [InlineData("out", "in")]
        public void Overloading_InvalidParameterRefness(string refKind1, string refKind2)
        {
            var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C<T>
{{
    static void M1(delegate*<{refKind1} object, void> ptr) => throw null;
    static void M1(delegate*<{refKind2} object, void> ptr) => throw null;

    static void M2(C<delegate*<{refKind1} object, void>[]> c) => throw null;
    static void M2(C<delegate*<{refKind2} object, void>[]> c) => throw null;
}}
");

            comp.VerifyDiagnostics(
                // (5,17): error CS0111: Type 'C<T>' already defines a member called 'M1' with the same parameter types
                //     static void M1(delegate*<{refKind2} object, void> ptr) => throw null;
                Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M1").WithArguments("M1", "C<T>").WithLocation(5, 17),
                // (8,17): error CS0111: Type 'C<T>' already defines a member called 'M2' with the same parameter types
                //     static void M2(C<delegate*<{refKind2} object, void>[]> c) => throw null;
                Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M2").WithArguments("M2", "C<T>").WithLocation(8, 17)
            );
        }

        [Fact]
        public void Overloading_ParameterTypesNoBetterFunctionMember()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
interface I1 {}
interface I2 {}
unsafe class C : I1, I2
{
    static void M1(delegate*<delegate*<I1, void>, void> ptr) => throw null;
    static void M1(delegate*<delegate*<I2, void>, void> ptr) => throw null;

    static void M2(delegate*<delegate*<C, void>, void> ptr)
    {
        M1(ptr);
    }
}
");

            comp.VerifyDiagnostics(
                // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M1(delegate*<delegate*<I1, void>, void>)' and 'C.M1(delegate*<delegate*<I2, void>, void>)'
                //         M1(ptr);
                Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("C.M1(delegate*<delegate*<I1, void>, void>)", "C.M1(delegate*<delegate*<I2, void>, void>)").WithLocation(11, 9)
            );
        }

        [Fact]
        public void Override_CallingConventionMustMatch()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
    protected virtual void M1(delegate*<void> ptr) {}
    protected virtual delegate*<void> M2() => throw null;
6244 6245
    protected virtual void M3(delegate* unmanaged[Stdcall, Thiscall]<void> ptr) {}
    protected virtual delegate* unmanaged[Stdcall, Thiscall]<void> M4() => throw null;
6246
}
6247
unsafe class Derived1 : Base
6248
{
6249 6250
    protected override void M1(delegate* unmanaged[Cdecl]<void> ptr) {}
    protected override delegate* unmanaged[Cdecl]<void> M2() => throw null;
6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263
    protected override void M3(delegate* unmanaged[Fastcall, Thiscall]<void> ptr) {}
    protected override delegate* unmanaged[Fastcall, Thiscall]<void> M4() => throw null;
}
unsafe class Derived2 : Base
{
    protected override void M1(delegate*<void> ptr) {} // Implemented correctly
    protected override delegate*<void> M2() => throw null; // Implemented correctly
    protected override void M3(delegate* unmanaged[Stdcall, Fastcall]<void> ptr) {}
    protected override delegate* unmanaged[Stdcall, Fastcall]<void> M4() => throw null;
}
");

            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
6264 6265

            comp.VerifyDiagnostics(
6266
                // (11,29): error CS0115: 'Derived1.M1(delegate* unmanaged[Cdecl]<void>)': no suitable method found to override
6267
                //     protected override void M1(delegate* unmanaged[Cdecl]<void> ptr) {}
6268
                Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("Derived1.M1(delegate* unmanaged[Cdecl]<void>)").WithLocation(11, 29),
6269
                // (12,57): error CS0508: 'Derived1.M2()': return type must be 'delegate*<void>' to match overridden member 'Base.M2()'
6270
                //     protected override delegate* unmanaged[Cdecl]<void> M2() => throw null;
6271
                Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived1.M2()", "Base.M2()", "delegate*<void>").WithLocation(12, 57),
6272
                // (13,29): error CS0115: 'Derived1.M3(delegate* unmanaged[Fastcall, Thiscall]<void>)': no suitable method found to override
6273
                //     protected override void M3(delegate* unmanaged[Fastcall, Thiscall]<void> ptr) {}
6274 6275
                Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("Derived1.M3(delegate* unmanaged[Fastcall, Thiscall]<void>)").WithLocation(13, 29),
                // (14,70): error CS0508: 'Derived1.M4()': return type must be 'delegate* unmanaged[Stdcall, Thiscall]<void>' to match overridden member 'Base.M4()'
6276
                //     protected override delegate* unmanaged[Fastcall, Thiscall]<void> M4() => throw null;
6277 6278
                Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M4").WithArguments("Derived1.M4()", "Base.M4()", "delegate* unmanaged[Stdcall, Thiscall]<void>").WithLocation(14, 70),
                // (20,29): error CS0115: 'Derived2.M3(delegate* unmanaged[Stdcall, Fastcall]<void>)': no suitable method found to override
6279
                //     protected override void M3(delegate* unmanaged[Stdcall, Fastcall]<void> ptr) {}
6280 6281
                Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("Derived2.M3(delegate* unmanaged[Stdcall, Fastcall]<void>)").WithLocation(20, 29),
                // (21,69): error CS0508: 'Derived2.M4()': return type must be 'delegate* unmanaged[Stdcall, Thiscall]<void>' to match overridden member 'Base.M4()'
6282
                //     protected override delegate* unmanaged[Stdcall, Fastcall]<void> M4() => throw null;
6283
                Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M4").WithArguments("Derived2.M4()", "Base.M4()", "delegate* unmanaged[Stdcall, Thiscall]<void>").WithLocation(21, 69)
6284 6285 6286
            );
        }

6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315
        [Fact]
        public void Override_ConventionOrderingDoesNotMatter()
        {
            var source1 = @"
public unsafe class Base
{
    public virtual void M1(delegate* unmanaged[Thiscall, Stdcall]<void> param) => throw null;
    public virtual delegate* unmanaged[Thiscall, Stdcall]<void> M2() => throw null;
    public virtual void M3(delegate* unmanaged[Thiscall, Stdcall]<ref string> param) => throw null;
    public virtual delegate* unmanaged[Thiscall, Stdcall]<ref string> M4() => throw null;
}
";

            var source2 = @"
unsafe class Derived1 : Base
{
    public override void M1(delegate* unmanaged[Stdcall, Thiscall]<void> param) => throw null;
    public override delegate* unmanaged[Stdcall, Thiscall]<void> M2() => throw null;
    public override void M3(delegate* unmanaged[Stdcall, Thiscall]<ref string> param) => throw null;
    public override delegate* unmanaged[Stdcall, Thiscall]<ref string> M4() => throw null;
}
unsafe class Derived2 : Base
{
    public override void M1(delegate* unmanaged[Stdcall, Stdcall, Thiscall]<void> param) => throw null;
    public override delegate* unmanaged[Stdcall, Stdcall, Thiscall]<void> M2() => throw null;
    public override void M3(delegate* unmanaged[Stdcall, Stdcall, Thiscall]<ref string> param) => throw null;
    public override delegate* unmanaged[Stdcall, Stdcall, Thiscall]<ref string> M4() => throw null;
}
";
6316 6317
            // https://github.com/dotnet/roslyn/issues/46676: When we have a p8 runtime, verify output
            // on these, that the correct overload is called.
F
Fredric Silberberg 已提交
6318

6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352
            var allSourceComp = CreateCompilationWithFunctionPointers(source1 + source2);

            allSourceComp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            CompileAndVerify(allSourceComp, symbolValidator: getSymbolValidator(separateAssembly: false));

            var baseComp = CreateCompilationWithFunctionPointers(source1);
            baseComp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            var metadataRef = baseComp.EmitToImageReference();

            var derivedComp = CreateCompilationWithFunctionPointers(source2, references: new[] { metadataRef });
            derivedComp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            CompileAndVerify(derivedComp, symbolValidator: getSymbolValidator(separateAssembly: true));

            static Action<ModuleSymbol> getSymbolValidator(bool separateAssembly)
            {
                return module =>
                {
                    var @base = (separateAssembly ? module.ReferencedAssemblySymbols[1].GlobalNamespace : module.GlobalNamespace).GetTypeMember("Base");
                    var baseM1 = @base.GetMethod("M1");
                    var baseM2 = @base.GetMethod("M2");
                    var baseM3 = @base.GetMethod("M3");
                    var baseM4 = @base.GetMethod("M4");

                    for (int derivedI = 1; derivedI <= 2; derivedI++)
                    {
                        var derived = module.GlobalNamespace.GetTypeMember($"Derived{derivedI}");
                        var derivedM1 = derived.GetMethod("M1");
                        var derivedM2 = derived.GetMethod("M2");
                        var derivedM3 = derived.GetMethod("M3");
                        var derivedM4 = derived.GetMethod("M4");

                        Assert.True(baseM1.Parameters.Single().Type.Equals(derivedM1.Parameters.Single().Type, TypeCompareKind.ConsiderEverything));
                        Assert.True(baseM2.ReturnType.Equals(derivedM2.ReturnType, TypeCompareKind.ConsiderEverything));
                        Assert.True(baseM3.Parameters.Single().Type.Equals(derivedM3.Parameters.Single().Type, TypeCompareKind.ConsiderEverything));
F
Fredric Silberberg 已提交
6353
                        Assert.True(baseM4.ReturnType.Equals(derivedM4.ReturnType, TypeCompareKind.ConsiderEverything));
6354 6355 6356 6357 6358
                    }
                };
            }
        }

6359
        [Theory]
F
Fredric Silberberg 已提交
6360 6361 6362
        [InlineData("", "ref ")]
        [InlineData("", "out ")]
        [InlineData("", "in ")]
6363 6364 6365
        [InlineData("ref ", "")]
        [InlineData("ref ", "out ")]
        [InlineData("ref ", "in ")]
F
Fredric Silberberg 已提交
6366
        [InlineData("out ", "")]
6367 6368
        [InlineData("out ", "ref ")]
        [InlineData("out ", "in ")]
F
Fredric Silberberg 已提交
6369
        [InlineData("in ", "")]
6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388
        [InlineData("in ", "ref ")]
        [InlineData("in ", "out ")]
        public void Override_RefnessMustMatch_Parameters(string refKind1, string refKind2)
        {
            var comp = CreateCompilationWithFunctionPointers(@$"
unsafe class Base
{{
    protected virtual void M1(delegate*<{refKind1}string, void> ptr) {{}}
    protected virtual delegate*<{refKind1}string, void> M2() => throw null;
}}
unsafe class Derived : Base
{{
    protected override void M1(delegate*<{refKind2}string, void> ptr) {{}}
    protected override delegate*<{refKind2}string, void> M2() => throw null;
}}");

            comp.VerifyDiagnostics(
                // (9,29): error CS0115: 'Derived.M1(delegate*<{refKind2} string, void>)': no suitable method found to override
                //     protected override void M1(delegate*<{refKind2} string, void> ptr) {}
F
Fredric Silberberg 已提交
6389
                Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments($"Derived.M1(delegate*<{refKind2}string, void>)").WithLocation(9, 29),
6390 6391
                // (10,49): error CS0508: 'Derived.M2()': return type must be 'delegate*<{refKind1} string, void>' to match overridden member 'Base.M2()'
                //     protected override delegate*<{refKind2} string, void> M2() => throw null;
F
Fredric Silberberg 已提交
6392
                Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", $"delegate*<{refKind1}string, void>").WithLocation(10, 48 + refKind2.Length)
6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476
            );
        }

        [Theory]
        [InlineData(" ", "ref ")]
        [InlineData(" ", "ref readonly ")]
        [InlineData("ref ", " ")]
        [InlineData("ref ", "ref readonly ")]
        [InlineData("ref readonly ", " ")]
        [InlineData("ref readonly ", "ref ")]
        public void Override_RefnessMustMatch_Returns(string refKind1, string refKind2)
        {
            var comp = CreateCompilationWithFunctionPointers(@$"
unsafe class Base
{{
    protected virtual void M1(delegate*<{refKind1}string> ptr) {{}}
    protected virtual delegate*<{refKind1}string> M2() => throw null;
}}
unsafe class Derived : Base
{{
    protected override void M1(delegate*<{refKind2}string> ptr) {{}}
    protected override delegate*<{refKind2}string> M2() => throw null;
}}");

            comp.VerifyDiagnostics(
                // (9,29): error CS0115: 'Derived.M1(delegate*<{refKind2} string>)': no suitable method found to override
                //     protected override void M1(delegate*<{refKind2} string> ptr) {}
                Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments($"Derived.M1(delegate*<string>)").WithLocation(9, 29),
                // (10,49): error CS0508: 'Derived.M2()': return type must be 'delegate*<{refKind1} string>' to match overridden member 'Base.M2()'
                //     protected override delegate*<{refKind2} string> M2() => throw null;
                Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", $"delegate*<string>").WithLocation(10, 42 + refKind2.Length)
            );
        }

        [Fact]
        public void Override_ParameterTypesMustMatch()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
    protected virtual void M1(delegate*<object, void> ptr) {{}}
    protected virtual delegate*<object, void> M2() => throw null;
}
unsafe class Derived : Base
{
    protected override void M1(delegate*<string, void> ptr) {{}}
    protected override delegate*<string, void> M2() => throw null;
}");

            comp.VerifyDiagnostics(
                // (9,29): error CS0115: 'Derived.M1(delegate*<string, void>)': no suitable method found to override
                //     protected override void M1(delegate*<string, void> ptr) {}
                Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("Derived.M1(delegate*<string, void>)").WithLocation(9, 29),
                // (10,48): error CS0508: 'Derived.M2()': return type must be 'delegate*<object, void>' to match overridden member 'Base.M2()'
                //     protected override delegate*<string, void> M2() => throw null;
                Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", "delegate*<object, void>").WithLocation(10, 48)
            );
        }

        [Fact]
        public void Override_ReturnTypesMustMatch()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
    protected virtual void M1(delegate*<object> ptr) {{}}
    protected virtual delegate*<object> M2() => throw null;
}
unsafe class Derived : Base
{
    protected override void M1(delegate*<string> ptr) {{}}
    protected override delegate*<string> M2() => throw null;
}");

            comp.VerifyDiagnostics(
                // (9,29): error CS0115: 'Derived.M1(delegate*<string>)': no suitable method found to override
                //     protected override void M1(delegate*<string> ptr) {}
                Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("Derived.M1(delegate*<string>)").WithLocation(9, 29),
                // (10,42): error CS0508: 'Derived.M2()': return type must be 'delegate*<object>' to match overridden member 'Base.M2()'
                //     protected override delegate*<string> M2() => throw null;
                Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", "delegate*<object>").WithLocation(10, 42)
            );
        }

F
Fredric Silberberg 已提交
6477 6478
        [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44358")]
        public void Override_NintIntPtrDifferences()
6479
        {
F
Fredric Silberberg 已提交
6480
            var comp = CreateCompilationWithFunctionPointers(@"
6481
unsafe class Base
F
Fredric Silberberg 已提交
6482 6483 6484 6485 6486 6487 6488 6489 6490 6491
{
    protected virtual void M1(delegate*<nint> ptr) {}
    protected virtual delegate*<nint> M2() => throw null;
    protected virtual void M3(delegate*<nint, void> ptr) {}
    protected virtual delegate*<nint, void> M4() => throw null;
    protected virtual void M5(delegate*<System.IntPtr> ptr) {}
    protected virtual delegate*<System.IntPtr> M6() => throw null;
    protected virtual void M7(delegate*<System.IntPtr, void> ptr) {}
    protected virtual delegate*<System.IntPtr, void> M8() => throw null;
}
6492
unsafe class Derived : Base
F
Fredric Silberberg 已提交
6493 6494 6495 6496 6497 6498 6499 6500 6501 6502
{
    protected override void M1(delegate*<System.IntPtr> ptr) {}
    protected override delegate*<System.IntPtr> M2() => throw null;
    protected override void M3(delegate*<System.IntPtr, void> ptr) {}
    protected override delegate*<System.IntPtr, void> M4() => throw null;
    protected override void M5(delegate*<nint> ptr) {}
    protected override delegate*<nint> M6() => throw null;
    protected override void M7(delegate*<nint, void> ptr) {}
    protected override delegate*<nint, void> M8() => throw null;
}");
6503 6504 6505

            comp.VerifyDiagnostics(
            );
F
Fredric Silberberg 已提交
6506

F
Fredric Silberberg 已提交
6507
            assertMethods(comp.SourceModule);
F
Fredric Silberberg 已提交
6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559
            CompileAndVerify(comp, symbolValidator: assertMethods);

            static void assertMethods(ModuleSymbol module)
            {
                var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
                assertMethod(derived, "M1", "void Derived.M1(delegate*<System.IntPtr> ptr)");
                assertMethod(derived, "M2", "delegate*<System.IntPtr> Derived.M2()");
                assertMethod(derived, "M3", "void Derived.M3(delegate*<System.IntPtr, System.Void> ptr)");
                assertMethod(derived, "M4", "delegate*<System.IntPtr, System.Void> Derived.M4()");
                assertMethod(derived, "M5", "void Derived.M5(delegate*<nint> ptr)");
                assertMethod(derived, "M6", "delegate*<nint> Derived.M6()");
                assertMethod(derived, "M7", "void Derived.M7(delegate*<nint, System.Void> ptr)");
                assertMethod(derived, "M8", "delegate*<nint, System.Void> Derived.M8()");
            }

            static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
            {
                var m = derived.GetMember<MethodSymbol>(methodName);
                AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
            }
        }

        [Fact]
        public void Override_ObjectDynamicDifferences()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
    protected virtual void M1(delegate*<dynamic> ptr) {}
    protected virtual delegate*<dynamic> M2() => throw null;
    protected virtual void M3(delegate*<dynamic, void> ptr) {}
    protected virtual delegate*<dynamic, void> M4() => throw null;
    protected virtual void M5(delegate*<object> ptr) {}
    protected virtual delegate*<object> M6() => throw null;
    protected virtual void M7(delegate*<object, void> ptr) {}
    protected virtual delegate*<object, void> M8() => throw null;
}
unsafe class Derived : Base
{
    protected override void M1(delegate*<object> ptr) {}
    protected override delegate*<object> M2() => throw null;
    protected override void M3(delegate*<object, void> ptr) {}
    protected override delegate*<object, void> M4() => throw null;
    protected override void M5(delegate*<dynamic> ptr) {}
    protected override delegate*<dynamic> M6() => throw null;
    protected override void M7(delegate*<dynamic, void> ptr) {}
    protected override delegate*<dynamic, void> M8() => throw null;
}");

            comp.VerifyDiagnostics(
            );

F
Fredric Silberberg 已提交
6560
            assertMethods(comp.SourceModule);
F
Fredric Silberberg 已提交
6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580
            CompileAndVerify(comp, symbolValidator: assertMethods);

            static void assertMethods(ModuleSymbol module)
            {
                var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
                assertMethod(derived, "M1", "void Derived.M1(delegate*<System.Object> ptr)");
                assertMethod(derived, "M2", "delegate*<System.Object> Derived.M2()");
                assertMethod(derived, "M3", "void Derived.M3(delegate*<System.Object, System.Void> ptr)");
                assertMethod(derived, "M4", "delegate*<System.Object, System.Void> Derived.M4()");
                assertMethod(derived, "M5", "void Derived.M5(delegate*<dynamic> ptr)");
                assertMethod(derived, "M6", "delegate*<dynamic> Derived.M6()");
                assertMethod(derived, "M7", "void Derived.M7(delegate*<dynamic, System.Void> ptr)");
                assertMethod(derived, "M8", "delegate*<dynamic, System.Void> Derived.M8()");
            }

            static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
            {
                var m = derived.GetMember<MethodSymbol>(methodName);
                AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
            }
6581 6582 6583 6584 6585 6586 6587 6588
        }

        [Fact]
        public void Override_TupleNameChanges()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
F
Fredric Silberberg 已提交
6589
    protected virtual void M1(delegate*<(int, string)> ptr) {}
6590
    protected virtual delegate*<(int, string)> M2() => throw null;
F
Fredric Silberberg 已提交
6591
    protected virtual void M3(delegate*<(int, string), void> ptr) {}
6592
    protected virtual delegate*<(int, string), void> M4() => throw null;
F
Fredric Silberberg 已提交
6593
    protected virtual void M5(delegate*<(int i, string s)> ptr) {}
6594
    protected virtual delegate*<(int i, string s)> M6() => throw null;
F
Fredric Silberberg 已提交
6595
    protected virtual void M7(delegate*<(int i, string s), void> ptr) {}
6596 6597 6598 6599
    protected virtual delegate*<(int i, string s), void> M8() => throw null;
}
unsafe class Derived : Base
{
F
Fredric Silberberg 已提交
6600
    protected override void M1(delegate*<(int i, string s)> ptr) {}
6601
    protected override delegate*<(int i, string s)> M2() => throw null;
F
Fredric Silberberg 已提交
6602
    protected override void M3(delegate*<(int i, string s), void> ptr) {}
6603
    protected override delegate*<(int i, string s), void> M4() => throw null;
F
Fredric Silberberg 已提交
6604
    protected override void M5(delegate*<(int, string)> ptr) {}
6605
    protected override delegate*<(int, string)> M6() => throw null;
F
Fredric Silberberg 已提交
6606
    protected override void M7(delegate*<(int, string), void> ptr) {}
6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623
    protected override delegate*<(int, string), void> M8() => throw null;
}");

            comp.VerifyDiagnostics(
                // (15,29): error CS8139: 'Derived.M1(delegate*<(int i, string s)>)': cannot change tuple element names when overriding inherited member 'Base.M1(delegate*<(int, string)>)'
                //     protected override void M1(delegate*<(int i, string s)> ptr) {}
                Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M1").WithArguments("Derived.M1(delegate*<(int i, string s)>)", "Base.M1(delegate*<(int, string)>)").WithLocation(15, 29),
                // (16,53): error CS8139: 'Derived.M2()': cannot change tuple element names when overriding inherited member 'Base.M2()'
                //     protected override delegate*<(int i, string s)> M2() => throw null;
                Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()").WithLocation(16, 53),
                // (17,29): error CS8139: 'Derived.M3(delegate*<(int i, string s), void>)': cannot change tuple element names when overriding inherited member 'Base.M3(delegate*<(int, string), void>)'
                //     protected override void M3(delegate*<(int i, string s), void> ptr) {}
                Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M3").WithArguments("Derived.M3(delegate*<(int i, string s), void>)", "Base.M3(delegate*<(int, string), void>)").WithLocation(17, 29),
                // (18,59): error CS8139: 'Derived.M4()': cannot change tuple element names when overriding inherited member 'Base.M4()'
                //     protected override delegate*<(int i, string s), void> M4() => throw null;
                Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M4").WithArguments("Derived.M4()", "Base.M4()").WithLocation(18, 59)
            );
F
Fredric Silberberg 已提交
6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638

            assertMethod("M1", "void Derived.M1(delegate*<(System.Int32 i, System.String s)> ptr)");
            assertMethod("M2", "delegate*<(System.Int32 i, System.String s)> Derived.M2()");
            assertMethod("M3", "void Derived.M3(delegate*<(System.Int32 i, System.String s), System.Void> ptr)");
            assertMethod("M4", "delegate*<(System.Int32 i, System.String s), System.Void> Derived.M4()");
            assertMethod("M5", "void Derived.M5(delegate*<(System.Int32, System.String)> ptr)");
            assertMethod("M6", "delegate*<(System.Int32, System.String)> Derived.M6()");
            assertMethod("M7", "void Derived.M7(delegate*<(System.Int32, System.String), System.Void> ptr)");
            assertMethod("M8", "delegate*<(System.Int32, System.String), System.Void> Derived.M8()");

            void assertMethod(string methodName, string expectedSignature)
            {
                var m = comp.GetMember<MethodSymbol>($"Derived.{methodName}");
                AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString());
            }
6639 6640 6641 6642 6643 6644 6645 6646 6647
        }

        [Fact]
        public void Override_NullabilityChanges_NoRefs()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
#nullable enable
unsafe class Base
{
F
Fredric Silberberg 已提交
6648
    protected virtual void M1(delegate*<string?> ptr) {}
6649
    protected virtual delegate*<string?> M2() => throw null!;
F
Fredric Silberberg 已提交
6650
    protected virtual void M3(delegate*<string?, void> ptr) {}
6651
    protected virtual delegate*<string?, void> M4() => throw null!;
F
Fredric Silberberg 已提交
6652
    protected virtual void M5(delegate*<string> ptr) {}
6653
    protected virtual delegate*<string> M6() => throw null!;
F
Fredric Silberberg 已提交
6654
    protected virtual void M7(delegate*<string, void> ptr) {}
6655 6656 6657 6658
    protected virtual delegate*<string, void> M8() => throw null!;
}
unsafe class Derived : Base
{
F
Fredric Silberberg 已提交
6659
    protected override void M1(delegate*<string> ptr) {}
6660
    protected override delegate*<string> M2() => throw null!;
F
Fredric Silberberg 已提交
6661
    protected override void M3(delegate*<string, void> ptr) {}
6662
    protected override delegate*<string, void> M4() => throw null!;
F
Fredric Silberberg 已提交
6663
    protected override void M5(delegate*<string?> ptr) {}
6664
    protected override delegate*<string?> M6() => throw null!;
F
Fredric Silberberg 已提交
6665
    protected override void M7(delegate*<string?, void> ptr) {}
6666 6667 6668 6669 6670
    protected override delegate*<string?, void> M8() => throw null!;
}");

            comp.VerifyDiagnostics(
                // (16,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
F
Fredric Silberberg 已提交
6671
                //     protected override void M1(delegate*<string> ptr) {}
6672 6673 6674 6675 6676 6677 6678 6679
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M1").WithArguments("ptr").WithLocation(16, 29),
                // (19,48): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
                //     protected override delegate*<string, void> M4() => throw null!;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(19, 48),
                // (21,43): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
                //     protected override delegate*<string?> M6() => throw null!;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M6").WithLocation(21, 43),
                // (22,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
F
Fredric Silberberg 已提交
6680
                //     protected override void M7(delegate*<string?, void> ptr) {}
6681 6682
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M7").WithArguments("ptr").WithLocation(22, 29)
            );
F
Fredric Silberberg 已提交
6683

F
Fredric Silberberg 已提交
6684
            assertMethods(comp.SourceModule);
F
Fredric Silberberg 已提交
6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704
            CompileAndVerify(comp, symbolValidator: assertMethods);

            static void assertMethods(ModuleSymbol module)
            {
                var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
                assertMethod(derived, "M1", "void Derived.M1(delegate*<System.String!> ptr)");
                assertMethod(derived, "M2", "delegate*<System.String!> Derived.M2()");
                assertMethod(derived, "M3", "void Derived.M3(delegate*<System.String!, System.Void> ptr)");
                assertMethod(derived, "M4", "delegate*<System.String!, System.Void> Derived.M4()");
                assertMethod(derived, "M5", "void Derived.M5(delegate*<System.String?> ptr)");
                assertMethod(derived, "M6", "delegate*<System.String?> Derived.M6()");
                assertMethod(derived, "M7", "void Derived.M7(delegate*<System.String?, System.Void> ptr)");
                assertMethod(derived, "M8", "delegate*<System.String?, System.Void> Derived.M8()");
            }

            static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
            {
                var m = derived.GetMember<MethodSymbol>(methodName);
                AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
            }
6705 6706 6707 6708 6709 6710 6711 6712 6713
        }

        [Fact]
        public void Override_NullabilityChanges_RefsInParameterReturnTypes()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
#nullable enable
unsafe class Base
{
F
Fredric Silberberg 已提交
6714
    protected virtual void M1(delegate*<ref string?> ptr) {}
6715
    protected virtual delegate*<ref string?> M2() => throw null!;
F
Fredric Silberberg 已提交
6716
    protected virtual void M3(delegate*<ref string?, void> ptr) {}
6717
    protected virtual delegate*<ref string?, void> M4() => throw null!;
F
Fredric Silberberg 已提交
6718
    protected virtual void M5(delegate*<ref string> ptr) {}
6719
    protected virtual delegate*<ref string> M6() => throw null!;
F
Fredric Silberberg 已提交
6720
    protected virtual void M7(delegate*<ref string, void> ptr) {}
6721 6722 6723 6724
    protected virtual delegate*<ref string, void> M8() => throw null!;
}
unsafe class Derived : Base
{
F
Fredric Silberberg 已提交
6725
    protected override void M1(delegate*<ref string> ptr) {}
6726
    protected override delegate*<ref string> M2() => throw null!;
F
Fredric Silberberg 已提交
6727
    protected override void M3(delegate*<ref string, void> ptr) {}
6728
    protected override delegate*<ref string, void> M4() => throw null!;
F
Fredric Silberberg 已提交
6729
    protected override void M5(delegate*<ref string?> ptr) {}
6730
    protected override delegate*<ref string?> M6() => throw null!;
F
Fredric Silberberg 已提交
6731
    protected override void M7(delegate*<ref string?, void> ptr) {}
6732 6733 6734 6735 6736
    protected override delegate*<ref string?, void> M8() => throw null!;
}");

            comp.VerifyDiagnostics(
                // (16,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
F
Fredric Silberberg 已提交
6737
                //     protected override void M1(delegate*<ref string> ptr) {}
6738 6739 6740 6741 6742
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M1").WithArguments("ptr").WithLocation(16, 29),
                // (17,46): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
                //     protected override delegate*<ref string> M2() => throw null!;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(17, 46),
                // (18,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
F
Fredric Silberberg 已提交
6743
                //     protected override void M3(delegate*<ref string, void> ptr) {}
6744 6745 6746 6747 6748
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("ptr").WithLocation(18, 29),
                // (19,52): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
                //     protected override delegate*<ref string, void> M4() => throw null!;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(19, 52),
                // (20,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
F
Fredric Silberberg 已提交
6749
                //     protected override void M5(delegate*<ref string?> ptr) {}
6750 6751 6752 6753 6754
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M5").WithArguments("ptr").WithLocation(20, 29),
                // (21,47): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
                //     protected override delegate*<ref string?> M6() => throw null!;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M6").WithLocation(21, 47),
                // (22,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
F
Fredric Silberberg 已提交
6755
                //     protected override void M7(delegate*<ref string?, void> ptr) {}
6756 6757 6758 6759 6760
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M7").WithArguments("ptr").WithLocation(22, 29),
                // (23,53): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
                //     protected override delegate*<ref string?, void> M8() => throw null!;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M8").WithLocation(23, 53)
            );
F
Fredric Silberberg 已提交
6761

F
Fredric Silberberg 已提交
6762
            assertMethods(comp.SourceModule);
F
Fredric Silberberg 已提交
6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782
            CompileAndVerify(comp, symbolValidator: assertMethods);

            static void assertMethods(ModuleSymbol module)
            {
                var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
                assertMethod(derived, "M1", "void Derived.M1(delegate*<ref System.String!> ptr)");
                assertMethod(derived, "M2", "delegate*<ref System.String!> Derived.M2()");
                assertMethod(derived, "M3", "void Derived.M3(delegate*<ref System.String!, System.Void> ptr)");
                assertMethod(derived, "M4", "delegate*<ref System.String!, System.Void> Derived.M4()");
                assertMethod(derived, "M5", "void Derived.M5(delegate*<ref System.String?> ptr)");
                assertMethod(derived, "M6", "delegate*<ref System.String?> Derived.M6()");
                assertMethod(derived, "M7", "void Derived.M7(delegate*<ref System.String?, System.Void> ptr)");
                assertMethod(derived, "M8", "delegate*<ref System.String?, System.Void> Derived.M8()");
            }

            static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
            {
                var m = derived.GetMember<MethodSymbol>(methodName);
                AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
            }
6783 6784 6785 6786 6787 6788 6789
        }

        [Fact]
        public void Override_NullabilityChanges_PointerByRef()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
#nullable enable
F
Fredric Silberberg 已提交
6790 6791
public unsafe class Base
{
F
Fredric Silberberg 已提交
6792
    public virtual void M1(ref delegate*<string?> ptr) {}
F
Fredric Silberberg 已提交
6793
    public virtual ref delegate*<string?> M2() => throw null!;
F
Fredric Silberberg 已提交
6794
    public virtual void M3(ref delegate*<string?, void> ptr) {}
F
Fredric Silberberg 已提交
6795
    public virtual ref delegate*<string?, void> M4() => throw null!;
F
Fredric Silberberg 已提交
6796
    public virtual void M5(ref delegate*<string> ptr) {}
F
Fredric Silberberg 已提交
6797
    public virtual ref delegate*<string> M6() => throw null!;
F
Fredric Silberberg 已提交
6798
    public virtual void M7(ref delegate*<string, void> ptr) {}
F
Fredric Silberberg 已提交
6799
    public virtual ref delegate*<string, void> M8() => throw null!;
6800
}
F
Fredric Silberberg 已提交
6801 6802
public unsafe class Derived : Base
{
F
Fredric Silberberg 已提交
6803
    public override void M1(ref delegate*<string> ptr) {}
F
Fredric Silberberg 已提交
6804
    public override ref delegate*<string> M2() => throw null!;
F
Fredric Silberberg 已提交
6805
    public override void M3(ref delegate*<string, void> ptr) {}
F
Fredric Silberberg 已提交
6806
    public override ref delegate*<string, void> M4() => throw null!;
F
Fredric Silberberg 已提交
6807
    public override void M5(ref delegate*<string?> ptr) {}
F
Fredric Silberberg 已提交
6808
    public override ref delegate*<string?> M6() => throw null!;
F
Fredric Silberberg 已提交
6809
    public override void M7(ref delegate*<string?, void> ptr) {}
F
Fredric Silberberg 已提交
6810
    public override ref delegate*<string?, void> M8() => throw null!;
6811 6812 6813
}");

            comp.VerifyDiagnostics(
F
Fredric Silberberg 已提交
6814
                // (16,26): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
F
Fredric Silberberg 已提交
6815
                //     public override void M1(ref delegate*<string> ptr) {}
F
Fredric Silberberg 已提交
6816 6817 6818 6819 6820
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M1").WithArguments("ptr").WithLocation(16, 26),
                // (17,43): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
                //     public override ref delegate*<string> M2() => throw null!;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(17, 43),
                // (18,26): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
F
Fredric Silberberg 已提交
6821
                //     public override void M3(ref delegate*<string, void> ptr) {}
F
Fredric Silberberg 已提交
6822 6823 6824 6825 6826
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("ptr").WithLocation(18, 26),
                // (19,49): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
                //     public override ref delegate*<string, void> M4() => throw null!;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(19, 49),
                // (20,26): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
F
Fredric Silberberg 已提交
6827
                //     public override void M5(ref delegate*<string?> ptr) {}
F
Fredric Silberberg 已提交
6828 6829 6830 6831 6832
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M5").WithArguments("ptr").WithLocation(20, 26),
                // (21,44): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
                //     public override ref delegate*<string?> M6() => throw null!;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M6").WithLocation(21, 44),
                // (22,26): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
F
Fredric Silberberg 已提交
6833
                //     public override void M7(ref delegate*<string?, void> ptr) {}
F
Fredric Silberberg 已提交
6834 6835 6836 6837
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M7").WithArguments("ptr").WithLocation(22, 26),
                // (23,50): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
                //     public override ref delegate*<string?, void> M8() => throw null!;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M8").WithLocation(23, 50)
6838
            );
F
Fredric Silberberg 已提交
6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861

            assertMethods(comp.SourceModule);
            CompileAndVerify(comp, symbolValidator: assertMethods);

            static void assertMethods(ModuleSymbol module)
            {
                var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
                assertMethod(derived, "M1", "void Derived.M1(ref delegate*<System.String!> ptr)");
                assertMethod(derived, "M2", "ref delegate*<System.String!> Derived.M2()");
                assertMethod(derived, "M3", "void Derived.M3(ref delegate*<System.String!, System.Void> ptr)");
                assertMethod(derived, "M4", "ref delegate*<System.String!, System.Void> Derived.M4()");
                assertMethod(derived, "M5", "void Derived.M5(ref delegate*<System.String?> ptr)");
                assertMethod(derived, "M6", "ref delegate*<System.String?> Derived.M6()");
                assertMethod(derived, "M7", "void Derived.M7(ref delegate*<System.String?, System.Void> ptr)");
                assertMethod(derived, "M8", "ref delegate*<System.String?, System.Void> Derived.M8()");

            }

            static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
            {
                var m = derived.GetMember<MethodSymbol>(methodName);
                AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
            }
6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130
        }

        [Fact]
        public void Override_SingleDimensionArraySizesInMetadata()
        {
            var il = @"
.class public auto ansi abstract beforefieldinit Base
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig newslot abstract virtual
        void M1 (method void *(int32[0...]) param) cil managed 
    {
    }

    .method public hidebysig newslot abstract virtual
        method void *(int32[0...]) M2 () cil managed 
    {
    }

    .method public hidebysig newslot abstract virtual
        void M3 (method int32[0...] *() param) cil managed 
    {
    }

    .method public hidebysig newslot abstract virtual
        method int32[0...] *() M4 () cil managed 
    {
    }

    .method family hidebysig specialname rtspecialname 
        instance void .ctor () cil managed 
    {
        ldarg.0
        call instance void [mscorlib]System.Object::.ctor()
        ret
    }
}";

            var source = @"
unsafe class Derived : Base
{
    public override void M1(delegate*<int[], void> param) => throw null;
    public override delegate*<int[], void> M2() => throw null;
    public override void M3(delegate*<int[]> param) => throw null;
    public override delegate*<int[]> M4() => throw null;
}";

            var comp = CreateCompilationWithFunctionPointersAndIl(source, il);
            comp.VerifyDiagnostics(
                // (2,14): error CS0534: 'Derived' does not implement inherited abstract member 'Base.M1(delegate*<int[*], void>)'
                // unsafe class Derived : Base
                Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.M1(delegate*<int[*], void>)").WithLocation(2, 14),
                // (2,14): error CS0534: 'Derived' does not implement inherited abstract member 'Base.M3(delegate*<int[*]>)'
                // unsafe class Derived : Base
                Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.M3(delegate*<int[*]>)").WithLocation(2, 14),
                // (4,26): error CS0115: 'Derived.M1(delegate*<int[], void>)': no suitable method found to override
                //     public override void M1(delegate*<int[], void> param) => throw null;
                Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("Derived.M1(delegate*<int[], void>)").WithLocation(4, 26),
                // (5,44): error CS0508: 'Derived.M2()': return type must be 'delegate*<int[*], void>' to match overridden member 'Base.M2()'
                //     public override delegate*<int[], void> M2() => throw null;
                Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", "delegate*<int[*], void>").WithLocation(5, 44),
                // (6,26): error CS0115: 'Derived.M3(delegate*<int[]>)': no suitable method found to override
                //     public override void M3(delegate*<int[]> param) => throw null;
                Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("Derived.M3(delegate*<int[]>)").WithLocation(6, 26),
                // (7,38): error CS0508: 'Derived.M4()': return type must be 'delegate*<int[*]>' to match overridden member 'Base.M4()'
                //     public override delegate*<int[]> M4() => throw null;
                Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M4").WithArguments("Derived.M4()", "Base.M4()", "delegate*<int[*]>").WithLocation(7, 38)
            );
        }

        [Fact]
        public void Override_ArraySizesInMetadata()
        {
            var il = @"
.class public auto ansi abstract beforefieldinit Base
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig newslot abstract virtual
        void M1 (method void *(int32[5...5,2...4]) param) cil managed 
    {
    }

    .method public hidebysig newslot abstract virtual
        method void *(int32[5...5,2...4]) M2 () cil managed 
    {
    }

    .method public hidebysig newslot abstract virtual
        void M3 (method int32[5...5,2...4] *() param) cil managed 
    {
    }

    .method public hidebysig newslot abstract virtual
        method int32[5...5,2...4] *() M4 () cil managed 
    {
    }

    .method family hidebysig specialname rtspecialname 
        instance void .ctor () cil managed 
    {
        ldarg.0
        call instance void [mscorlib]System.Object::.ctor()
        ret
    }
}";

            var source = @"
using System;
unsafe class Derived : Base
{
    private static void MultiDimensionParamFunc(int[,] param) { }
    private static int[,] MultiDimensionReturnFunc() => null;

    public override void M1(delegate*<int[,], void> param)
    {
        Console.WriteLine(""Multi-dimension array param as param"");
        param(null);
    }

    public override delegate*<int[,], void> M2()
    {
        Console.WriteLine(""Multi-dimension array param as return"");
        return &MultiDimensionParamFunc;
    }

    public override void M3(delegate*<int[,]> param)
    {
        Console.WriteLine(""Multi-dimension array return as param"");
        _ = param();
    }

    public override delegate*<int[,]> M4()
    {
        Console.WriteLine(""Multi-dimension array return as return"");
        return &MultiDimensionReturnFunc;
    }

    public static void Main()
    {
        var d = new Derived();
        d.M1(&MultiDimensionParamFunc);
        var ptr1 = d.M2();
        ptr1(null);
        d.M3(&MultiDimensionReturnFunc);
        var ptr2 = d.M4();
        _ = ptr2();
    }
}";

            var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, expectedOutput: @"
Multi-dimension array param as param
Multi-dimension array param as return
Multi-dimension array return as param
Multi-dimension array return as return
");

            verifier.VerifyIL("Derived.M1", expectedIL: @"
{
  // Code size       20 (0x14)
  .maxstack  2
  .locals init (delegate*<int[,], void> V_0)
  IL_0000:  ldstr      ""Multi-dimension array param as param""
  IL_0005:  call       ""void System.Console.WriteLine(string)""
  IL_000a:  ldarg.1
  IL_000b:  stloc.0
  IL_000c:  ldnull
  IL_000d:  ldloc.0
  IL_000e:  calli      ""delegate*<int[,], void>""
  IL_0013:  ret
}
");

            verifier.VerifyIL("Derived.M2", expectedIL: @"
{
  // Code size       17 (0x11)
  .maxstack  1
  IL_0000:  ldstr      ""Multi-dimension array param as return""
  IL_0005:  call       ""void System.Console.WriteLine(string)""
  IL_000a:  ldftn      ""void Derived.MultiDimensionParamFunc(int[,])""
  IL_0010:  ret
}
");

            verifier.VerifyIL("Derived.M3", expectedIL: @"
{
  // Code size       18 (0x12)
  .maxstack  1
  IL_0000:  ldstr      ""Multi-dimension array return as param""
  IL_0005:  call       ""void System.Console.WriteLine(string)""
  IL_000a:  ldarg.1
  IL_000b:  calli      ""delegate*<int[,]>""
  IL_0010:  pop
  IL_0011:  ret
}
");

            verifier.VerifyIL("Derived.M4", expectedIL: @"
{
  // Code size       17 (0x11)
  .maxstack  1
  IL_0000:  ldstr      ""Multi-dimension array return as return""
  IL_0005:  call       ""void System.Console.WriteLine(string)""
  IL_000a:  ldftn      ""int[,] Derived.MultiDimensionReturnFunc()""
  IL_0010:  ret
}
");

            verifier.VerifyIL("Derived.Main", expectedIL: @"
{
  // Code size       55 (0x37)
  .maxstack  3
  .locals init (delegate*<int[,], void> V_0)
  IL_0000:  newobj     ""Derived..ctor()""
  IL_0005:  dup
  IL_0006:  ldftn      ""void Derived.MultiDimensionParamFunc(int[,])""
  IL_000c:  callvirt   ""void Base.M1(delegate*<int[,], void>)""
  IL_0011:  dup
  IL_0012:  callvirt   ""delegate*<int[,], void> Base.M2()""
  IL_0017:  stloc.0
  IL_0018:  ldnull
  IL_0019:  ldloc.0
  IL_001a:  calli      ""delegate*<int[,], void>""
  IL_001f:  dup
  IL_0020:  ldftn      ""int[,] Derived.MultiDimensionReturnFunc()""
  IL_0026:  callvirt   ""void Base.M3(delegate*<int[,]>)""
  IL_002b:  callvirt   ""delegate*<int[,]> Base.M4()""
  IL_0030:  calli      ""delegate*<int[,]>""
  IL_0035:  pop
  IL_0036:  ret
}
");

            var comp = (CSharpCompilation)verifier.Compilation;

            var m1 = comp.GetMember<MethodSymbol>("Derived.M1");
            var m2 = comp.GetMember<MethodSymbol>("Derived.M2");
            var m3 = comp.GetMember<MethodSymbol>("Derived.M3");
            var m4 = comp.GetMember<MethodSymbol>("Derived.M4");

            var funcPtr = (FunctionPointerTypeSymbol)m1.Parameters.Single().Type;
            CommonVerifyFunctionPointer(funcPtr);
            verifyArray(funcPtr.Signature.Parameters.Single().Type);

            funcPtr = (FunctionPointerTypeSymbol)m2.ReturnType;
            CommonVerifyFunctionPointer(funcPtr);
            verifyArray(funcPtr.Signature.Parameters.Single().Type);

            funcPtr = (FunctionPointerTypeSymbol)m3.Parameters.Single().Type;
            CommonVerifyFunctionPointer(funcPtr);
            verifyArray(funcPtr.Signature.ReturnType);

            funcPtr = (FunctionPointerTypeSymbol)m4.ReturnType;
            CommonVerifyFunctionPointer(funcPtr);
            verifyArray(funcPtr.Signature.ReturnType);

            static void verifyArray(TypeSymbol type)
            {
                var array = (ArrayTypeSymbol)type;
                Assert.False(array.IsSZArray);
                Assert.Equal(2, array.Rank);
                Assert.Equal(5, array.LowerBounds[0]);
                Assert.Equal(1, array.Sizes[0]);
                Assert.Equal(2, array.LowerBounds[1]);
                Assert.Equal(3, array.Sizes[1]);
            }
        }

F
Fredric Silberberg 已提交
7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185
        [Fact]
        public void NullableUsageWarnings()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
#nullable enable
unsafe public class C
{
    static void M1(delegate*<string, string?, string?> ptr1)
    {
        _ = ptr1(null, null);
        _ = ptr1("""", null).ToString();
        delegate*<string?, string?, string?> ptr2 = ptr1;
        delegate*<string, string?, string> ptr3 = ptr1;
    }

    static void M2(delegate*<ref string, ref string> ptr1)
    {
        string? str1 = null;
        ptr1(ref str1);
        string str2 = """";
        ref string? str3 = ref ptr1(ref str2);
        delegate*<ref string?, ref string> ptr2 = ptr1;
        delegate*<ref string, ref string?> ptr3 = ptr1;
    }
}
");

            comp.VerifyDiagnostics(
                // (7,18): warning CS8625: Cannot convert null literal to non-nullable reference type.
                //         _ = ptr1(null, null);
                Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 18),
                // (8,13): warning CS8602: Dereference of a possibly null reference.
                //         _ = ptr1("", null).ToString();
                Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"ptr1("""", null)").WithLocation(8, 13),
                // (9,53): warning CS8619: Nullability of reference types in value of type 'delegate*<string, string?, string?>' doesn't match target type 'delegate*<string?, string?, string?>'.
                //         delegate*<string?, string?, string?> ptr2 = ptr1;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1").WithArguments("delegate*<string, string?, string?>", "delegate*<string?, string?, string?>").WithLocation(9, 53),
                // (10,51): warning CS8619: Nullability of reference types in value of type 'delegate*<string, string?, string?>' doesn't match target type 'delegate*<string, string?, string>'.
                //         delegate*<string, string?, string> ptr3 = ptr1;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1").WithArguments("delegate*<string, string?, string?>", "delegate*<string, string?, string>").WithLocation(10, 51),
                // (16,18): warning CS8601: Possible null reference assignment.
                //         ptr1(ref str1);
                Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "str1").WithLocation(16, 18),
                // (18,32): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'.
                //         ref string? str3 = ref ptr1(ref str2);
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1(ref str2)").WithArguments("string", "string?").WithLocation(18, 32),
                // (19,51): warning CS8619: Nullability of reference types in value of type 'delegate*<ref string, string>' doesn't match target type 'delegate*<ref string?, string>'.
                //         delegate*<ref string?, ref string> ptr2 = ptr1;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1").WithArguments("delegate*<ref string, string>", "delegate*<ref string?, string>").WithLocation(19, 51),
                // (20,51): warning CS8619: Nullability of reference types in value of type 'delegate*<ref string, string>' doesn't match target type 'delegate*<ref string, string?>'.
                //         delegate*<ref string, ref string?> ptr3 = ptr1;
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1").WithArguments("delegate*<ref string, string>", "delegate*<ref string, string?>").WithLocation(20, 51)
            );
        }

7186
        [ConditionalFact(typeof(CoreClrOnly))]
F
Fredric Silberberg 已提交
7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223
        public void SpanInArgumentAndReturn()
        {
            var comp = CompileAndVerifyFunctionPointers(@"
using System;
public class C
{
    static char[] chars = new[] { '1', '2', '3', '4' };

    static Span<char> ChopSpan(Span<char> span) => span[..^1];

    public static unsafe void Main()
    {
        delegate*<Span<char>, Span<char>> ptr = &ChopSpan;
        Console.Write(new string(ptr(chars)));
    }
}
", targetFramework: TargetFramework.NetCoreApp30, expectedOutput: "123");

            comp.VerifyIL("C.Main", @"
{
  // Code size       39 (0x27)
  .maxstack  2
  .locals init (delegate*<System.Span<char>, System.Span<char>> V_0)
  IL_0000:  ldftn      ""System.Span<char> C.ChopSpan(System.Span<char>)""
  IL_0006:  stloc.0
  IL_0007:  ldsfld     ""char[] C.chars""
  IL_000c:  call       ""System.Span<char> System.Span<char>.op_Implicit(char[])""
  IL_0011:  ldloc.0
  IL_0012:  calli      ""delegate*<System.Span<char>, System.Span<char>>""
  IL_0017:  call       ""System.ReadOnlySpan<char> System.Span<char>.op_Implicit(System.Span<char>)""
  IL_001c:  newobj     ""string..ctor(System.ReadOnlySpan<char>)""
  IL_0021:  call       ""void System.Console.Write(string)""
  IL_0026:  ret
}
");
        }

7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251
        [Fact, WorkItem(45447, "https://github.com/dotnet/roslyn/issues/45447")]
        public void LocalFunction_ValidStatic()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class FunctionPointer
{
    public static void Main()
    {
        delegate*<void> a = &local;
        a();

        static void local() => System.Console.Write(""local"");
    }
}
", expectedOutput: "local");


            verifier.VerifyIL("FunctionPointer.Main", @"
{
  // Code size       12 (0xc)
  .maxstack  1
  IL_0000:  ldftn      ""void FunctionPointer.<Main>g__local|0_0()""
  IL_0006:  calli      ""delegate*<void>""
  IL_000b:  ret
}
");
        }

F
Fredric Silberberg 已提交
7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335
        [Fact, WorkItem(45447, "https://github.com/dotnet/roslyn/issues/45447")]
        public void LocalFunction_ValidStatic_NestedInLocalFunction()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class FunctionPointer
{
    public static void Main()
    {
        local(true);

        static void local(bool invoke)
        {
            if (invoke)
            {
                delegate*<bool, void> ptr = &local;
                ptr(false);
            }
            else
            {
                System.Console.Write(""local"");
            }
        }
    }
}
", expectedOutput: "local");


            verifier.VerifyIL("FunctionPointer.<Main>g__local|0_0(bool)", @"
{
  // Code size       29 (0x1d)
  .maxstack  2
  .locals init (delegate*<bool, void> V_0)
  IL_0000:  ldarg.0
  IL_0001:  brfalse.s  IL_0012
  IL_0003:  ldftn      ""void FunctionPointer.<Main>g__local|0_0(bool)""
  IL_0009:  stloc.0
  IL_000a:  ldc.i4.0
  IL_000b:  ldloc.0
  IL_000c:  calli      ""delegate*<bool, void>""
  IL_0011:  ret
  IL_0012:  ldstr      ""local""
  IL_0017:  call       ""void System.Console.Write(string)""
  IL_001c:  ret
}
");
        }

        [Fact]
        public void LocalFunction_ValidStatic_NestedInLambda()
        {
            var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class C
{
    public static void Main()
    {
        int capture = 1;
        System.Action _ = () =>
        {
            System.Console.Write(capture); // Just to ensure that this is emitted as a capture
            delegate*<void> ptr = &local;
            ptr();

            static void local() => System.Console.Write(""local"");
        };

        _();
    }
}
", expectedOutput: "1local");

            verifier.VerifyIL("C.<>c__DisplayClass0_0.<Main>b__0()", expectedIL: @"
{
  // Code size       23 (0x17)
  .maxstack  1
  IL_0000:  ldarg.0
  IL_0001:  ldfld      ""int C.<>c__DisplayClass0_0.capture""
  IL_0006:  call       ""void System.Console.Write(int)""
  IL_000b:  ldftn      ""void C.<Main>g__local|0_1()""
  IL_0011:  calli      ""delegate*<void>""
  IL_0016:  ret
}
");
        }

7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363
        [Fact, WorkItem(45447, "https://github.com/dotnet/roslyn/issues/45447")]
        public void LocalFunction_InvalidNonStatic()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class FunctionPointer
{
    public static void M()
    {
        int local = 1;

        delegate*<void> first = &noCaptures;
        delegate*<void> second = &capturesLocal;

        void noCaptures() { }
        void capturesLocal() { local++; }
    }
}");

            comp.VerifyDiagnostics(
                // (8,34): error CS8759: Cannot create a function pointer for 'noCaptures()' because it is not a static method
                //         delegate*<void> first = &noCaptures;
                Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "noCaptures").WithArguments("noCaptures()").WithLocation(8, 34),
                // (9,35): error CS8759: Cannot create a function pointer for 'capturesLocal()' because it is not a static method
                //         delegate*<void> second = &capturesLocal;
                Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "capturesLocal").WithArguments("capturesLocal()").WithLocation(9, 35)
            );
        }

7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403
        [Fact, WorkItem(45418, "https://github.com/dotnet/roslyn/issues/45418")]
        public void RefMismatchInCall()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Test
{
    void M1(delegate*<ref string, void> param1)
    {
        param1(out var l);
        string s = null;
        param1(s);
        param1(in s);
    }

    void M2(delegate*<in string, void> param2)
    {
        param2(out var l);
        string s = null;
        param2(s);
        param2(ref s);
    }

    void M3(delegate*<out string, void> param3)
    {
        string s = null;
        param3(s);
        param3(ref s);
        param3(in s);
    }

    void M4(delegate*<string, void> param4)
    {
        param4(out var l);
        string s = null;
        param4(ref s);
        param4(in s);
    }
}");

            comp.VerifyDiagnostics(
F
Fredric Silberberg 已提交
7404
                // (6,20): error CS1620: Argument 1 must be passed with the 'ref' keyword
7405
                //         param1(out var l);
F
Fredric Silberberg 已提交
7406 7407
                Diagnostic(ErrorCode.ERR_BadArgRef, "var l").WithArguments("1", "ref").WithLocation(6, 20),
                // (8,16): error CS1620: Argument 1 must be passed with the 'ref' keyword
7408
                //         param1(s);
F
Fredric Silberberg 已提交
7409 7410
                Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "ref").WithLocation(8, 16),
                // (9,19): error CS1620: Argument 1 must be passed with the 'ref' keyword
7411
                //         param1(in s);
F
Fredric Silberberg 已提交
7412 7413
                Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "ref").WithLocation(9, 19),
                // (14,20): error CS1615: Argument 1 may not be passed with the 'out' keyword
7414
                //         param2(out var l);
F
Fredric Silberberg 已提交
7415 7416
                Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var l").WithArguments("1", "out").WithLocation(14, 20),
                // (17,20): error CS1615: Argument 1 may not be passed with the 'ref' keyword
7417
                //         param2(ref s);
F
Fredric Silberberg 已提交
7418 7419
                Diagnostic(ErrorCode.ERR_BadArgExtraRef, "s").WithArguments("1", "ref").WithLocation(17, 20),
                // (23,16): error CS1620: Argument 1 must be passed with the 'out' keyword
7420
                //         param3(s);
F
Fredric Silberberg 已提交
7421 7422
                Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(23, 16),
                // (24,20): error CS1620: Argument 1 must be passed with the 'out' keyword
7423
                //         param3(ref s);
F
Fredric Silberberg 已提交
7424 7425
                Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(24, 20),
                // (25,19): error CS1620: Argument 1 must be passed with the 'out' keyword
7426
                //         param3(in s);
F
Fredric Silberberg 已提交
7427 7428
                Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(25, 19),
                // (30,20): error CS1615: Argument 1 may not be passed with the 'out' keyword
7429
                //         param4(out var l);
F
Fredric Silberberg 已提交
7430 7431
                Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var l").WithArguments("1", "out").WithLocation(30, 20),
                // (32,20): error CS1615: Argument 1 may not be passed with the 'ref' keyword
7432
                //         param4(ref s);
F
Fredric Silberberg 已提交
7433 7434
                Diagnostic(ErrorCode.ERR_BadArgExtraRef, "s").WithArguments("1", "ref").WithLocation(32, 20),
                // (33,19): error CS1615: Argument 1 may not be passed with the 'in' keyword
7435
                //         param4(in s);
F
Fredric Silberberg 已提交
7436
                Diagnostic(ErrorCode.ERR_BadArgExtraRef, "s").WithArguments("1", "in").WithLocation(33, 19)
7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500
            );
        }

        [Fact]
        public void MismatchedInferredLambdaReturn()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
    public void M(delegate*<System.Func<string>, void> param)
    {
        param(a => a);
    }
}");

            comp.VerifyDiagnostics(
                // (6,15): error CS1593: Delegate 'Func<string>' does not take 1 arguments
                //         param(a => a);
                Diagnostic(ErrorCode.ERR_BadDelArgCount, "a => a").WithArguments("System.Func<string>", "1").WithLocation(6, 15)
            );

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

            var lambda = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();

            Assert.Equal("a => a", lambda.ToString());

            var info = model.GetSymbolInfo(lambda);
            var lambdaSymbol = (IMethodSymbol)info.Symbol!;
            Assert.NotNull(lambdaSymbol);
            Assert.Equal("System.String", lambdaSymbol.ReturnType.ToTestDisplayString(includeNonNullable: false));
            Assert.True(lambdaSymbol.Parameters.Single().Type.IsErrorType());
        }

        [Fact, WorkItem(45418, "https://github.com/dotnet/roslyn/issues/45418")]
        public void OutDeconstructionMismatch()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Test
{
    void M1(delegate*<string, void> param1, object o)
    {
        param1(o is var (a, b));
        param1(o is (var c, var d));
    }
}");

            comp.VerifyDiagnostics(
                // (6,25): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
                //         param1(o is var (a, b));
                Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a, b)").WithArguments("object", "Deconstruct").WithLocation(6, 25),
                // (6,25): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type.
                //         param1(o is var (a, b));
                Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a, b)").WithArguments("object", "2").WithLocation(6, 25),
                // (7,21): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
                //         param1(o is (var c, var d));
                Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(var c, var d)").WithArguments("object", "Deconstruct").WithLocation(7, 21),
                // (7,21): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type.
                //         param1(o is (var c, var d));
                Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(var c, var d)").WithArguments("object", "2").WithLocation(7, 21)
            );
        }

7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536
        [Fact]
        public void UnusedLoadNotLeftOnStack()
        {
            string source = @"
unsafe class FunctionPointer
{
    public static void Main()
    {
        delegate*<void> ptr = &Main;
    }
}
";
            var verifier = CompileAndVerifyFunctionPointers(source, expectedOutput: "", options: TestOptions.UnsafeReleaseExe);

            verifier.VerifyIL(@"FunctionPointer.Main", expectedIL: @"
{
  // Code size        1 (0x1)
  .maxstack  0
  IL_0000:  ret
}
");

            verifier = CompileAndVerifyFunctionPointers(source, expectedOutput: "", options: TestOptions.UnsafeDebugExe);
            verifier.VerifyIL("FunctionPointer.Main", @"
{
  // Code size        9 (0x9)
  .maxstack  1
  .locals init (delegate*<void> V_0) //ptr
  IL_0000:  nop
  IL_0001:  ldftn      ""void FunctionPointer.Main()""
  IL_0007:  stloc.0
  IL_0008:  ret
}
");
        }

7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551
        [Fact]
        public void UnmanagedOnUnsupportedRuntime()
        {
            var comp = CreateCompilationWithFunctionPointers(@"
#pragma warning disable CS0168 // Unused variable
class C
{
    unsafe void M()
    {
        delegate* unmanaged<void> ptr1;
        delegate* unmanaged[Stdcall, Thiscall]<void> ptr2;
    }
}");

            comp.VerifyDiagnostics(
7552
                // (7,19): error CS8889: The target runtime doesn't support extensible or runtime-environment default calling conventions.
7553 7554
                //         delegate* unmanaged<void> ptr1;
                Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv, "unmanaged").WithLocation(7, 19),
7555
                // (8,19): error CS8889: The target runtime doesn't support extensible or runtime-environment default calling conventions.
7556
                //         delegate* unmanaged[Stdcall, Thiscall]<void> ptr2;
F
Fredric Silberberg 已提交
7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568
                Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv, "unmanaged").WithLocation(8, 19)
            );

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

            var functionPointerSyntaxes = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().ToArray();

            Assert.Equal(2, functionPointerSyntaxes.Length);

            VerifyFunctionPointerSemanticInfo(model, functionPointerSyntaxes[0],
                expectedSyntax: "delegate* unmanaged<void>",
7569 7570
                expectedType: "delegate* unmanaged<System.Void>",
                expectedSymbol: "delegate* unmanaged<System.Void>");
F
Fredric Silberberg 已提交
7571 7572 7573

            VerifyFunctionPointerSemanticInfo(model, functionPointerSyntaxes[1],
                expectedSyntax: "delegate* unmanaged[Stdcall, Thiscall]<void>",
7574 7575
                expectedType: "delegate* unmanaged[Stdcall, Thiscall]<System.Void modopt(System.Runtime.CompilerServices.CallConvStdcall) modopt(System.Runtime.CompilerServices.CallConvThiscall)>",
                expectedSymbol: "delegate* unmanaged[Stdcall, Thiscall]<System.Void modopt(System.Runtime.CompilerServices.CallConvStdcall) modopt(System.Runtime.CompilerServices.CallConvThiscall)>");
F
Fredric Silberberg 已提交
7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608
        }

        [Fact]
        public void NonPublicCallingConventionType()
        {
            string source1 = @"
namespace System
{
    public class Object { }
    public abstract class ValueType { }
    public struct Void { }
    public class String { }
    namespace Runtime.CompilerServices
    {
        internal class CallConvTest {}
        public static class RuntimeFeature
        {
            public const string UnmanagedSignatureCallingConvention = nameof(UnmanagedSignatureCallingConvention);
        }
    }
}
";

            string source2 = @"
#pragma warning disable CS0168 // Unused local
unsafe class C
{
    void M()
    {
        delegate* unmanaged[Test]<void> ptr = null;
    }
}
";
7609
            var allInCoreLib = CreateEmptyCompilation(source1 + source2, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
F
Fredric Silberberg 已提交
7610
            allInCoreLib.VerifyDiagnostics(
7611
                // (23,29): error CS8891: Type 'CallConvTest' must be public to be used as a calling convention.
F
Fredric Silberberg 已提交
7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622
                //         delegate* unmanaged[Test]<void> ptr = null;
                Diagnostic(ErrorCode.ERR_TypeMustBePublic, "Test").WithArguments("System.Runtime.CompilerServices.CallConvTest").WithLocation(23, 29)
            );

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

            var functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();

            VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
                expectedSyntax: "delegate* unmanaged[Test]<void>",
7623 7624
                expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest)>",
                expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest)>");
F
Fredric Silberberg 已提交
7625 7626 7627 7628

            var coreLib = CreateEmptyCompilation(source1);
            coreLib.VerifyDiagnostics();

7629
            var comp1 = CreateEmptyCompilation(source2, references: new[] { coreLib.EmitToImageReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
F
Fredric Silberberg 已提交
7630
            comp1.VerifyDiagnostics(
7631
                // (7,29): error CS8891: Type 'CallConvTest' must be public to be used as a calling convention.
F
Fredric Silberberg 已提交
7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642
                //         delegate* unmanaged[Test]<void> ptr = null;
                Diagnostic(ErrorCode.ERR_TypeMustBePublic, "Test").WithArguments("System.Runtime.CompilerServices.CallConvTest").WithLocation(7, 29)
            );

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

            functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();

            VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
                expectedSyntax: "delegate* unmanaged[Test]<void>",
7643 7644
                expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest)>",
                expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest)>");
F
Fredric Silberberg 已提交
7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677
        }

        [Fact]
        public void GenericCallingConventionType()
        {
            string source1 = @"
namespace System
{
    public class Object { }
    public abstract class ValueType { }
    public struct Void { }
    public class String { }
    namespace Runtime.CompilerServices
    {
        public class CallConvTest<T> {}
        public static class RuntimeFeature
        {
            public const string UnmanagedSignatureCallingConvention = nameof(UnmanagedSignatureCallingConvention);
        }
    }
}
";

            string source2 = @"
#pragma warning disable CS0168 // Unused local
unsafe class C
{
    void M()
    {
        delegate* unmanaged[Test]<void> ptr = null;
    }
}
";
7678
            var allInCoreLib = CreateEmptyCompilation(source1 + source2, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
F
Fredric Silberberg 已提交
7679
            allInCoreLib.VerifyDiagnostics(
7680
                // (23,29): error CS8890: Type 'CallConvTest' is not defined.
F
Fredric Silberberg 已提交
7681 7682
                //         delegate* unmanaged[Test]<void> ptr = null;
                Diagnostic(ErrorCode.ERR_TypeNotFound, "Test").WithArguments("CallConvTest").WithLocation(23, 29)
7683
            );
F
Fredric Silberberg 已提交
7684 7685 7686 7687 7688 7689 7690 7691

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

            var functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();

            VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
                expectedSyntax: "delegate* unmanaged[Test]<void>",
7692 7693
                expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>",
                expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>");
F
Fredric Silberberg 已提交
7694 7695 7696 7697

            var coreLib = CreateEmptyCompilation(source1);
            coreLib.VerifyDiagnostics();

7698
            var comp1 = CreateEmptyCompilation(source2, references: new[] { coreLib.EmitToImageReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
F
Fredric Silberberg 已提交
7699
            comp1.VerifyDiagnostics(
7700
                // (7,29): error CS8890: Type 'CallConvTest' is not defined.
F
Fredric Silberberg 已提交
7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711
                //         delegate* unmanaged[Test]<void> ptr = null;
                Diagnostic(ErrorCode.ERR_TypeNotFound, "Test").WithArguments("CallConvTest").WithLocation(7, 29)
            );

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

            functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();

            VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
                expectedSyntax: "delegate* unmanaged[Test]<void>",
7712 7713
                expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>",
                expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>");
F
Fredric Silberberg 已提交
7714 7715 7716 7717

            var @string = comp1.GetSpecialType(SpecialType.System_String);
            var testMod = CSharpCustomModifier.CreateOptional(comp1.GetTypeByMetadataName("System.Runtime.CompilerServices.CallConvTest`1"));

F
Fredric Silberberg 已提交
7718
            var funcPtr = FunctionPointerTypeSymbol.CreateFromPartsForTests(
F
Fredric Silberberg 已提交
7719
                CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: default,
7720 7721
                returnRefKind: RefKind.None, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
                parameterRefCustomModifiers: default, compilation: comp1);
F
Fredric Silberberg 已提交
7722
            var funcPtrRef = FunctionPointerTypeSymbol.CreateFromPartsForTests(
F
Fredric Silberberg 已提交
7723
                CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: default,
7724 7725
                parameterRefCustomModifiers: default, returnRefKind: RefKind.Ref, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
                compilation: comp1);
F
Fredric Silberberg 已提交
7726

F
Fredric Silberberg 已提交
7727
            var funcPtrWithTestOnReturn = FunctionPointerTypeSymbol.CreateFromPartsForTests(
F
Fredric Silberberg 已提交
7728
                CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string, customModifiers: ImmutableArray.Create(testMod)), refCustomModifiers: default,
7729 7730
                parameterRefCustomModifiers: default, returnRefKind: RefKind.None, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
                compilation: comp1);
F
Fredric Silberberg 已提交
7731
            var funcPtrWithTestOnRef = FunctionPointerTypeSymbol.CreateFromPartsForTests(
F
Fredric Silberberg 已提交
7732
                CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: ImmutableArray.Create(testMod),
7733 7734
                parameterRefCustomModifiers: default, returnRefKind: RefKind.Ref, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
                compilation: comp1);
F
Fredric Silberberg 已提交
7735

F
Fredric Silberberg 已提交
7736 7737
            Assert.Empty(funcPtrWithTestOnReturn.Signature.GetCallingConventionModifiers());
            Assert.Empty(funcPtrWithTestOnRef.Signature.GetCallingConventionModifiers());
F
Fredric Silberberg 已提交
7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767
            Assert.True(funcPtr.Equals(funcPtrWithTestOnReturn, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds));
            Assert.False(funcPtr.Equals(funcPtrWithTestOnReturn, TypeCompareKind.ConsiderEverything));
            Assert.True(funcPtrRef.Equals(funcPtrWithTestOnRef, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds));
            Assert.False(funcPtrRef.Equals(funcPtrWithTestOnRef, TypeCompareKind.ConsiderEverything));
        }

        [Fact]
        public void ConventionDefinedInWrongAssembly()
        {
            var source1 = @"
namespace System.Runtime.CompilerServices
{
    public class CallConvTest { }
}
";

            var source2 = @"
#pragma warning disable CS0168 // Unused local
unsafe class C
{
    static void M()
    {
        delegate* unmanaged[Test]<void> ptr;
    }
}
";

            var comp1 = CreateCompilationWithFunctionPointers(source1 + source2);
            comp1.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            comp1.VerifyDiagnostics(
7768
                // (12,29): error CS8890: Type 'CallConvTest' is not defined.
F
Fredric Silberberg 已提交
7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779
                //         delegate* unmanaged[Test]<void> ptr;
                Diagnostic(ErrorCode.ERR_TypeNotFound, "Test").WithArguments("CallConvTest").WithLocation(12, 29)
            );

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

            var functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();

            VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
                expectedSyntax: "delegate* unmanaged[Test]<void>",
7780 7781
                expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>",
                expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>");
F
Fredric Silberberg 已提交
7782 7783 7784 7785 7786

            var reference = CreateCompilation(source1);
            var comp2 = CreateCompilationWithFunctionPointers(source2, new[] { reference.EmitToImageReference() });
            comp2.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            comp2.VerifyDiagnostics(
7787
                // (7,29): error CS8890: Type 'CallConvTest' is not defined.
F
Fredric Silberberg 已提交
7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798
                //         delegate* unmanaged[Test]<void> ptr;
                Diagnostic(ErrorCode.ERR_TypeNotFound, "Test").WithArguments("CallConvTest").WithLocation(7, 29)
            );

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

            functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();

            VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
                expectedSyntax: "delegate* unmanaged[Test]<void>",
7799 7800
                expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>",
                expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>");
7801 7802 7803 7804

            var @string = comp2.GetSpecialType(SpecialType.System_String);
            var testMod = CSharpCustomModifier.CreateOptional(comp2.GetTypeByMetadataName("System.Runtime.CompilerServices.CallConvTest"));

F
Fredric Silberberg 已提交
7805
            var funcPtr = FunctionPointerTypeSymbol.CreateFromPartsForTests(
7806
                CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: default,
7807 7808
                returnRefKind: RefKind.None, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
                parameterRefCustomModifiers: default, compilation: comp2);
F
Fredric Silberberg 已提交
7809
            var funcPtrRef = FunctionPointerTypeSymbol.CreateFromPartsForTests(
7810
                CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: default,
7811 7812
                returnRefKind: RefKind.Ref, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
                parameterRefCustomModifiers: default, compilation: comp2);
7813

F
Fredric Silberberg 已提交
7814
            var funcPtrWithTestOnReturn = FunctionPointerTypeSymbol.CreateFromPartsForTests(
7815
                CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string, customModifiers: ImmutableArray.Create(testMod)), refCustomModifiers: default,
7816 7817
                returnRefKind: RefKind.None, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
                parameterRefCustomModifiers: default, compilation: comp2);
F
Fredric Silberberg 已提交
7818
            var funcPtrWithTestOnRef = FunctionPointerTypeSymbol.CreateFromPartsForTests(
7819
                CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: ImmutableArray.Create(testMod),
7820 7821
                returnRefKind: RefKind.Ref, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
                parameterRefCustomModifiers: default, compilation: comp2);
7822

F
Fredric Silberberg 已提交
7823 7824
            Assert.Empty(funcPtrWithTestOnReturn.Signature.GetCallingConventionModifiers());
            Assert.Empty(funcPtrWithTestOnRef.Signature.GetCallingConventionModifiers());
7825 7826 7827 7828
            Assert.True(funcPtr.Equals(funcPtrWithTestOnReturn, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds));
            Assert.False(funcPtr.Equals(funcPtrWithTestOnReturn, TypeCompareKind.ConsiderEverything));
            Assert.True(funcPtrRef.Equals(funcPtrWithTestOnRef, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds));
            Assert.False(funcPtrRef.Equals(funcPtrWithTestOnRef, TypeCompareKind.ConsiderEverything));
7829 7830
        }

7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844
        private const string UnmanagedCallersOnlyAttribute = @"
namespace System.Runtime.InteropServices
{
    [AttributeUsage(AttributeTargets.Method, Inherited = false)]
    public sealed class UnmanagedCallersOnlyAttribute : Attribute
    {
        public UnmanagedCallersOnlyAttribute()
        {
        }

        public Type[] CallConvs;
        public string EntryPoint;
    }
}
7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865
";

        private const string UnmanagedCallersOnlyAttributeIl = @"
.class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute
    extends [mscorlib]System.Attribute
{
    .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = (
        01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72
        69 74 65 64 00
    )
    .field public class [mscorlib]System.Type[] CallConvs
    .field public string EntryPoint

    .method public hidebysig specialname rtspecialname 
        instance void .ctor () cil managed 
    {
        ldarg.0
        call instance void [mscorlib]System.Attribute::.ctor()
        ret
    }
}
7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884
";

        [Fact]
        public void UnmanagedCallersOnlyRequiresStatic()
        {
            var comp = CreateCompilation(new[] { @"
#pragma warning disable 8321 // Unreferenced local function
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly]
    void M1() {}

    public void M2()
    {
        [UnmanagedCallersOnly]
        void local() {}
    }
}
7885
", UnmanagedCallersOnlyAttribute });
7886 7887

            comp.VerifyDiagnostics(
7888
                // (6,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
7889 7890
                //     [UnmanagedCallersOnly]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(6, 6),
7891
                // (11,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913
                //         [UnmanagedCallersOnly]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(11, 10)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyAllowedOnStatics()
        {
            var comp = CreateCompilation(new[] { @"
#pragma warning disable 8321 // Unreferenced local function
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly]
    static void M1() {}

    public void M2()
    {
        [UnmanagedCallersOnly]
        static void local() {}
    }
}
7914
", UnmanagedCallersOnlyAttribute });
7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952

            comp.VerifyDiagnostics();
        }

        [Fact]
        public void UnmanagedCallersOnlyCallConvsMustComeFromCorrectNamespace()
        {
            var comp = CreateEmptyCompilation(new[] { @"
using System.Runtime.InteropServices;
namespace System
{
    public class Object { }
    public abstract class ValueType { }
    public struct Void { }
    public abstract partial class Enum : ValueType {}
    public class String { }
    public struct Boolean { }
    public struct Int32 { }
    public class Type { }
    public class Attribute { }
    public class AttributeUsageAttribute : Attribute
    {
        public AttributeUsageAttribute(AttributeTargets validOn) {}
        public bool Inherited { get; set; }
    }
    public enum AttributeTargets { Method = 0x0040, }
}
class CallConvTest
{
}
class C
{
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })]
    static void M() {}
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
7953
                // (26,6): error CS8893: 'CallConvTest' is not a valid calling convention type for 'UnmanagedCallersOnly'.
7954 7955 7956 7957 7958
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })]
                Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })").WithArguments("CallConvTest").WithLocation(26, 6)
            );
        }

7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003
        [Fact]
        public void UnmanagedCallersOnlyCallConvsMustNotBeNestedType()
        {
            var comp = CreateEmptyCompilation(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System
{
    public class Object { }
    public abstract class ValueType { }
    public struct Void { }
    public abstract partial class Enum : ValueType {}
    public class String { }
    public struct Boolean { }
    public struct Int32 { }
    public class Type { }
    public class Attribute { }
    public class AttributeUsageAttribute : Attribute
    {
        public AttributeUsageAttribute(AttributeTargets validOn) {}
        public bool Inherited { get; set; }
    }
    public enum AttributeTargets { Method = 0x0040, }
    namespace Runtime.CompilerServices
    {
        public class CallConvTestA
        {
            public class CallConvTestB { }
        }
    }
}
class C
{
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTestA.CallConvTestB) })]
    static void M() {}
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (31,6): error CS8893: 'CallConvTestA.CallConvTestB' is not a valid calling convention type for 'UnmanagedCallersOnly'.
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTestA.CallConvTestB) })]
                Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTestA.CallConvTestB) })").WithArguments("System.Runtime.CompilerServices.CallConvTestA.CallConvTestB").WithLocation(31, 6)
            );
        }

8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023
        [Fact]
        public void UnmanagedCallersOnlyCallConvsMustComeFromCorelib()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Runtime.CompilerServices
{
    class CallConvTest
    {
    }
}
class C
{
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })]
    static void M() {}
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
8024
                // (12,6): error CS8893: 'CallConvTest' is not a valid calling convention type for 'UnmanagedCallersOnly'.
8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })]
                Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })").WithArguments("System.Runtime.CompilerServices.CallConvTest").WithLocation(12, 6)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyCallConvsMustStartWithCallConv()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(ExtensionAttribute) })]
    static void M() {}
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
8044
                // (6,6): error CS8893: 'ExtensionAttribute' is not a valid calling convention type for 'UnmanagedCallersOnly'.
8045 8046 8047 8048 8049 8050
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.ExtensionAttribute) })]
                Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(ExtensionAttribute) })").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(6, 6)
            );
        }

        [Fact]
8051
        public void UnmanagedCallersOnlyCallConvNull_InSource()
8052
        {
8053
            var comp = CreateCompilationWithFunctionPointers(new[] { @"
8054 8055 8056 8057 8058
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly(CallConvs = new System.Type[] { null })]
    static void M() {}
8059 8060 8061 8062 8063

    unsafe static void M1()
    {
        delegate* unmanaged<void> ptr = &M;
    }
8064 8065 8066
}
", UnmanagedCallersOnlyAttribute });

8067
            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
8068
            comp.VerifyDiagnostics(
8069
                // (5,6): error CS8893: 'null' is not a valid calling convention type for 'UnmanagedCallersOnly'.
8070 8071 8072 8073 8074
                //     [UnmanagedCallersOnly(CallConvs = new System.Type[] { null })]
                Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new System.Type[] { null })").WithArguments("null").WithLocation(5, 6)
            );
        }

8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100
        [Fact]
        public void UnmanagedCallersOnlyCallConvNull_InMetadata()
        {
            var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static void M () cil managed 
    {
        // [UnmanagedCallersOnly(CallConvs = new Type[] { null })]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 01 00 53 1d 50 09 43 61 6c 6c 43 6f 6e 76
            73 01 00 00 00 ff
        )

        ret
    }
} 
";

            var comp = CreateCompilationWithFunctionPointersAndIl(@"
class D
{
    unsafe static void M1()
    {
F
Fredric Silberberg 已提交
8101
        C.M();
8102 8103 8104 8105 8106 8107 8108
        delegate* unmanaged<void> ptr = &C.M;
    }
}
", il);

            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            comp.VerifyDiagnostics(
F
Fredric Silberberg 已提交
8109 8110 8111
                // (6,9): error CS8901: 'C.M()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
                //         C.M();
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "C.M()").WithArguments("C.M()").WithLocation(6, 9)
8112
            );
F
Fredric Silberberg 已提交
8113 8114 8115 8116 8117 8118 8119

            var c = comp.GetTypeByMetadataName("C");
            var m1 = c.GetMethod("M");
            var unmanagedData = m1.GetUnmanagedCallersOnlyAttributeData(forceComplete: true);
            Assert.NotSame(unmanagedData, UnmanagedCallersOnlyAttributeData.Uninitialized);
            Assert.NotSame(unmanagedData, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound);
            Assert.Empty(unmanagedData!.CallingConventionTypes);
8120 8121
        }

8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140
        [Fact]
        public void UnmanagedCallersOnlyCallConvDefault()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly(CallConvs = new System.Type[] { default })]
    static void M() {}
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (5,6): error CS8893: 'null' is not a valid calling convention type for 'UnmanagedCallersOnly'.
                //     [UnmanagedCallersOnly(CallConvs = new System.Type[] { default })]
                Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new System.Type[] { default })").WithArguments("null").WithLocation(5, 6)
            );
        }

8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166
        [Fact]
        public void UnmanagedCallersOnlyRequiresUnmanagedTypes_Errors()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly]
    static string M1() => throw null;

    [UnmanagedCallersOnly]
    static void M2(object o) {}

    [UnmanagedCallersOnly]
    static T M3<T>() => throw null;

    [UnmanagedCallersOnly]
    static void M4<T>(T t) {}

    [UnmanagedCallersOnly]
    static T M5<T>() where T : struct => throw null;

    [UnmanagedCallersOnly]
    static void M6<T>(T t) where T : struct {}

    [UnmanagedCallersOnly]
8167
    static T M7<T>() where T : unmanaged => throw null;
8168 8169

    [UnmanagedCallersOnly]
8170
    static void M8<T>(T t) where T : unmanaged {}
8171 8172 8173 8174
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
8175
                // (6,12): error CS8894: Cannot use 'string' as a return type on a method attributed with 'UnmanagedCallersOnly'.
8176 8177
                //     static string M1() => throw null;
                Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "string").WithArguments("string", "return").WithLocation(6, 12),
8178
                // (9,20): error CS8894: Cannot use 'object' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
8179 8180
                //     static void M2(object o) {}
                Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "object o").WithArguments("object", "parameter").WithLocation(9, 20),
8181 8182 8183
                // (11,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //     [UnmanagedCallersOnly]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(11, 6),
8184
                // (12,12): error CS8894: Cannot use 'T' as a return type on a method attributed with 'UnmanagedCallersOnly'.
8185 8186
                //     static T M3<T>() => throw null;
                Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "T").WithArguments("T", "return").WithLocation(12, 12),
8187 8188 8189
                // (14,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //     [UnmanagedCallersOnly]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(14, 6),
8190
                // (15,23): error CS8894: Cannot use 'T' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
8191 8192
                //     static void M4<T>(T t) {}
                Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "T t").WithArguments("T", "parameter").WithLocation(15, 23),
8193 8194 8195
                // (17,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //     [UnmanagedCallersOnly]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(17, 6),
8196
                // (18,12): error CS8894: Cannot use 'T' as a return type on a method attributed with 'UnmanagedCallersOnly'.
8197 8198
                //     static T M5<T>() where T : struct => throw null;
                Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "T").WithArguments("T", "return").WithLocation(18, 12),
8199 8200 8201
                // (20,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //     [UnmanagedCallersOnly]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(20, 6),
8202
                // (21,23): error CS8894: Cannot use 'T' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
8203 8204
                //     static void M6<T>(T t) where T : struct {}
                Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "T t").WithArguments("T", "parameter").WithLocation(21, 23),
8205 8206 8207 8208 8209 8210
                // (23,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //     [UnmanagedCallersOnly]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(23, 6),
                // (26,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //     [UnmanagedCallersOnly]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(26, 6)
8211
            );
8212 8213 8214 8215 8216 8217 8218
        }

        [Fact]
        public void UnmanagedCallersOnlyRequiresUnmanagedTypes_Valid()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
8219 8220 8221 8222 8223
#pragma warning disable CS0169 // unused private field
struct S
{
    private int _field;
}
8224 8225 8226 8227 8228 8229 8230 8231 8232
class C
{
    [UnmanagedCallersOnly]
    static int M1() => throw null;

    [UnmanagedCallersOnly]
    static void M2(int o) {}

    [UnmanagedCallersOnly]
8233
    static S M3() => throw null;
8234 8235

    [UnmanagedCallersOnly]
8236
    public static void M4(S s) {}
8237 8238 8239 8240 8241 8242

    [UnmanagedCallersOnly]
    static int? M5() => throw null;

    [UnmanagedCallersOnly]
    static void M6(int? o) {}
8243 8244 8245 8246 8247 8248 8249
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics();
        }

        [Fact]
8250
        public void UnmanagedCallersOnlyRequiresUnmanagedTypes_MethodWithGenericParameter()
8251 8252
        {
            var comp = CreateCompilation(new[] { @"
8253
#pragma warning disable CS8321 // Unused local function
8254 8255 8256 8257 8258 8259 8260
using System.Runtime.InteropServices;
public struct S<T> where T : unmanaged
{
    public T t;
}
class C
{
8261
    [UnmanagedCallersOnly] // 1
8262 8263
    static S<T> M1<T>() where T : unmanaged => throw null;

8264
    [UnmanagedCallersOnly] // 2
8265
    static void M2<T>(S<T> o) where T : unmanaged {}
8266 8267 8268

    static void M3<T>()
    {
8269
        [UnmanagedCallersOnly] // 3
8270
        static void local1() {}
8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282

        static void local2()
        {
            [UnmanagedCallersOnly] // 4
            static void local3() { }
        }

        System.Action a = () =>
        {
            [UnmanagedCallersOnly] // 5
            static void local4() { }
        };
8283 8284 8285 8286
    }

    static void M4()
    {
8287
        [UnmanagedCallersOnly] // 6
8288 8289
        static void local2<T>() {}
    }
8290 8291 8292 8293
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
8294 8295 8296 8297 8298 8299
                // (10,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //     [UnmanagedCallersOnly] // 1
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(10, 6),
                // (13,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //     [UnmanagedCallersOnly] // 2
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(13, 6),
8300
                // (18,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
8301
                //         [UnmanagedCallersOnly] // 3
8302 8303 8304 8305 8306 8307 8308 8309 8310 8311
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(18, 10),
                // (23,14): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //             [UnmanagedCallersOnly] // 4
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(23, 14),
                // (29,14): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //             [UnmanagedCallersOnly] // 5
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(29, 14),
                // (36,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //         [UnmanagedCallersOnly] // 6
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(36, 10)
8312 8313 8314
            );
        }

8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344
        [Fact]
        public void UnmanagedCallersOnlyRequiredUnmanagedTypes_MethodWithGenericParameter_InIl()
        {
            var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C extends [mscorlib]System.Object
{
    .method public hidebysig static void M<T> () cil managed 
    {
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 00 00
        )
        ret
    }
}
";

            var comp = CreateCompilationWithFunctionPointersAndIl(@"
unsafe
{
    delegate* unmanaged<void> ptr = C.M<int>;
}", il, options: TestOptions.UnsafeReleaseExe);

            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            comp.VerifyDiagnostics(
                // (4,37): error CS0570: 'C.M<T>()' is not supported by the language
                //     delegate* unmanaged<void> ptr = C.M<int>;
                Diagnostic(ErrorCode.ERR_BindToBogus, "C.M<int>").WithArguments("C.M<T>()").WithLocation(4, 37)
            );
        }

8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355
        [Fact]
        public void UnmanagedCallersOnlyRequiresUnmanagedTypes_TypeWithGenericParameter()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S<T> where T : unmanaged
{
    public T t;
}
class C<T> where T : unmanaged
{
8356
    [UnmanagedCallersOnly] // 1
8357 8358
    static S<T> M1() => throw null;

8359
    [UnmanagedCallersOnly] // 2
8360
    static void M2(S<T> o) {}
8361

8362
    [UnmanagedCallersOnly] // 3
8363 8364
    static S<int> M3() => throw null;

8365
    [UnmanagedCallersOnly] // 4
8366
    static void M4(S<int> o) {}
8367 8368 8369

    class C2
    {
8370
        [UnmanagedCallersOnly] // 5
8371 8372 8373 8374 8375
        static void M5() {}
    }

    struct S2
    {
8376
        [UnmanagedCallersOnly] // 6
8377 8378
        static void M6() {}
    }
8379 8380 8381 8382 8383 8384 8385

#pragma warning disable CS8321 // Unused local function
    static void M7()
    {
        [UnmanagedCallersOnly] // 7
        static void local1() { }
    }
8386 8387 8388
}
", UnmanagedCallersOnlyAttribute });

8389
            comp.VerifyDiagnostics(
8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406
                // (9,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //     [UnmanagedCallersOnly] // 1
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(9, 6),
                // (12,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //     [UnmanagedCallersOnly] // 2
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(12, 6),
                // (15,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //     [UnmanagedCallersOnly] // 3
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(15, 6),
                // (18,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //     [UnmanagedCallersOnly] // 4
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(18, 6),
                // (23,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //         [UnmanagedCallersOnly] // 5
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(23, 10),
                // (29,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //         [UnmanagedCallersOnly] // 6
8407 8408 8409 8410
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(29, 10),
                // (36,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
                //         [UnmanagedCallersOnly] // 7
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(36, 10)
8411 8412
            );
        }
8413

8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479
        [Fact]
        public void UnmanagedCallersOnlyRequiresUnmanagedTypes_TypeWithGenericParameter_InMetadata()
        {
            var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Object
{
    // Nested Types
    .class nested public auto ansi beforefieldinit NestedClass<T> extends [mscorlib]System.Object
    {
        .method public hidebysig static void M2 () cil managed 
        {
            .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
                01 00 00 00
            )
            ret
        }
    }

    .class nested public sequential ansi sealed beforefieldinit NestedStruct<T> extends [mscorlib]System.ValueType
    {
        .pack 0
        .size 1

        // Methods
        .method public hidebysig static void M3 () cil managed 
        {
            .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
                01 00 00 00
            )
            ret
        }
    }

    .method public hidebysig static void M1 () cil managed 
    {
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 00 00
        )
        ret
    }
}
";

            var comp = CreateCompilationWithFunctionPointersAndIl(@"
unsafe
{
    delegate* unmanaged<void> ptr1 = &C<int>.M1;
    delegate* unmanaged<void> ptr2 = &C<int>.NestedClass.M2;
    delegate* unmanaged<void> ptr3 = &C<int>.NestedStruct.M3;
}
", il, options: TestOptions.UnsafeReleaseExe);

            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            comp.VerifyDiagnostics(
                // (4,39): error CS0570: 'C<T>.M1()' is not supported by the language
                //     delegate* unmanaged<void> ptr1 = &C<int>.M1;
                Diagnostic(ErrorCode.ERR_BindToBogus, "C<int>.M1").WithArguments("C<T>.M1()").WithLocation(4, 39),
                // (5,39): error CS0570: 'C<T>.NestedClass.M2()' is not supported by the language
                //     delegate* unmanaged<void> ptr2 = &C<int>.NestedClass.M2;
                Diagnostic(ErrorCode.ERR_BindToBogus, "C<int>.NestedClass.M2").WithArguments("C<T>.NestedClass.M2()").WithLocation(5, 39),
                // (6,39): error CS0570: 'C<T>.NestedStruct.M3()' is not supported by the language
                //     delegate* unmanaged<void> ptr3 = &C<int>.NestedStruct.M3;
                Diagnostic(ErrorCode.ERR_BindToBogus, "C<int>.NestedStruct.M3").WithArguments("C<T>.NestedStruct.M3()").WithLocation(6, 39)
            );
        }

8480 8481 8482 8483 8484 8485 8486 8487 8488 8489
        [Fact]
        public void UnmanagedCallersOnlyRequiresUnmanagedTypes_TypeAndMethodWithGenericParameter()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C<T1>
{
    [UnmanagedCallersOnly]
    static void M<T2>() {}
}
F
Fredric Silberberg 已提交
8490
", UnmanagedCallersOnlyAttribute });
8491 8492 8493

            comp.VerifyDiagnostics(
                // (5,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
8494
                //     [UnmanagedCallersOnly]
8495
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(5, 6)
8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyRequiresUnmanagedTypes_StructWithGenericParameters_1()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S<T>
{
    public T t;
}
class C
{
    [UnmanagedCallersOnly]
    static S<int> M1() => throw null;

    [UnmanagedCallersOnly]
    static void M2(S<int> o) {}

    [UnmanagedCallersOnly]
    static S<S<int>> M2() => throw null;

    [UnmanagedCallersOnly]
    static void M3(S<S<int>> o) {}
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics();
        }

        [Fact]
        public void UnmanagedCallersOnlyRequiresUnmanagedTypes_StructWithGenericParameters_2()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S<T>
{
    public T t;
}
class C
{
    [UnmanagedCallersOnly]
    static S<object> M1() => throw null;

    [UnmanagedCallersOnly]
    static void M2(S<object> o) {}

    [UnmanagedCallersOnly]
    static S<S<object>> M2() => throw null;

    [UnmanagedCallersOnly]
    static void M3(S<S<object>> o) {}
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (10,12): error CS8894: Cannot use 'S<object>' as a return type on a method attributed with 'UnmanagedCallersOnly'.
                //     static S<object> M1() => throw null;
                Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "S<object>").WithArguments("S<object>", "return").WithLocation(10, 12),
                // (13,20): error CS8894: Cannot use 'S<object>' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
                //     static void M2(S<object> o) {}
                Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "S<object> o").WithArguments("S<object>", "parameter").WithLocation(13, 20),
                // (16,12): error CS8894: Cannot use 'S<S<object>>' as a return type on a method attributed with 'UnmanagedCallersOnly'.
                //     static S<S<object>> M2() => throw null;
                Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "S<S<object>>").WithArguments("S<S<object>>", "return").WithLocation(16, 12),
                // (19,20): error CS8894: Cannot use 'S<S<object>>' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
                //     static void M3(S<S<object>> o) {}
                Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "S<S<object>> o").WithArguments("S<S<object>>", "parameter").WithLocation(19, 20)
8565
            );
8566 8567
        }

8568
        [Fact]
F
Fredric Silberberg 已提交
8569
        public void UnmanagedCallersOnlyCannotCallMethodDirectly()
8570
        {
8571
            var comp = CreateCompilationWithFunctionPointers(new[] { @"
8572 8573 8574 8575 8576 8577
using System.Runtime.InteropServices;
public class C
{
    [UnmanagedCallersOnly]
    public static void M1() { }

8578
    public static unsafe void M2()
8579 8580
    {
        M1();
8581 8582
        delegate*<void> p1 = &M1;
        delegate* unmanaged<void> p2 = &M1;
8583 8584 8585 8586
    }
}
", UnmanagedCallersOnlyAttribute });

8587
            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
8588
            comp.VerifyDiagnostics(
8589
                // (10,9): error CS8901: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
8590
                //         M1();
8591 8592 8593 8594
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "M1()", isSuppressed: false).WithArguments("C.M1()").WithLocation(10, 9),
                // (11,31): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Default'.
                //         delegate*<void> p1 = &M1;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M1", isSuppressed: false).WithArguments("C.M1()", "Default").WithLocation(11, 31)
8595 8596 8597
            );
        }

F
Fredric Silberberg 已提交
8598 8599 8600
        [Fact]
        public void UnmanagedCallersOnlyCannotCallMethodDirectlyWithAlias()
        {
8601
            var comp = CreateCompilationWithFunctionPointers(new[] { @"
F
Fredric Silberberg 已提交
8602 8603 8604 8605
using System.Runtime.InteropServices;
using E = D;
public class C
{
8606
    public static unsafe void M2()
F
Fredric Silberberg 已提交
8607 8608
    {
        E.M1();
8609 8610
        delegate*<void> p1 = &E.M1;
        delegate* unmanaged<void> p2 = &E.M1;
F
Fredric Silberberg 已提交
8611 8612 8613 8614 8615 8616 8617 8618 8619 8620
    }
}
public class D
{
    [UnmanagedCallersOnly]
    public static void M1() { }

}
", UnmanagedCallersOnlyAttribute });

8621
            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
F
Fredric Silberberg 已提交
8622
            comp.VerifyDiagnostics(
8623
                // (8,9): error CS8901: 'D.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
8624
                //         E.M1();
8625 8626 8627 8628
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "E.M1()", isSuppressed: false).WithArguments("D.M1()").WithLocation(8, 9),
                // (9,31): error CS8786: Calling convention of 'D.M1()' is not compatible with 'Default'.
                //         delegate*<void> p1 = &E.M1;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "E.M1", isSuppressed: false).WithArguments("D.M1()", "Default").WithLocation(9, 31)
F
Fredric Silberberg 已提交
8629 8630 8631 8632 8633 8634
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyCannotCallMethodDirectlyWithUsingStatic()
        {
8635
            var comp = CreateCompilationWithFunctionPointers(new[] { @"
F
Fredric Silberberg 已提交
8636 8637 8638 8639
using System.Runtime.InteropServices;
using static D;
public class C
{
8640
    public static unsafe void M2()
F
Fredric Silberberg 已提交
8641 8642
    {
        M1();
8643 8644
        delegate*<void> p1 = &M1;
        delegate* unmanaged<void> p2 = &M1;
F
Fredric Silberberg 已提交
8645 8646 8647 8648 8649 8650 8651 8652 8653 8654
    }
}
public class D
{
    [UnmanagedCallersOnly]
    public static void M1() { }

}
", UnmanagedCallersOnlyAttribute });

8655
            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
F
Fredric Silberberg 已提交
8656
            comp.VerifyDiagnostics(
8657
                // (8,9): error CS8901: 'D.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
8658
                //         M1();
8659 8660 8661 8662
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "M1()", isSuppressed: false).WithArguments("D.M1()").WithLocation(8, 9),
                // (9,31): error CS8786: Calling convention of 'D.M1()' is not compatible with 'Default'.
                //         delegate*<void> p1 = &M1;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M1", isSuppressed: false).WithArguments("D.M1()", "Default").WithLocation(9, 31)
F
Fredric Silberberg 已提交
8663 8664 8665
            );
        }

8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682
        [Fact]
        public void UnmanagedCallersOnlyReferencedFromMetadata()
        {
            var comp0 = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public class C
{
    [UnmanagedCallersOnly]
    public static void M1() { }
}
", UnmanagedCallersOnlyAttribute });

            validate(comp0.ToMetadataReference());
            validate(comp0.EmitToImageReference());

            static void validate(MetadataReference reference)
            {
8683
                var comp1 = CreateCompilationWithFunctionPointers(@"
8684 8685
class D
{
8686
    public static unsafe void M2()
8687 8688
    {
        C.M1();
8689 8690
        delegate*<void> p1 = &C.M1;
        delegate* unmanaged<void> p2 = &C.M1;
8691 8692 8693 8694
    }
}
", references: new[] { reference });

8695
                comp1.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
8696
                comp1.VerifyDiagnostics(
8697
                    // (6,9): error CS8901: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
8698
                    //         C.M1();
8699 8700 8701 8702
                    Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "C.M1()").WithArguments("C.M1()").WithLocation(6, 9),
                    // (7,31): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Default'.
                    //         delegate*<void> p1 = &C.M1;
                    Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M1", isSuppressed: false).WithArguments("C.M1()", "Default").WithLocation(7, 31)
8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732
                );
            }
        }

        [Fact]
        public void UnmanagedCallersOnlyReferencedFromMetadata_BadTypeInList()
        {
            var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static 
        void M1 () cil managed 
    {
        // [System.Runtime.InteropServices.UnmanagedCallersOnly(CallConvs = new[] { typeof(object) })]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 01 00 53 1d 50 09 43 61 6c 6c 43 6f 6e 76
            73 01 00 00 00 68 53 79 73 74 65 6d 2e 4f 62 6a
            65 63 74 2c 20 53 79 73 74 65 6d 2e 50 72 69 76
            61 74 65 2e 43 6f 72 65 4c 69 62 2c 20 56 65 72
            73 69 6f 6e 3d 34 2e 30 2e 30 2e 30 2c 20 43 75
            6c 74 75 72 65 3d 6e 65 75 74 72 61 6c 2c 20 50
            75 62 6c 69 63 4b 65 79 54 6f 6b 65 6e 3d 37 63
            65 63 38 35 64 37 62 65 61 37 37 39 38 65
        )
        ret
    }
}";

F
Fredric Silberberg 已提交
8733
            var comp = CreateCompilationWithFunctionPointersAndIl(@"
8734 8735
class D
{
F
Fredric Silberberg 已提交
8736
    public unsafe static void M2()
8737 8738
    {
        C.M1();
F
Fredric Silberberg 已提交
8739
        delegate* unmanaged<void> ptr = &C.M1;
8740 8741 8742 8743
    }
}
", il);

F
Fredric Silberberg 已提交
8744
            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
8745
            comp.VerifyDiagnostics(
F
Fredric Silberberg 已提交
8746
                // (6,9): error CS8901: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
8747
                //         C.M1();
F
Fredric Silberberg 已提交
8748
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "C.M1()").WithArguments("C.M1()").WithLocation(6, 9)
8749 8750 8751 8752
            );

            var c = comp.GetTypeByMetadataName("C");
            var m1 = c.GetMethod("M1");
F
Fredric Silberberg 已提交
8753
            var unmanagedData = m1.GetUnmanagedCallersOnlyAttributeData(forceComplete: true);
8754 8755
            Assert.NotSame(unmanagedData, UnmanagedCallersOnlyAttributeData.Uninitialized);
            Assert.NotSame(unmanagedData, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound);
F
Fredric Silberberg 已提交
8756
            Assert.Empty(unmanagedData!.CallingConventionTypes);
8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289
        }

        [Fact]
        public void UnmanagedCallersOnlyDefinedOnInstanceMethod()
        {
            var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    .method public hidebysig 
        instance void M1 () cil managed 
    {
        // [System.Runtime.InteropServices.UnmanagedCallersOnly]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 00 00
        )
        ret
    }
}
";
            var comp = CreateCompilationWithIL(@"
class D
{
    public static void M2(C c)
    {
        c.M1();
    }
}
", il);

            comp.VerifyDiagnostics(
                // (6,11): error CS0570: 'C.M1()' is not supported by the language
                //         c.M1();
                Diagnostic(ErrorCode.ERR_BindToBogus, "M1").WithArguments("C.M1()").WithLocation(6, 11)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDefinedOnProperty_InSource()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
    static int Prop
    {
        [UnmanagedCallersOnly] get => throw null;
        [UnmanagedCallersOnly] set => throw null;
    }
    static void M()
    {
        Prop = 1;
        _ = Prop;
    }
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (7,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
                //         [UnmanagedCallersOnly] get => throw null;
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 10),
                // (8,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
                //         [UnmanagedCallersOnly] set => throw null;
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 10)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDefinedOnProperty_InMetadata()
        {
            var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig specialname static 
        int32 get_Prop () cil managed 
    {
        // [System.Runtime.InteropServices.UnmanagedCallersOnly]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 00 00
        )
        ldnull
        throw
    }

    .method public hidebysig specialname static 
        void set_Prop (
            int32 'value'
        ) cil managed 
    {
        // [System.Runtime.InteropServices.UnmanagedCallersOnly]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 00 00
        )
        ldnull
        throw
    }

    .property int32 Prop()
    {
        .get int32 C::get_Prop()
        .set void C::set_Prop(int32)
    }
}
";
            var comp = CreateCompilationWithIL(@"
class D
{
    public static void M2()
    {
        C.Prop = 1;
        _ = C.Prop;
    }
}
", il);

            comp.VerifyDiagnostics(
                // (6,11): error CS0570: 'C.Prop.set' is not supported by the language
                //         C.Prop = 1;
                Diagnostic(ErrorCode.ERR_BindToBogus, "Prop").WithArguments("C.Prop.set").WithLocation(6, 11),
                // (7,15): error CS0570: 'C.Prop.get' is not supported by the language
                //         _ = C.Prop;
                Diagnostic(ErrorCode.ERR_BindToBogus, "Prop").WithArguments("C.Prop.get").WithLocation(7, 15)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDefinedOnPropertyRefReadonlyGetterAsLvalue_InSource()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
    static ref int Prop { [UnmanagedCallersOnly] get => throw null; }
    static void M()
    {
        Prop = 1;
    }
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (5,28): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
                //     static int Prop { [UnmanagedCallersOnly] get {} }
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(5, 28)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDefinedOnPropertyRefReadonlyGetterAsLvalue_InMetadata()
        {
            var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig specialname static 
        int32& get_Prop () cil managed 
    {
        // [System.Runtime.InteropServices.UnmanagedCallersOnly]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 00 00
        )

        ldnull
        throw
    } // end of method C::get_Prop

    // Properties
    .property int32& Prop()
    {
        .get int32& C::get_Prop()
    }
}
";
            var comp = CreateCompilationWithIL(@"
class D
{
    public static void M2()
    {
        C.Prop = 1;
    }
}
", il);

            comp.VerifyDiagnostics(
                // (6,11): error CS0570: 'C.Prop.get' is not supported by the language
                //         C.Prop = 1;
                Diagnostic(ErrorCode.ERR_BindToBogus, "Prop").WithArguments("C.Prop.get").WithLocation(6, 11)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDefinedOnIndexer_InMetadata()
        {
            var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = (
        01 00 04 49 74 65 6d 00 00
    )
    // Methods
    .method public hidebysig specialname 
        instance void set_Item (
            int32 i,
            int32 'value'
        ) cil managed 
    {
        // [System.Runtime.InteropServices.UnmanagedCallersOnly]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 00 00
        )
        nop
        ret
    } // end of method C::set_Item

    .method public hidebysig specialname 
        instance int32 get_Item (
            int32 i
        ) cil managed 
    {
        // [System.Runtime.InteropServices.UnmanagedCallersOnly]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 00 00
        )
        ldnull
        throw
    } // end of method C::get_Item

    // Properties
    .property instance int32 Item(
        int32 i
    )
    {
        .get instance int32 C::get_Item(int32)
        .set instance void C::set_Item(int32, int32)
    }
}
";
            var comp = CreateCompilationWithIL(@"
class D
{
    public static void M2(C c)
    {
        c[1] = 1;
        _ = c[0];
    }
}
", il);

            comp.VerifyDiagnostics(
                // (6,10): error CS0570: 'C.this[int].set' is not supported by the language
                //         c[1] = 1;
                Diagnostic(ErrorCode.ERR_BindToBogus, "[1]").WithArguments("C.this[int].set").WithLocation(6, 10),
                // (7,14): error CS0570: 'C.this[int].get' is not supported by the language
                //         _ = c[0];
                Diagnostic(ErrorCode.ERR_BindToBogus, "[0]").WithArguments("C.this[int].get").WithLocation(7, 14)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDefinedOnIndexer_InSource()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
    public int this[int i]
    { 
        [UnmanagedCallersOnly] set => throw null;
        [UnmanagedCallersOnly] get => throw null;
    }
    static void M(C c)
    {
        c[1] = 1;
        _ = c[0];
    }
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (7,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
                //         [UnmanagedCallersOnly] set => throw null;
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 10),
                // (8,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
                //         [UnmanagedCallersOnly] get => throw null;
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 10)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDefinedOnIndexerRefReturnAsLvalue_InMetadata()
        {
            var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = (
        01 00 04 49 74 65 6d 00 00
    )
    // Methods
    .method public hidebysig specialname 
        instance int32& get_Item (
            int32 i
        ) cil managed 
    {
        // [System.Runtime.InteropServices.UnmanagedCallersOnly]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 00 00
        )
        ldnull
        throw
    } // end of method C::get_Item

    // Properties
    .property instance int32& Item(
        int32 i
    )
    {
        .get instance int32& C::get_Item(int32)
    }

} 
";
            var comp = CreateCompilationWithIL(@"
class D
{
    public static void M2(C c)
    {
        c[1] = 1;
        _ = c[0];
    }
}
", il);

            comp.VerifyDiagnostics(
                // (6,10): error CS0570: 'C.this[int].get' is not supported by the language
                //         c[1] = 1;
                Diagnostic(ErrorCode.ERR_BindToBogus, "[1]").WithArguments("C.this[int].get").WithLocation(6, 10),
                // (7,14): error CS0570: 'C.this[int].get' is not supported by the language
                //         _ = c[0];
                Diagnostic(ErrorCode.ERR_BindToBogus, "[0]").WithArguments("C.this[int].get").WithLocation(7, 14)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDefinedOnBinaryOperator_InSource()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly]
    public static C operator +(C c1, C c2) => null;
    static void M(C c1, C c2)
    {
        _ = c1 + c2;
    }
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (5,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
                //     [UnmanagedCallersOnly]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(5, 6)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDefinedOnBinaryOperator_InMetadata()
        {
            var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    .method public hidebysig specialname static 
        class C op_Addition (
            class C c1,
            class C c2
        ) cil managed 
    {
        // [System.Runtime.InteropServices.UnmanagedCallersOnly]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 00 00
        )
        ldnull
        ret
    }
}
";
            var comp = CreateCompilationWithIL(@"
class D
{
    public static void M2(C c1, C c2)
    {
        _ = c1 + c2;
    }
}
", il);

            comp.VerifyDiagnostics(
                // (6,13): error CS0570: 'C.operator +(C, C)' is not supported by the language
                //         _ = c1 + c2;
                Diagnostic(ErrorCode.ERR_BindToBogus, "c1 + c2").WithArguments("C.operator +(C, C)").WithLocation(6, 13)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDefinedOnUnaryOperator_InSource()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly]
    public static C operator +(C c) => null;
    static void M(C c)
    {
        _ = +c;
    }
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (5,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
                //     [UnmanagedCallersOnly]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(5, 6)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDefinedOnUnaryOperator_InMetadata()
        {
            var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    .method public hidebysig specialname static 
        class C op_UnaryPlus (
            class C c1
        ) cil managed 
    {
        // [System.Runtime.InteropServices.UnmanagedCallersOnly]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 00 00
        )
        ldnull
        ret
    }
}
";
            var comp = CreateCompilationWithIL(@"
class D
{
    public static void M2(C c1, C c2)
    {
        _ = +c1;
    }
}
", il);

            comp.VerifyDiagnostics(
                // (6,13): error CS0570: 'C.operator +(C)' is not supported by the language
                //         _ = +c1;
                Diagnostic(ErrorCode.ERR_BindToBogus, "+c1").WithArguments("C.operator +(C)").WithLocation(6, 13)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDeclaredOnGetEnumerator_InMetadata()
        {
            var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig 
        instance class [mscorlib]System.Collections.Generic.IEnumerator`1<int32> GetEnumerator () cil managed 
    {
        // [System.Runtime.InteropServices.UnmanagedCallersOnly]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 00 00
        )
        ldnull
        throw
    }
}
";

            var comp = CreateCompilationWithIL(@"
class D
{
    public static void M2(C c)
    {
        foreach (var i in c) {}
    }
}
", il);

            comp.VerifyDiagnostics(
                // (6,27): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator'
                //         foreach (var i in c) {}
                Diagnostic(ErrorCode.ERR_ForEachMissingMember, "c").WithArguments("C", "GetEnumerator").WithLocation(6, 27)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDeclaredOnGetEnumeratorExtension()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S
{
    public static void M2(S s)
    {
        foreach (var i in s) {}
    }
}
public struct SEnumerator
{
    public bool MoveNext() => throw null;
    public int Current => throw null;
}
public static class CExt
{
    [UnmanagedCallersOnly]
    public static SEnumerator GetEnumerator(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
9290
                // (7,9): error CS8901: 'CExt.GetEnumerator(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383
                //         foreach (var i in s) {}
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "foreach").WithArguments("CExt.GetEnumerator(S)").WithLocation(7, 9)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDeclaredOnMoveNext()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S
{
    public static void M2(S s)
    {
        foreach (var i in s) {}
    }
}
public struct SEnumerator
{
    [UnmanagedCallersOnly]
    public bool MoveNext() => throw null;
    public int Current => throw null;
}
public static class CExt
{
    public static SEnumerator GetEnumerator(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (12,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
                //     [UnmanagedCallersOnly]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(12, 6)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyDeclaredOnPatternDispose()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S
{
    public static void M2(S s)
    {
        foreach (var i in s) {}
    }
}
public ref struct SEnumerator
{
    public bool MoveNext() => throw null;
    public int Current => throw null;
    [UnmanagedCallersOnly]
    public void Dispose() => throw null;
}
public static class CExt
{
    public static SEnumerator GetEnumerator(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (14,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
                //     [UnmanagedCallersOnly]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(14, 6)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyCannotCaptureToDelegate()
        {
            var comp = CreateCompilation(new[] { @"
using System;
using System.Runtime.InteropServices;
public class C
{
    [UnmanagedCallersOnly]
    public static void M1() { }

    public static void M2()
    {
        Action a = M1;
        a = local;
        a = new Action(M1);
        a = new Action(local);

        [UnmanagedCallersOnly]
        static void local() {}
    }
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
9384
                // (11,20): error CS8902: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
9385
                //         Action a = M1;
F
Fredric Silberberg 已提交
9386
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "M1").WithArguments("C.M1()").WithLocation(11, 20),
9387
                // (12,13): error CS8902: 'local()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
9388
                //         a = local;
F
Fredric Silberberg 已提交
9389
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "local").WithArguments("local()").WithLocation(12, 13),
9390
                // (13,24): error CS8902: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
9391
                //         a = new Action(M1);
F
Fredric Silberberg 已提交
9392
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "M1").WithArguments("C.M1()").WithLocation(13, 24),
9393
                // (14,24): error CS8902: 'local()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
9394
                //         a = new Action(local);
F
Fredric Silberberg 已提交
9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "local").WithArguments("local()").WithLocation(14, 24)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyCannotCaptureToDelegate_OverloadStillPicked()
        {
            var comp = CreateCompilation(new[] { @"
using System;
using System.Runtime.InteropServices;
public class C 
{
    [UnmanagedCallersOnly]
    public static void M(int s) { }

    public static void M(object o) { }

    void N()
    {
        Action<int> a = M;
    }
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
9420
                // (13,25): error CS8902: 'C.M(int)' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447
                //         Action<int> a = M;
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "M").WithArguments("C.M(int)").WithLocation(13, 25)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyOnExtensionsCannotBeUsedDirectly()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;

struct S
{
    static void M(S s)
    {
        s.Extension();
        CExt.Extension(s);
    }
}
static class CExt
{
    [UnmanagedCallersOnly]
    public static void Extension(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
9448
                // (8,9): error CS8901: 'CExt.Extension(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
9449 9450
                //         s.Extension();
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "s.Extension()").WithArguments("CExt.Extension(S)").WithLocation(8, 9),
9451
                // (9,9): error CS8901: 'CExt.Extension(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481
                //         CExt.Extension(s);
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "CExt.Extension(s)").WithArguments("CExt.Extension(S)").WithLocation(9, 9)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyExtensionDeconstructCannotBeUsedDirectly()
        {
            var comp = CreateCompilation(new[] { @"
using System.Collections.Generic;
using System.Runtime.InteropServices;

struct S
{
    static void M(S s, List<S> ls)
    {
        var (i1, i2) = s;
        (i1, i2) = s;
        foreach (var (_, _) in ls) { }
        _ = s is (int _, int _);
    }
}
static class CExt
{
    [UnmanagedCallersOnly]
    public static void Deconstruct(this S s, out int i1, out int i2) => throw null;
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
9482
                // (9,24): error CS8901: 'CExt.Deconstruct(S, out int, out int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
9483 9484
                //         var (i1, i2) = s;
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "s").WithArguments("CExt.Deconstruct(S, out int, out int)").WithLocation(9, 24),
9485
                // (10,20): error CS8901: 'CExt.Deconstruct(S, out int, out int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
9486 9487
                //         (i1, i2) = s;
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "s").WithArguments("CExt.Deconstruct(S, out int, out int)").WithLocation(10, 20),
9488
                // (11,32): error CS8901: 'CExt.Deconstruct(S, out int, out int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
9489 9490
                //         foreach (var (_, _) in ls) { }
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "ls").WithArguments("CExt.Deconstruct(S, out int, out int)").WithLocation(11, 32),
9491
                // (12,18): error CS8901: 'CExt.Deconstruct(S, out int, out int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521
                //         _ = s is (int _, int _);
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "(int _, int _)").WithArguments("CExt.Deconstruct(S, out int, out int)").WithLocation(12, 18)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyExtensionAddCannotBeUsedDirectly()
        {
            var comp = CreateCompilation(new[] { @"
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;

struct S : IEnumerable
{
    static void M(S s, List<S> ls)
    {
        _ = new S() { 1, 2, 3 };
    }

    public IEnumerator GetEnumerator() => throw null;
}
static class CExt
{
    [UnmanagedCallersOnly]
    public static void Add(this S s, int i) => throw null;
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
9522
                // (10,23): error CS8901: 'CExt.Add(S, int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
9523 9524
                //         _ = new S() { 1, 2, 3 };
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "1").WithArguments("CExt.Add(S, int)").WithLocation(10, 23),
9525
                // (10,26): error CS8901: 'CExt.Add(S, int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
9526 9527
                //         _ = new S() { 1, 2, 3 };
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "2").WithArguments("CExt.Add(S, int)").WithLocation(10, 26),
9528
                // (10,29): error CS8901: 'CExt.Add(S, int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546
                //         _ = new S() { 1, 2, 3 };
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "3").WithArguments("CExt.Add(S, int)").WithLocation(10, 29)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyExtensionGetAwaiterCannotBeUsedDirectly()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;

struct S
{
    static async void M(S s)
    {
        await s;
    }
}
9547 9548 9549 9550 9551 9552
public struct Result : System.Runtime.CompilerServices.INotifyCompletion
{
    public int GetResult() => throw null;
    public void OnCompleted(System.Action continuation) => throw null;
    public bool IsCompleted => throw null;
}
F
Fredric Silberberg 已提交
9553 9554 9555
static class CExt
{
    [UnmanagedCallersOnly]
9556
    public static Result GetAwaiter(this S s) => throw null;
F
Fredric Silberberg 已提交
9557 9558 9559 9560
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
9561
                // (8,9): error CS8901: 'CExt.GetAwaiter(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
9562
                //         await s;
9563
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "await s").WithArguments("CExt.GetAwaiter(S)").WithLocation(8, 9)
F
Fredric Silberberg 已提交
9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyExtensionGetPinnableReferenceCannotBeUsedDirectly()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;

struct S
{
    static void M(S s)
    {
        unsafe
        {
            fixed (int* i = s)
            {

            }
        }
    }
}
static class CExt
{
    [UnmanagedCallersOnly]
    public static ref int GetPinnableReference(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.UnsafeReleaseDll);

            comp.VerifyDiagnostics(
9594
                // (10,29): error CS8901: 'CExt.GetPinnableReference(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
F
Fredric Silberberg 已提交
9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612
                //             fixed (int* i = s)
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "s").WithArguments("CExt.GetPinnableReference(S)").WithLocation(10, 29)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyOnMain_1()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly]
    public static void Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);

            comp.VerifyDiagnostics(
9613
                // (6,24): error CS8899: Application entry points cannot be attributed with 'UnmanagedCallersOnly'.
F
Fredric Silberberg 已提交
9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638
                //     public static void Main() {}
                Diagnostic(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, "Main").WithLocation(6, 24)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyOnMain_2()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
    public static void Main() {}
}
class D
{
    [UnmanagedCallersOnly]
    public static void Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);

            comp.VerifyDiagnostics(
                // (5,24): error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.
                //     public static void Main() {}
                Diagnostic(ErrorCode.ERR_MultipleEntryPoints, "Main").WithLocation(5, 24),
9639
                // (10,24): error CS8899: Application entry points cannot be attributed with 'UnmanagedCallersOnly'.
F
Fredric Silberberg 已提交
9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690
                //     public static void Main() {}
                Diagnostic(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, "Main").WithLocation(10, 24)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyOnMain_3()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
    public static void Main() {}
}
class D
{
    [UnmanagedCallersOnly]
    public static void Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseDll);

            comp.VerifyDiagnostics();
        }

        [Fact]
        public void UnmanagedCallersOnlyOnMain_4()
        {
            var comp = CreateCompilation(new[] { @"
using System.Threading.Tasks;
using System.Runtime.InteropServices;
class C
{
    public static async Task Main() {}
}
class D
{
    [UnmanagedCallersOnly]
    public static async Task Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);

            comp.VerifyDiagnostics(
                // (6,30): error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.
                //     public static async Task Main() {}
                Diagnostic(ErrorCode.ERR_MultipleEntryPoints, "Main").WithLocation(6, 30),
                // (6,30): 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.
                //     public static async Task Main() {}
                Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(6, 30),
                // (11,25): error CS8894: Cannot use 'Task' as a return type on a method attributed with 'UnmanagedCallersOnly'.
                //     public static async Task Main() {}
                Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "Task").WithArguments("System.Threading.Tasks.Task", "return").WithLocation(11, 25),
9691
                // (11,30): error CS8899: Application entry points cannot be attributed with 'UnmanagedCallersOnly'.
F
Fredric Silberberg 已提交
9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726
                //     public static async Task Main() {}
                Diagnostic(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, "Main").WithLocation(11, 30),
                // (11,30): 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.
                //     public static async Task Main() {}
                Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(11, 30)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyOnMain_5()
        {
            var comp = CreateCompilation(new[] { @"
using System.Threading.Tasks;
using System.Runtime.InteropServices;
class C
{
    public static void Main() {}
}
class D
{
    [UnmanagedCallersOnly]
    public static async Task Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);

            comp.VerifyDiagnostics(
                // (11,25): error CS8894: Cannot use 'Task' as a return type on a method attributed with 'UnmanagedCallersOnly'.
                //     public static async Task Main() {}
                Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "Task").WithArguments("System.Threading.Tasks.Task", "return").WithLocation(11, 25),
                // (11,30): 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.
                //     public static async Task Main() {}
                Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(11, 30)
            );
        }

9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750
        [Fact, WorkItem(47858, "https://github.com/dotnet/roslyn/issues/47858")]
        public void UnmanagedCallersOnlyOnMain_GetEntryPoint()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly]
    public static void Main()
    {
    }
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);

            var method = comp.GetEntryPoint(System.Threading.CancellationToken.None);
            Assert.Equal("void C.Main()", method.ToTestDisplayString());

            comp.VerifyDiagnostics(
                // (6,24): error CS8899: Application entry points cannot be attributed with 'UnmanagedCallersOnly'.
                //     public static void Main()
                Diagnostic(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, "Main", isSuppressed: false).WithLocation(6, 24)
            );
        }

F
Fredric Silberberg 已提交
9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770
        [Fact]
        public void UnmanagedCallersOnlyOnModuleInitializer()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }

public class C
{
    [UnmanagedCallersOnly, ModuleInitializer]
    public static void M1() {}

    [ModuleInitializer, UnmanagedCallersOnly]
    public static void M2() {}
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
9771
                // (9,28): error CS8900: Module initializer cannot be attributed with 'UnmanagedCallersOnly'.
F
Fredric Silberberg 已提交
9772 9773
                //     [UnmanagedCallersOnly, ModuleInitializer]
                Diagnostic(ErrorCode.ERR_ModuleInitializerCannotBeUnmanagedCallersOnly, "ModuleInitializer").WithLocation(9, 28),
9774
                // (12,6): error CS8900: Module initializer cannot be attributed with 'UnmanagedCallersOnly'.
F
Fredric Silberberg 已提交
9775
                //     [ModuleInitializer, UnmanagedCallersOnly]
9776
                Diagnostic(ErrorCode.ERR_ModuleInitializerCannotBeUnmanagedCallersOnly, "ModuleInitializer").WithLocation(12, 6)
9777 9778 9779
            );
        }

F
Fredric Silberberg 已提交
9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798
        [Fact]
        public void UnmanagedCallersOnlyMultipleApplications()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public class C
{
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(string) })]
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(object) })]
    public static void M1() {}
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (5,6): error CS8893: 'string' is not a valid calling convention type for 'UnmanagedCallersOnly'.
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(string) })]
                Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(string) })").WithArguments("string").WithLocation(5, 6),
                // (6,6): error CS0579: Duplicate 'UnmanagedCallersOnly' attribute
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(object) })]
9799
                Diagnostic(ErrorCode.ERR_DuplicateAttribute, "UnmanagedCallersOnly").WithArguments("UnmanagedCallersOnly").WithLocation(6, 6)
F
Fredric Silberberg 已提交
9800 9801 9802
            );
        }

9803
        [Fact]
9804
        public void UnmanagedCallersOnlyWithLoopInDefinition_1()
9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820
        {
            var comp = CreateCompilation(@"
#nullable enable
namespace System.Runtime.InteropServices
{
    [AttributeUsage(AttributeTargets.Method, Inherited = false)]
    public sealed class UnmanagedCallersOnlyAttribute : Attribute
    {
        public UnmanagedCallersOnlyAttribute()
        {
        }

        public Type[]? CallConvs;
        public string? EntryPoint;

        [UnmanagedCallersOnly]
9821
        static void M() {}
9822 9823 9824 9825
    }
}
");

9826
            comp.VerifyDiagnostics();
9827 9828 9829
        }

        [Fact]
9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847
        public void UnmanagedCallersOnlyWithLoopInDefinition_2()
        {
            var comp = CreateCompilation(@"
namespace System.Runtime.InteropServices
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
    public sealed class UnmanagedCallersOnlyAttribute : Attribute
    {
        [UnmanagedCallersOnly(CallConvs = new[] { typeof(UnmanagedCallersOnlyAttribute) })]
        public UnmanagedCallersOnlyAttribute() { }
        public Type[] CallConvs;
    }
}
");

            comp.VerifyDiagnostics(
                // (7,10): error CS8893: 'UnmanagedCallersOnlyAttribute' is not a valid calling convention type for 'UnmanagedCallersOnly'.
                //         [UnmanagedCallersOnly(CallConvs = new[] { typeof(UnmanagedCallersOnlyAttribute) })]
9848 9849 9850 9851
                Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(UnmanagedCallersOnlyAttribute) })").WithArguments("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute").WithLocation(7, 10),
                // (7,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
                //         [UnmanagedCallersOnly(CallConvs = new[] { typeof(UnmanagedCallersOnlyAttribute) })]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 10)
9852 9853 9854 9855 9856
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyWithLoopInUsage_1()
9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(C) })]
    public static void Func() {}
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
9868
                // (5,6): error CS8893: 'C' is not a valid calling convention type for 'UnmanagedCallersOnly'.
9869 9870 9871 9872 9873
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(C) })]
                Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(C) })").WithArguments("C").WithLocation(5, 6)
            );
        }

9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896
        [Fact]
        public void UnmanagedCallersOnlyWithLoopInUsage_2()
        {
            var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class A
{
    struct B { }
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(B) })]
    static void F() { }
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (6,6): error CS8893: 'A.B' is not a valid calling convention type for 'UnmanagedCallersOnly'.
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(B) })]
                Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(B) })").WithArguments("A.B").WithLocation(6, 6)
            );
        }

        [Fact(Skip = "https://github.com/dotnet/roslyn/issues/47125")]
        public void UnmanagedCallersOnlyWithLoopInUsage_3()
        {
9897 9898
            // Remove UnmanagedCallersOnlyWithLoopInUsage_3_Release when
            // this is unskipped.
9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913

            var comp = CreateCompilation(new[] { @"
#nullable enable
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly(CallConvs = F())]
    static Type[] F() { }
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
            );
        }

9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936
        [ConditionalFact(typeof(IsRelease))]
        public void UnmanagedCallersOnlyWithLoopInUsage_3_Release()
        {
            // The bug in UnmanagedCallersOnlyWithLoopInUsage_3 is only
            // triggered by the nullablewalker, which is unconditionally
            // run in debug mode. We also want to verify the use-site
            // diagnostic for unmanagedcallersonly does not cause a loop,
            // so we have a separate version that does not have nullable
            // enabled and only runs in release to verify. When
            // https://github.com/dotnet/roslyn/issues/47125 is fixed, this
            // test can be removed

            var comp = CreateCompilation(new[] { @"
using System;
using System.Runtime.InteropServices;
class C
{
    [UnmanagedCallersOnly(CallConvs = F())]
    static Type[] F() => null;
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
F
Fredric Silberberg 已提交
9937 9938 9939
                // (6,39): error CS8901: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
                //     [UnmanagedCallersOnly(CallConvs = F())]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "F()").WithArguments("C.F()").WithLocation(6, 39),
9940 9941 9942 9943 9944 9945
                // (6,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
                //     [UnmanagedCallersOnly(CallConvs = F())]
                Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F()").WithLocation(6, 39)
            );
        }

F
Fredric Silberberg 已提交
9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980
        [Fact]
        public void UnmanagedCallersOnlyWithLoopInUsage_4()
        {
            var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
unsafe class Attr : Attribute
{
    public Attr(delegate*<void> d) {}
}
unsafe class C
{
    [UnmanagedCallersOnly]
    [Attr(&M1)]
    static void M1()
    {
    }
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (12,6): error CS0181: Attribute constructor parameter 'd' has type 'delegate*<void>', which is not a valid attribute parameter type
                //     [Attr(&M1)]
                Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr", isSuppressed: false).WithArguments("d", "delegate*<void>").WithLocation(12, 6)
            );
        }

        [Fact(Skip = "https://github.com/dotnet/roslyn/issues/47125")]
        public void UnmanagedCallersOnlyWithLoopInUsage_5()
        {
            var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
F
Fredric Silberberg 已提交
9981
class Attr : Attribute
F
Fredric Silberberg 已提交
9982 9983 9984 9985 9986 9987 9988 9989 9990
{
    public Attr(int i) {}
}
unsafe class C
{
    [UnmanagedCallersOnly]
    [Attr(F())]
    static int F()
    {
F
Fredric Silberberg 已提交
9991
        return 0;
F
Fredric Silberberg 已提交
9992 9993 9994 9995 9996 9997 9998 9999 10000 10001
    }
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (12,11): error CS8901: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
                //     [Attr(F())]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "F()", isSuppressed: false).WithArguments("C.F()").WithLocation(12, 11),
                // (12,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
                //     [Attr(F())]
F
Fredric Silberberg 已提交
10002
                Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F()", isSuppressed: false).WithLocation(12, 11)
F
Fredric Silberberg 已提交
10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021
            );
        }

        [ConditionalFact(typeof(IsRelease))]
        public void UnmanagedCallersOnlyWithLoopInUsage_5_Release()
        {
            // The bug in UnmanagedCallersOnlyWithLoopInUsage_5 is only
            // triggered by the nullablewalker, which is unconditionally
            // run in debug mode. We also want to verify the use-site
            // diagnostic for unmanagedcallersonly does not cause a loop,
            // so we have a separate version that does not have nullable
            // enabled and only runs in release to verify. When
            // https://github.com/dotnet/roslyn/issues/47125 is fixed, this
            // test can be removed

            var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
F
Fredric Silberberg 已提交
10022
class Attr : Attribute
F
Fredric Silberberg 已提交
10023 10024 10025 10026 10027 10028 10029 10030 10031
{
    public Attr(int i) {}
}
unsafe class C
{
    [UnmanagedCallersOnly]
    [Attr(F())]
    static int F()
    {
F
Fredric Silberberg 已提交
10032
        return 0;
F
Fredric Silberberg 已提交
10033 10034 10035 10036 10037 10038 10039 10040 10041 10042
    }
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (12,11): error CS8901: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
                //     [Attr(F())]
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "F()", isSuppressed: false).WithArguments("C.F()").WithLocation(12, 11),
                // (12,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
                //     [Attr(F())]
F
Fredric Silberberg 已提交
10043
                Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F()", isSuppressed: false).WithLocation(12, 11)
F
Fredric Silberberg 已提交
10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyWithLoopInUsage_6()
        {
            var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public unsafe class C
{
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvFastcall) })]
    static void F(int i = G(&F)) { }
    static int G(delegate*unmanaged[Fastcall]<int, void> d) => 0;
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (7,27): error CS1736: Default parameter value for 'i' must be a compile-time constant
                //     static void F(int i = G(&F)) { }
                Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "G(&F)", isSuppressed: false).WithArguments("i").WithLocation(7, 27)
            );
        }

        [Fact]
        public void UnmanagedCallersOnlyWithLoopInUsage_7()
        {
            var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public unsafe class C
{
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvFastcall) })]
    static int F(int i = F()) => 0;
}
", UnmanagedCallersOnlyAttribute });

            comp.VerifyDiagnostics(
                // (7,26): error CS8901: 'C.F(int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
                //     static int F(int i = F()) => 0;
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "F()", isSuppressed: false).WithArguments("C.F(int)").WithLocation(7, 26),
                // (7,26): error CS1736: Default parameter value for 'i' must be a compile-time constant
                //     static int F(int i = F()) => 0;
                Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()", isSuppressed: false).WithArguments("i").WithLocation(7, 26)
            );
        }

10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151
        [Fact]
        public void UnmanagedCallersOnlyUnrecognizedConstructor()
        {
            var comp = CreateCompilation(@"
using System.Runtime.InteropServices;
public class C
{
    // Invalid typeof for the regular constructor, non-static method
    [UnmanagedCallersOnly(CallConvs: new[] { typeof(string) })]
    public void M() {}
}

#nullable enable
namespace System.Runtime.InteropServices
{
    [AttributeUsage(AttributeTargets.Method, Inherited = false)]
    public sealed class UnmanagedCallersOnlyAttribute : Attribute
    {
        public UnmanagedCallersOnlyAttribute(Type[]? CallConvs)
        {
        }

        public string? EntryPoint;
    }
}
");

            comp.VerifyDiagnostics();
        }

        [Fact]
        public void UnmanagedCallersOnlyCallConvsWithADifferentType()
        {
            var comp = CreateCompilation(@"
using System.Runtime.InteropServices;
public class C
{
    [UnmanagedCallersOnly(CallConvs = new[] { 1, 2 })]
    public static void M1() {}

    [UnmanagedCallersOnly(CallConvs = new[] { 1, 2 })]
    public void M2() {}
}

#nullable enable
namespace System.Runtime.InteropServices
{
    [AttributeUsage(AttributeTargets.Method, Inherited = false)]
    public sealed class UnmanagedCallersOnlyAttribute : Attribute
    {
        public UnmanagedCallersOnlyAttribute()
        {
        }

        public string? EntryPoint;
        public int[]? CallConvs;
    }
}
");

            comp.VerifyDiagnostics(
10152
                // (8,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static methods or static local functions.
10153
                //     [UnmanagedCallersOnly(CallConvs = new[] { 1, 2 })]
10154
                Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 6)
10155 10156 10157
            );
        }

F
Fredric Silberberg 已提交
10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403
        [Fact]
        public void UnmanagedCallersOnly_CallConvsAsProperty()
        {
            string source1 = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Runtime.InteropServices
{
    [AttributeUsage(AttributeTargets.Method, Inherited = false)]
    public sealed class UnmanagedCallersOnlyAttribute : Attribute
    {
        public UnmanagedCallersOnlyAttribute()
        {
        }

        public Type[] CallConvs { get; set; }
        public string EntryPoint;
    }
}

public class C
{
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
    public static void M() {}
}";
            string source2 = @"
class D
{
    unsafe void M2()
    {
        delegate* unmanaged<void> ptr1 = &C.M;
        delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
    }
}";
            var sameComp = CreateCompilationWithFunctionPointers(source1 + source2);
            sameComp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            sameComp.VerifyDiagnostics(
                // (28,50): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
                //         delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "CDecl").WithLocation(28, 50)
            );

            verifyUnmanagedData(sameComp);

            var refComp = CreateCompilation(source1);

            var differentComp = CreateCompilationWithFunctionPointers(source2, new[] { refComp.EmitToImageReference() });
            differentComp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            differentComp.VerifyDiagnostics(
                // (7,50): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
                //         delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "CDecl").WithLocation(7, 50)
            );

            verifyUnmanagedData(differentComp);

            static void verifyUnmanagedData(CSharpCompilation compilation)
            {
                var c = compilation.GetTypeByMetadataName("C");
                var m = c.GetMethod("M");
                Assert.Empty(m.GetUnmanagedCallersOnlyAttributeData(forceComplete: true)!.CallingConventionTypes);
            }
        }

        [Fact]
        public void UnmanagedCallersOnly_UnrecognizedSignature()
        {
            string source1 = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Runtime.InteropServices
{
    [AttributeUsage(AttributeTargets.Method, Inherited = false)]
    public sealed class UnmanagedCallersOnlyAttribute : Attribute
    {
        public UnmanagedCallersOnlyAttribute(Type[] CallConvs)
        {
        }

        public string EntryPoint;
    }
}

public class C
{
    [UnmanagedCallersOnly(CallConvs: new[] { typeof(CallConvCdecl) })]
    public static void M() {}
}";
            string source2 = @"
class D
{
    unsafe void M2()
    {
        delegate* unmanaged<void> ptr1 = &C.M;
        delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
        delegate*<void> ptr3 = &C.M;
    }
}";
            var sameComp = CreateCompilationWithFunctionPointers(source1 + source2);
            sameComp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            sameComp.VerifyDiagnostics(
                // (26,43): error CS8786: Calling convention of 'C.M()' is not compatible with 'Unmanaged'.
                //         delegate* unmanaged<void> ptr1 = &C.M;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "Unmanaged").WithLocation(26, 43),
                // (27,50): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
                //         delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "CDecl").WithLocation(27, 50)
            );

            verifyUnmanagedData(sameComp);

            var refComp = CreateCompilation(source1);

            var differentComp = CreateCompilationWithFunctionPointers(source2, new[] { refComp.EmitToImageReference() });
            differentComp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            differentComp.VerifyDiagnostics(
                // (6,43): error CS8786: Calling convention of 'C.M()' is not compatible with 'Unmanaged'.
                //         delegate* unmanaged<void> ptr1 = &C.M;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "Unmanaged").WithLocation(6, 43),
                // (7,50): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
                //         delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "CDecl").WithLocation(7, 50)
            );

            verifyUnmanagedData(differentComp);

            static void verifyUnmanagedData(CSharpCompilation compilation)
            {
                var c = compilation.GetTypeByMetadataName("C");
                var m = c.GetMethod("M");
                Assert.Null(m.GetUnmanagedCallersOnlyAttributeData(forceComplete: true));
            }
        }

        [Fact]
        public void UnmanagedCallersOnly_PropertyAndFieldNamedCallConvs()
        {
            var il = @"
.class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute
    extends [mscorlib]System.Attribute
{
    .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = (
        01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72
        69 74 65 64 00
    )
    // Fields
    .field public class [mscorlib]System.Type[] CallConvs
    .field public string EntryPoint

    // Methods
    .method public hidebysig specialname rtspecialname instance void .ctor () cil managed 
    {
        ldarg.0
        call instance void [mscorlib]System.Attribute::.ctor()
        ret
    } // end of method UnmanagedCallersOnlyAttribute::.ctor

    .method public hidebysig specialname instance class [mscorlib]System.Type[] get_CallConvs () cil managed
    {
        ldnull
        ret
    } // end of method UnmanagedCallersOnlyAttribute::get_CallConvs

    .method public hidebysig specialname instance void set_CallConvs (
            class [mscorlib]System.Type[] 'value'
        ) cil managed 
    {
        ret
    } // end of method UnmanagedCallersOnlyAttribute::set_CallConvs

    // Properties
    .property instance class [mscorlib]System.Type[] CallConvs()
    {
        .get instance class [mscorlib]System.Type[] System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::get_CallConvs()
        .set instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::set_CallConvs(class [mscorlib]System.Type[])
    }

}
.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static void M () cil managed
    {
        // As separate field/property assignments. Property is first.
        // [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) }, CallConvs = new[] { typeof(CallConvCdecl) })]
        .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
            01 00 02 00 54 1d 50 09 43 61 6c 6c 43 6f 6e 76
            73 01 00 00 00 7c 53 79 73 74 65 6d 2e 52 75 6e
            74 69 6d 65 2e 43 6f 6d 70 69 6c 65 72 53 65 72
            76 69 63 65 73 2e 43 61 6c 6c 43 6f 6e 76 53 74
            64 63 61 6c 6c 2c 20 6d 73 63 6f 72 6c 69 62 2c
            20 56 65 72 73 69 6f 6e 3d 34 2e 30 2e 30 2e 30
            2c 20 43 75 6c 74 75 72 65 3d 6e 65 75 74 72 61
            6c 2c 20 50 75 62 6c 69 63 4b 65 79 54 6f 6b 65
            6e 3d 62 37 37 61 35 63 35 36 31 39 33 34 65 30
            38 39 53 1d 50 09 43 61 6c 6c 43 6f 6e 76 73 01
            00 00 00 7a 53 79 73 74 65 6d 2e 52 75 6e 74 69
            6d 65 2e 43 6f 6d 70 69 6c 65 72 53 65 72 76 69
            63 65 73 2e 43 61 6c 6c 43 6f 6e 76 43 64 65 63
            6c 2c 20 6d 73 63 6f 72 6c 69 62 2c 20 56 65 72
            73 69 6f 6e 3d 34 2e 30 2e 30 2e 30 2c 20 43 75
            6c 74 75 72 65 3d 6e 65 75 74 72 61 6c 2c 20 50
            75 62 6c 69 63 4b 65 79 54 6f 6b 65 6e 3d 62 37
            37 61 35 63 35 36 31 39 33 34 65 30 38 39
        )

        ret
    } // end of method C::M
}
";

            var comp = CreateCompilationWithFunctionPointersAndIl(@"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
unsafe class D
{
    static void M1()
    {
        delegate* unmanaged[Cdecl]<void> ptr1 = &C.M;
        delegate* unmanaged[Stdcall]<void> ptr2 = &C.M; // Error
        M2();
    }

    [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
    static void M2() {}
}
", il);

            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            comp.VerifyDiagnostics(
                // (9,52): error CS8786: Calling convention of 'C.M()' is not compatible with 'Standard'.
                //         delegate* unmanaged[Stdcall]<void> ptr2 = &C.M; // Error
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "Standard").WithLocation(9, 52),
                // (13,27): error CS0229: Ambiguity between 'UnmanagedCallersOnlyAttribute.CallConvs' and 'UnmanagedCallersOnlyAttribute.CallConvs'
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
                Diagnostic(ErrorCode.ERR_AmbigMember, "CallConvs").WithArguments("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute.CallConvs", "System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute.CallConvs").WithLocation(13, 27)
            );

            var c = comp.GetTypeByMetadataName("C");
            var m = c.GetMethod("M");
            var callConvCdecl = comp.GetTypeByMetadataName("System.Runtime.CompilerServices.CallConvCdecl");

            Assert.True(callConvCdecl!.Equals((NamedTypeSymbol)m.GetUnmanagedCallersOnlyAttributeData(forceComplete: true)!.CallingConventionTypes.Single(), TypeCompareKind.ConsiderEverything));
        }

10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434
        [Fact]
        public void UnmanagedCallersOnly_BadExpressionInArguments()
        {

            var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.InteropServices;
class A
{
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
    static unsafe void F()
    {
        delegate*<void> ptr1 = &F;
        delegate* unmanaged<void> ptr2 = &F;
    }
}
", UnmanagedCallersOnlyAttribute });

            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            comp.VerifyDiagnostics(
                // (5,54): error CS0246: The type or namespace name 'Bad' could not be found (are you missing a using directive or an assembly reference?)
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
                Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Bad", isSuppressed: false).WithArguments("Bad").WithLocation(5, 54),
                // (5,57): error CS1026: ) expected
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
                Diagnostic(ErrorCode.ERR_CloseParenExpected, ",", isSuppressed: false).WithLocation(5, 57),
                // (5,59): error CS0103: The name 'Expression' does not exist in the current context
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
                Diagnostic(ErrorCode.ERR_NameNotInContext, "Expression", isSuppressed: false).WithArguments("Expression").WithLocation(5, 59),
                // (5,69): error CS1003: Syntax error, ',' expected
                //     [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
                Diagnostic(ErrorCode.ERR_SyntaxError, ")", isSuppressed: false).WithArguments(",", ")").WithLocation(5, 69),
F
Fredric Silberberg 已提交
10435 10436 10437
                // (9,43): error CS8786: Calling convention of 'A.F()' is not compatible with 'Unmanaged'.
                //         delegate* unmanaged<void> ptr2 = &F;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "F", isSuppressed: false).WithArguments("A.F()", "Unmanaged").WithLocation(9, 43)
10438 10439 10440 10441 10442
            );
        }

        [Theory]
        [InlineData("", 1)]
F
Fredric Silberberg 已提交
10443
        [InlineData("CallConvs = null", 1)]
10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709
        [InlineData("CallConvs = new System.Type[0]", 1)]
        [InlineData("CallConvs = new[] { typeof(CallConvCdecl) }", 2)]
        [InlineData("CallConvs = new[] { typeof(CallConvCdecl), typeof(CallConvCdecl) }", 2)]
        [InlineData("CallConvs = new[] { typeof(CallConvThiscall) }", 3)]
        [InlineData("CallConvs = new[] { typeof(CallConvStdcall) }", 4)]
        [InlineData("CallConvs = new[] { typeof(CallConvFastcall) }", 5)]
        [InlineData("CallConvs = new[] { typeof(CallConvCdecl), typeof(CallConvThiscall) }", 6)]
        [InlineData("CallConvs = new[] { typeof(CallConvThiscall), typeof(CallConvCdecl) }", 6)]
        [InlineData("CallConvs = new[] { typeof(CallConvThiscall), typeof(CallConvCdecl), typeof(CallConvCdecl) }", 6)]
        [InlineData("CallConvs = new[] { typeof(CallConvFastcall), typeof(CallConvCdecl) }", -1)]
        [InlineData("CallConvs = new[] { typeof(CallConvThiscall), typeof(CallConvCdecl), typeof(CallConvStdcall) }", -1)]
        public void UnmanagedCallersOnlyAttribute_ConversionsToPointerType(string unmanagedCallersOnlyConventions, int diagnosticToSkip)
        {
            var comp = CreateCompilationWithFunctionPointers(new[] { $@"
#pragma warning disable CS8019 // Unused using
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public unsafe class C
{{
    [UnmanagedCallersOnly({unmanagedCallersOnlyConventions})]
    public static void M()
    {{
        delegate*<void> ptrManaged = &M;
        delegate* unmanaged<void> ptrUnmanaged = &M;
        delegate* unmanaged[Cdecl]<void> ptrCdecl = &M;
        delegate* unmanaged[Thiscall]<void> ptrThiscall = &M;
        delegate* unmanaged[Stdcall]<void> ptrStdcall = &M;
        delegate* unmanaged[Fastcall]<void> ptrFastcall = &M;
        delegate* unmanaged[Cdecl, Thiscall]<void> ptrCdeclThiscall = &M;
    }}
}}
", UnmanagedCallersOnlyAttribute });

            List<DiagnosticDescription> diagnostics = new()
            {
                // (10,39): error CS8786: Calling convention of 'C.M()' is not compatible with 'Default'.
                //         delegate*<void> ptrManaged = &M;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "Default").WithLocation(10, 39)
            };

            if (diagnosticToSkip != 1)
            {
                diagnostics.Add(
                    // (11,25): error CS8786: Calling convention of 'C.M()' is not compatible with 'Unmanaged'.
                    //         ptrUnmanaged = &M;
                    Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "Unmanaged").WithLocation(11, 51)
                    );
            }

            if (diagnosticToSkip != 2)
            {
                diagnostics.Add(
                    // (12,54): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
                    //         delegate* unmanaged[Cdecl]<void> ptrCdecl = &M;
                    Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "CDecl").WithLocation(12, 54)
                    );
            }

            if (diagnosticToSkip != 3)
            {
                diagnostics.Add(
                    // (13,60): error CS8786: Calling convention of 'C.M()' is not compatible with 'ThisCall'.
                    //         delegate* unmanaged[Thiscall]<void> ptrThiscall = &M;
                    Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "ThisCall").WithLocation(13, 60)
                    );
            }

            if (diagnosticToSkip != 4)
            {
                diagnostics.Add(
                    // (14,58): error CS8786: Calling convention of 'C.M()' is not compatible with 'Standard'.
                    //         delegate* unmanaged[Stdcall]<void> ptrStdcall = &M;
                    Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "Standard").WithLocation(14, 58)
                    );
            }

            if (diagnosticToSkip != 5)
            {
                diagnostics.Add(
                    // (15,60): error CS8786: Calling convention of 'C.M()' is not compatible with 'FastCall'.
                    //         delegate* unmanaged[Fastcall]<void> ptrFastcall = &M;
                    Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "FastCall").WithLocation(15, 60)
                    );
            }

            if (diagnosticToSkip != 6)
            {
                diagnostics.Add(
                    // (16,72): error CS8786: Calling convention of 'C.M()' is not compatible with 'Unmanaged'.
                    //         delegate* unmanaged[Cdecl, Thiscall]<void> ptrCdeclThiscall = &M;
                    Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "Unmanaged").WithLocation(16, 72)
                    );
            }


            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            comp.VerifyDiagnostics(diagnostics.ToArray());
        }

        [Fact]
        public void UnmanagedCallersOnlyAttribute_AddressOfUsedInAttributeArgument()
        {
            var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
unsafe class Attr : Attribute
{
    public Attr() {}

    public delegate* unmanaged<void> PropUnmanaged { get; set; }
    public delegate*<void> PropManaged { get; set; }
    public delegate* unmanaged[Cdecl]<void> PropCdecl { get; set; }
}
unsafe class C
{
    [UnmanagedCallersOnly]
    static void M1()
    {
    }

    [Attr(PropUnmanaged = &M1)]
    [Attr(PropManaged = &M1)]
    [Attr(PropCdecl = &M1)]
    static unsafe void M2()
    {

    }
}
", UnmanagedCallersOnlyAttribute });

            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            comp.VerifyDiagnostics(
                // (20,11): error CS0655: 'PropUnmanaged' is not a valid named attribute argument because it is not a valid attribute parameter type
                //     [Attr(PropUnmanaged = &M1)]
                Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "PropUnmanaged", isSuppressed: false).WithArguments("PropUnmanaged").WithLocation(20, 11),
                // (21,11): error CS0655: 'PropManaged' is not a valid named attribute argument because it is not a valid attribute parameter type
                //     [Attr(PropManaged = &M1)]
                Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "PropManaged", isSuppressed: false).WithArguments("PropManaged").WithLocation(21, 11),
                // (22,11): error CS0655: 'PropCdecl' is not a valid named attribute argument because it is not a valid attribute parameter type
                //     [Attr(PropCdecl = &M1)]
                Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "PropCdecl", isSuppressed: false).WithArguments("PropCdecl").WithLocation(22, 11)
            );
        }

        [ConditionalFact(typeof(CoreClrOnly))]
        public void UnmanagedCallersOnly_Il()
        {
            var verifier = CompileAndVerifyFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;

unsafe
{
    delegate* unmanaged<void> ptr = &M;
    ptr();
}

[UnmanagedCallersOnly]
static void M()
{
    Console.WriteLine(1);
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.UnsafeReleaseExe, overrideUnmanagedSupport: true);

            // TODO: Remove the manual unmanagedcallersonlyattribute definition and override and verify the
            // output of running this code when we move to p8

            verifier.VerifyIL("<top-level-statements-entry-point>", expectedIL: @"
{
  // Code size       12 (0xc)
  .maxstack  1
  IL_0000:  ldftn      ""void <Program>$.<<Main>$>g__M|0_0()""
  IL_0006:  calli      ""delegate* unmanaged<void>""
  IL_000b:  ret
}
");
        }

        [Fact]
        public void UnmanagedCallersOnly_AddressOfAsInvocationArgument()
        {
            var verifier = CompileAndVerifyFunctionPointers(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public unsafe class C
{
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
    public static void M1(int i) { }

    public static void M2(delegate* unmanaged[Cdecl]<int, void> param)
    {
        M2(&M1);
    }
}
", UnmanagedCallersOnlyAttribute });

            verifier.VerifyIL(@"C.M2", @"
{
  // Code size       12 (0xc)
  .maxstack  1
  IL_0000:  ldftn      ""void C.M1(int)""
  IL_0006:  call       ""void C.M2(delegate* unmanaged[Cdecl]<int, void>)""
  IL_000b:  ret
}
");
        }

        [Fact]
        public void UnmanagedCallersOnly_LambdaInference()
        {
            var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
public unsafe class C
{
    [UnmanagedCallersOnly]
    public static void M1(int i) { }

    public static void M2()
    {
        Func<delegate*<int, void>> a1 = () => &M1;
        Func<delegate* unmanaged<int, void>> a2 = () => &M1;
    }
}
", UnmanagedCallersOnlyAttribute });

            comp.Assembly.SetOverrideRuntimeSupportsUnmanagedSignatureCallingConvention();
            comp.VerifyDiagnostics(
                // (11,14): error CS0306: The type 'delegate*<int, void>' may not be used as a type argument
                //         Func<delegate*<int, void>> a1 = () => &M1;
                Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate*<int, void>", isSuppressed: false).WithArguments("delegate*<int, void>").WithLocation(11, 14),
                // (11,47): 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<delegate*<int, void>> a1 = () => &M1;
                Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "&M1", isSuppressed: false).WithArguments("lambda expression").WithLocation(11, 47),
                // (11,48): error CS8786: Calling convention of 'C.M1(int)' is not compatible with 'Default'.
                //         Func<delegate*<int, void>> a1 = () => &M1;
                Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M1", isSuppressed: false).WithArguments("C.M1(int)", "Default").WithLocation(11, 48),
                // (12,14): error CS0306: The type 'delegate* unmanaged<int, void>' may not be used as a type argument
                //         Func<delegate* unmanaged<int, void>> a2 = () => &M1;
                Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate* unmanaged<int, void>", isSuppressed: false).WithArguments("delegate* unmanaged<int, void>").WithLocation(12, 14)
            );

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

            var lambdas = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToArray();

            Assert.Equal(2, lambdas.Length);

            var typeInfo = model.GetTypeInfo(lambdas[0]);
            var conversion = model.GetConversion(lambdas[0]);
            AssertEx.Equal("System.Func<delegate*<System.Int32, System.Void>>",
                           typeInfo.Type.ToTestDisplayString(includeNonNullable: false));
            AssertEx.Equal("System.Func<delegate*<System.Int32, System.Void>>",
                           typeInfo.ConvertedType.ToTestDisplayString(includeNonNullable: false));
            Assert.Equal(Conversion.NoConversion, conversion);

            typeInfo = model.GetTypeInfo(lambdas[1]);
            conversion = model.GetConversion(lambdas[1]);
            Assert.Null(typeInfo.Type);
            AssertEx.Equal("System.Func<delegate* unmanaged<System.Int32, System.Void>>",
                           typeInfo.ConvertedType.ToTestDisplayString(includeNonNullable: false));
            Assert.Equal(ConversionKind.AnonymousFunction, conversion.Kind);
        }

F
Fredric Silberberg 已提交
10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872
        private static readonly Guid s_guid = new Guid("97F4DBD4-F6D1-4FAD-91B3-1001F92068E5");
        private static readonly BlobContentId s_contentId = new BlobContentId(s_guid, 0x04030201);

        private static void DefineInvalidSignatureAttributeIL(MetadataBuilder metadata, BlobBuilder ilBuilder, SignatureHeader headerToUseForM)
        {
            metadata.AddModule(
                0,
                metadata.GetOrAddString("ConsoleApplication.exe"),
                metadata.GetOrAddGuid(s_guid),
                default(GuidHandle),
                default(GuidHandle));

            metadata.AddAssembly(
                metadata.GetOrAddString("ConsoleApplication"),
                version: new Version(1, 0, 0, 0),
                culture: default(StringHandle),
                publicKey: metadata.GetOrAddBlob(new byte[0]),
                flags: default(AssemblyFlags),
                hashAlgorithm: AssemblyHashAlgorithm.Sha1);

            var mscorlibAssemblyRef = metadata.AddAssemblyReference(
                name: metadata.GetOrAddString("mscorlib"),
                version: new Version(4, 0, 0, 0),
                culture: default(StringHandle),
                publicKeyOrToken: metadata.GetOrAddBlob(ImmutableArray.Create<byte>(0xB7, 0x7A, 0x5C, 0x56, 0x19, 0x34, 0xE0, 0x89)),
                flags: default(AssemblyFlags),
                hashValue: default(BlobHandle));

            var systemObjectTypeRef = metadata.AddTypeReference(
                mscorlibAssemblyRef,
                metadata.GetOrAddString("System"),
                metadata.GetOrAddString("Object"));

            var systemConsoleTypeRefHandle = metadata.AddTypeReference(
                mscorlibAssemblyRef,
                metadata.GetOrAddString("System"),
                metadata.GetOrAddString("Console"));

            var consoleWriteLineSignature = new BlobBuilder();

            new BlobEncoder(consoleWriteLineSignature).
                MethodSignature().
                Parameters(1,
                    returnType => returnType.Void(),
                    parameters => parameters.AddParameter().Type().String());

            var consoleWriteLineMemberRef = metadata.AddMemberReference(
                systemConsoleTypeRefHandle,
                metadata.GetOrAddString("WriteLine"),
                metadata.GetOrAddBlob(consoleWriteLineSignature));

            var parameterlessCtorSignature = new BlobBuilder();

            new BlobEncoder(parameterlessCtorSignature).
                MethodSignature(isInstanceMethod: true).
                Parameters(0, returnType => returnType.Void(), parameters => { });

            var parameterlessCtorBlobIndex = metadata.GetOrAddBlob(parameterlessCtorSignature);

            var objectCtorMemberRef = metadata.AddMemberReference(
                systemObjectTypeRef,
                metadata.GetOrAddString(".ctor"),
                parameterlessCtorBlobIndex);

            // Signature for M() with an _invalid_ SignatureAttribute
            var mSignature = new BlobBuilder();
            var mBlobBuilder = new BlobEncoder(mSignature);
            mBlobBuilder.Builder.WriteByte(headerToUseForM.RawValue);
            var mParameterEncoder = new MethodSignatureEncoder(mBlobBuilder.Builder, hasVarArgs: false);
            mParameterEncoder.Parameters(parameterCount: 0, returnType => returnType.Void(), parameters => { });

            var methodBodyStream = new MethodBodyStreamEncoder(ilBuilder);

            var codeBuilder = new BlobBuilder();
            InstructionEncoder il;

            //
            // Program::.ctor
            //
            il = new InstructionEncoder(codeBuilder);

            // ldarg.0
            il.LoadArgument(0);

            // call instance void [mscorlib]System.Object::.ctor()
            il.Call(objectCtorMemberRef);

            // ret
            il.OpCode(ILOpCode.Ret);

            int ctorBodyOffset = methodBodyStream.AddMethodBody(il);
            codeBuilder.Clear();

            //
            // Program::M
            //
            il = new InstructionEncoder(codeBuilder);

            // ldstr "M"
            il.LoadString(metadata.GetOrAddUserString("M"));

            // call void [mscorlib]System.Console::WriteLine(string)
            il.Call(consoleWriteLineMemberRef);

            // ret
            il.OpCode(ILOpCode.Ret);

            int mBodyOffset = methodBodyStream.AddMethodBody(il);
            codeBuilder.Clear();

            var mMethodDef = metadata.AddMethodDefinition(
                MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig,
                MethodImplAttributes.IL | MethodImplAttributes.Managed,
                metadata.GetOrAddString("M"),
                metadata.GetOrAddBlob(mSignature),
                mBodyOffset,
                parameterList: default(ParameterHandle));

            var ctorDef = metadata.AddMethodDefinition(
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
                MethodImplAttributes.IL | MethodImplAttributes.Managed,
                metadata.GetOrAddString(".ctor"),
                parameterlessCtorBlobIndex,
                ctorBodyOffset,
                parameterList: default(ParameterHandle));

            metadata.AddTypeDefinition(
                default(TypeAttributes),
                default(StringHandle),
                metadata.GetOrAddString("<Module>"),
                baseType: default(EntityHandle),
                fieldList: MetadataTokens.FieldDefinitionHandle(1),
                methodList: mMethodDef);

            metadata.AddTypeDefinition(
                TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.BeforeFieldInit,
                metadata.GetOrAddString("ConsoleApplication"),
                metadata.GetOrAddString("Program"),
                systemObjectTypeRef,
                fieldList: MetadataTokens.FieldDefinitionHandle(1),
                methodList: mMethodDef);
        }

        private static void WritePEImage(
            Stream peStream,
            MetadataBuilder metadataBuilder,
            BlobBuilder ilBuilder)
        {
            var peHeaderBuilder = new PEHeaderBuilder(imageCharacteristics: Characteristics.Dll);

            var peBuilder = new ManagedPEBuilder(
                peHeaderBuilder,
                new MetadataRootBuilder(metadataBuilder),
                ilBuilder,
                flags: CorFlags.ILOnly,
                deterministicIdProvider: content => s_contentId);

            var peBlob = new BlobBuilder();

            var contentId = peBuilder.Serialize(peBlob);

            peBlob.WriteContentTo(peStream);
        }
F
Fredric Silberberg 已提交
10873 10874 10875 10876 10877

        private static ModuleSymbol GetSourceModule(CompilationVerifier verifier)
        {
            return ((CSharpCompilation)verifier.Compilation).SourceModule;
        }
10878 10879
    }
}