Welcome to mirror list, hosted at ThFree Co, Russian Federation.

delegate.cs « mcs « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8ecc5fb27404cb50cd5c33ed77436652ed7ebbd5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
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
676
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//
// delegate.cs: Delegate Handler
//
// Authors:
//     Ravi Pratap (ravi@ximian.com)
//     Miguel de Icaza (miguel@ximian.com)
//
// Licensed under the terms of the GNU GPL
//
// (C) 2001 Ximian, Inc (http://www.ximian.com)
//
//

using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;

namespace Mono.CSharp {

	/// <summary>
	///   Holds Delegates
	/// </summary>
	public class Delegate : DeclSpace {
 		public Expression ReturnType;
		public Parameters      Parameters;

		public ConstructorBuilder ConstructorBuilder;
		public MethodBuilder      InvokeBuilder;
		public MethodBuilder      BeginInvokeBuilder;
		public MethodBuilder      EndInvokeBuilder;
		
		Type [] param_types;
		Type ret_type;

		static string[] attribute_targets = new string [] { "type", "return" };
		
		Expression instance_expr;
		MethodBase delegate_method;
		ReturnParameter return_attributes;
	
		const int AllowedModifiers =
			Modifiers.NEW |
			Modifiers.PUBLIC |
			Modifiers.PROTECTED |
			Modifiers.INTERNAL |
		        Modifiers.UNSAFE |
			Modifiers.PRIVATE;

 		public Delegate (NamespaceEntry ns, TypeContainer parent, Expression type,
				 int mod_flags, string name, Parameters param_list,
				 Attributes attrs, Location l)
			: base (ns, parent, name, attrs, l)

		{
			this.ReturnType = type;
			ModFlags        = Modifiers.Check (AllowedModifiers, mod_flags,
							   IsTopLevel ? Modifiers.INTERNAL :
							   Modifiers.PRIVATE, l);
			Parameters      = param_list;
		}

		public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
		{
			if (a.Target == "return") {
				if (return_attributes == null)
					return_attributes = new ReturnParameter (InvokeBuilder, Location);

				return_attributes.ApplyAttributeBuilder (a, cb);
				return;
			}

			base.ApplyAttributeBuilder (a, cb);
		}

		public override TypeBuilder DefineType ()
		{
			if (TypeBuilder != null)
				return TypeBuilder;

			TypeAttributes attr = Modifiers.TypeAttr (ModFlags, IsTopLevel) |
				TypeAttributes.Class | TypeAttributes.Sealed;

			if (IsTopLevel) {
				if (TypeManager.NamespaceClash (Name, Location))
					return null;
				
				ModuleBuilder builder = CodeGen.Module.Builder;

				TypeBuilder = builder.DefineType (
					Name, attr, TypeManager.multicast_delegate_type);
			} else {
				TypeBuilder builder = Parent.TypeBuilder;

				string name = Name.Substring (1 + Name.LastIndexOf ('.'));
				TypeBuilder = builder.DefineNestedType (
					name, attr, TypeManager.multicast_delegate_type);
			}

			TypeManager.AddDelegateType (Name, TypeBuilder, this);

			return TypeBuilder;
		}

 		public override bool DefineMembers (TypeContainer container)
		{
			return true;
		}

 		public override bool Define (TypeContainer container)
		{
			MethodAttributes mattr;
			int i;
			EmitContext ec = new EmitContext (this, this, Location, null,
							  null, ModFlags, false);

			// FIXME: POSSIBLY make this static, as it is always constant
			//
			Type [] const_arg_types = new Type [2];
			const_arg_types [0] = TypeManager.object_type;
			const_arg_types [1] = TypeManager.intptr_type;

			mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
				MethodAttributes.HideBySig | MethodAttributes.Public;

			ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
									    CallingConventions.Standard,
									    const_arg_types);

			ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
			ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
			//
			// HACK because System.Reflection.Emit is lame
			//
			//
			// FIXME: POSSIBLY make these static, as they are always the same
			Parameter [] fixed_pars = new Parameter [2];
			fixed_pars [0] = new Parameter (null, null, Parameter.Modifier.NONE, null);
			fixed_pars [1] = new Parameter (null, null, Parameter.Modifier.NONE, null);
			Parameters const_parameters = new Parameters (fixed_pars, null, Location);
			
			TypeManager.RegisterMethod (
				ConstructorBuilder,
				new InternalParameters (const_arg_types, const_parameters),
				const_arg_types);
				
			
			ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);

			//
			// Here the various methods like Invoke, BeginInvoke etc are defined
			//
			// First, call the `out of band' special method for
			// defining recursively any types we need:
			
			if (!Parameters.ComputeAndDefineParameterTypes (this))
				return false;
			
 			param_types = Parameters.GetParameterInfo (this);
			if (param_types == null)
				return false;

			//
			// Invoke method
			//

			// Check accessibility
			foreach (Type partype in param_types){
				if (!container.AsAccessible (partype, ModFlags)) {
					Report.Error (59, Location,
						      "Inconsistent accessibility: parameter type `" +
						      TypeManager.CSharpName (partype) + "` is less " +
						      "accessible than delegate `" + Name + "'");
					return false;
				}
				if (partype.IsPointer && !UnsafeOK (container))
					return false;
			}
			
 			ReturnType = ResolveTypeExpr (ReturnType, false, Location);
                        if (ReturnType == null)
                            return false;
                        
   			ret_type = ReturnType.Type;
			if (ret_type == null)
				return false;

			if (!container.AsAccessible (ret_type, ModFlags)) {
				Report.Error (58, Location,
					      "Inconsistent accessibility: return type `" +
					      TypeManager.CSharpName (ret_type) + "` is less " +
					      "accessible than delegate `" + Name + "'");
				return false;
			}

			if (ret_type.IsPointer && !UnsafeOK (container))
				return false;

			//
			// We don't have to check any others because they are all
			// guaranteed to be accessible - they are standard types.
			//
			
  			CallingConventions cc = Parameters.GetCallingConvention ();

 			mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;

 			InvokeBuilder = TypeBuilder.DefineMethod ("Invoke", 
 								  mattr,		     
 								  cc,
 								  ret_type,		     
 								  param_types);

			//
			// Define parameters, and count out/ref parameters
			//
			int out_params = 0;
			i = 0;
			if (Parameters.FixedParameters != null){
				int top = Parameters.FixedParameters.Length;
				Parameter p;
				
				for (; i < top; i++) {
					p = Parameters.FixedParameters [i];
					p.DefineParameter (ec, InvokeBuilder, null, i + 1, Location);

					if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
						out_params++;
				}
			}
			if (Parameters.ArrayParameter != null){
				Parameter p = Parameters.ArrayParameter;
				p.DefineParameter (ec, InvokeBuilder, null, i + 1, Location);
			}
			
			InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);

			TypeManager.RegisterMethod (InvokeBuilder,
						    new InternalParameters (container, Parameters),
						    param_types);

			//
			// BeginInvoke
			//
			int params_num = param_types.Length;
			Type [] async_param_types = new Type [params_num + 2];

			param_types.CopyTo (async_param_types, 0);

			async_param_types [params_num] = TypeManager.asynccallback_type;
			async_param_types [params_num + 1] = TypeManager.object_type;

			mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
				MethodAttributes.Virtual | MethodAttributes.NewSlot;
			
			BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
								       mattr,
								       cc,
								       TypeManager.iasyncresult_type,
								       async_param_types);

			i = 0;
			if (Parameters.FixedParameters != null){
				int top = Parameters.FixedParameters.Length;
				Parameter p;
				
				for (i = 0 ; i < top; i++) {
					p = Parameters.FixedParameters [i];

					p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1, Location);
				}
			}
			if (Parameters.ArrayParameter != null){
				Parameter p = Parameters.ArrayParameter;
				p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1, Location);

				i++;
			}

			BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
			BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
			
			BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);

			Parameter [] async_params = new Parameter [params_num + 2];
			int n = 0;
			if (Parameters.FixedParameters != null){
				Parameters.FixedParameters.CopyTo (async_params, 0);
				n = Parameters.FixedParameters.Length;
			}
			if (Parameters.ArrayParameter != null)
				async_params [n] = Parameters.ArrayParameter;
			
			async_params [params_num] = new Parameter (
				TypeManager.system_asynccallback_expr, "callback",
								   Parameter.Modifier.NONE, null);
			async_params [params_num + 1] = new Parameter (
				TypeManager.system_object_expr, "object",
								   Parameter.Modifier.NONE, null);

			Parameters async_parameters = new Parameters (async_params, null, Location);
			async_parameters.ComputeAndDefineParameterTypes (this);
			
			async_parameters.ComputeAndDefineParameterTypes (this);
			TypeManager.RegisterMethod (BeginInvokeBuilder,
						    new InternalParameters (container, async_parameters),
						    async_param_types);

			//
			// EndInvoke is a bit more interesting, all the parameters labeled as
			// out or ref have to be duplicated here.
			//
			
			Type [] end_param_types = new Type [out_params + 1];
			Parameter [] end_params = new Parameter [out_params + 1];
			int param = 0; 
			if (out_params > 0){
				int top = Parameters.FixedParameters.Length;
				for (i = 0; i < top; i++){
					Parameter p = Parameters.FixedParameters [i];
					if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
						continue;

					end_param_types [param] = param_types [i];
					end_params [param] = p;
					param++;
				}
			}
			end_param_types [out_params] = TypeManager.iasyncresult_type;
			end_params [out_params] = new Parameter (TypeManager.system_iasyncresult_expr, "result", Parameter.Modifier.NONE, null);

			//
			// Create method, define parameters, register parameters with type system
			//
			EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_param_types);
			EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);

			//
			// EndInvoke: Label the parameters
			//
			EndInvokeBuilder.DefineParameter (out_params + 1, ParameterAttributes.None, "result");
			for (i = 0; i < end_params.Length-1; i++){
				EndInvokeBuilder.DefineParameter (i + 1, end_params [i].Attributes, end_params [i].Name);
			}

			Parameters end_parameters = new Parameters (end_params, null, Location);
			end_parameters.ComputeAndDefineParameterTypes (this);

			TypeManager.RegisterMethod (
				EndInvokeBuilder,
				new InternalParameters (container, end_parameters),
				end_param_types);

			return true;
		}

		public override void Emit (TypeContainer tc)
		{
			if (OptAttributes != null) {
				EmitContext ec = new EmitContext (tc, this, Location, null, null, ModFlags, false);
				Parameters.LabelParameters (ec, InvokeBuilder, Location);
				OptAttributes.Emit (ec, this);
			}

			base.Emit (tc);
		}

		protected override string[] ValidAttributeTargets {
			get {
				return attribute_targets;
			}
		}

		//TODO: duplicate
		protected override bool VerifyClsCompliance (DeclSpace ds)
		{
			if (!base.VerifyClsCompliance (ds)) {
				return false;
			}

			AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);

			if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
				Report.Error_T (3002, Location, GetSignatureForError ());
			}
			return true;
		}

		/// <summary>
		///  Verifies whether the method in question is compatible with the delegate
		///  Returns the method itself if okay and null if not.
		/// </summary>
		public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
						       Location loc)
		{
			ParameterData pd = Invocation.GetParameterData (mb);

			int pd_count = pd.Count;

			Expression ml = Expression.MemberLookup (
				ec, delegate_type, "Invoke", loc);

			if (!(ml is MethodGroupExpr)) {
				Report.Error (-100, loc, "Internal error: could not find Invoke method!");
				return null;
			}

			MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];

			ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);

			if (invoke_pd.Count != pd_count)
				return null;

			for (int i = pd_count; i > 0; ) {
				i--;

				if (invoke_pd.ParameterType (i) == pd.ParameterType (i) &&
				    invoke_pd.ParameterModifier (i) == pd.ParameterModifier (i))
					continue;
				else {
					return null;
				}
			}

			if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
				return mb;
			else
				return null;
		}

		// <summary>
		//  Verifies whether the invocation arguments are compatible with the
		//  delegate's target method
		// </summary>
		public static bool VerifyApplicability (EmitContext ec,
							Type delegate_type,
							ArrayList args,
							Location loc)
		{
			int arg_count;

			if (args == null)
				arg_count = 0;
			else
				arg_count = args.Count;

			Expression ml = Expression.MemberLookup (
				ec, delegate_type, "Invoke", loc);

			if (!(ml is MethodGroupExpr)) {
				Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
				return false;
			}
			
			MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
			ParameterData pd = Invocation.GetParameterData (mb);

			int pd_count = pd.Count;

			bool params_method = (pd_count != 0) &&
				(pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS);

			if (!params_method && pd_count != arg_count) {
				Report.Error (1593, loc,
					      "Delegate '" + delegate_type.ToString ()
					      + "' does not take '" + arg_count + "' arguments");
				return false;
			}

			//
			// Consider the case:
			//   delegate void FOO(param object[] args);
			//   FOO f = new FOO(...);
			//   f(new object[] {1, 2, 3});
			//
			// This should be treated like f(1,2,3).  This is done by ignoring the 
			// 'param' modifier for that invocation.  If that fails, then the
			// 'param' modifier is considered.
			//
			// One issue is that 'VerifyArgumentsCompat' modifies the elements of
			// the 'args' array.  However, the modifications appear idempotent.
			// Normal 'Invocation's also have the same behaviour, implicitly.
			//

			bool ans = false;
			if (arg_count == pd_count)
				ans = Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, false, delegate_type, loc);
			if (!ans && params_method)
				ans = Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, true,  delegate_type, loc);
			return ans;
		}
		
		/// <summary>
		///  Verifies whether the delegate in question is compatible with this one in
		///  order to determine if instantiation from the same is possible.
		/// </summary>
		public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
		{
			Expression ml = Expression.MemberLookup (
				ec, delegate_type, "Invoke", loc);
			
			if (!(ml is MethodGroupExpr)) {
				Report.Error (-100, loc, "Internal error: could not find Invoke method!");
				return false;
			}
			
			MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
			ParameterData pd = Invocation.GetParameterData (mb);

			Expression probe_ml = Expression.MemberLookup (
				ec, delegate_type, "Invoke", loc);
			
			if (!(probe_ml is MethodGroupExpr)) {
				Report.Error (-100, loc, "Internal error: could not find Invoke method!");
				return false;
			}
			
			MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
			ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
			
			if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
				return false;

			if (pd.Count != probe_pd.Count)
				return false;

			for (int i = pd.Count; i > 0; ) {
				i--;

				if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
				    pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
					return false;
			}
			
			return true;
		}
		
		public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
		{
			StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
			
			sb.Append (" " + del_type.ToString ());
			sb.Append (" (");

			int length = pd.Count;
			
			for (int i = length; i > 0; ) {
				i--;

				sb.Append (pd.ParameterDesc (length - i - 1));
				if (i != 0)
					sb.Append (", ");
			}
			
			sb.Append (")");
			return sb.ToString ();
			
		}
		
		// Hack around System.Reflection as found everywhere else
		public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
							MemberFilter filter, object criteria)
		{
			ArrayList members = new ArrayList ();

			if ((mt & MemberTypes.Method) != 0) {
				if (ConstructorBuilder != null)
				if (filter (ConstructorBuilder, criteria))
					members.Add (ConstructorBuilder);

				if (InvokeBuilder != null)
				if (filter (InvokeBuilder, criteria))
					members.Add (InvokeBuilder);

				if (BeginInvokeBuilder != null)
				if (filter (BeginInvokeBuilder, criteria))
					members.Add (BeginInvokeBuilder);

				if (EndInvokeBuilder != null)
				if (filter (EndInvokeBuilder, criteria))
					members.Add (EndInvokeBuilder);
			}

			return new MemberList (members);
		}

		public override MemberCache MemberCache {
			get {
				return null;
			}
		}

		public Expression InstanceExpression {
			get {
				return instance_expr;
			}
			set {
				instance_expr = value;
			}
		}

		public MethodBase TargetMethod {
			get {
				return delegate_method;
			}
			set {
				delegate_method = value;
			}
		}

		public Type TargetReturnType {
			get {
				return ret_type;
			}
		}

		public Type [] ParameterTypes {
			get {
				return param_types;
			}
		}

		public override AttributeTargets AttributeTargets {
			get {
				return AttributeTargets.Delegate | AttributeTargets.ReturnValue;
			}
		}

		protected override void VerifyObsoleteAttribute()
		{
			CheckUsageOfObsoleteAttribute (ret_type);

			foreach (Type type in param_types) {
				CheckUsageOfObsoleteAttribute (type);
			}
		}
	}

	//
	// Base class for `NewDelegate' and `ImplicitDelegateCreation'
	//
	public abstract class DelegateCreation : Expression {
		protected MethodBase constructor_method;
		protected MethodBase delegate_method;
		protected MethodGroupExpr method_group;

		public DelegateCreation () {}

		public static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
		{
			string method_desc;
			
			if (mg.Methods.Length > 1)
				method_desc = mg.Methods [0].Name;
			else
				method_desc = Invocation.FullMethodDesc (mg.Methods [0]);

			Expression invoke_method = Expression.MemberLookup (
				ec, type, "Invoke", MemberTypes.Method,
				Expression.AllBindingFlags, loc);
			MethodBase method = ((MethodGroupExpr) invoke_method).Methods [0];
			ParameterData param = Invocation.GetParameterData (method);
			string delegate_desc = Delegate.FullDelegateDesc (type, method, param);
			
			Report.Error (123, loc, "Method '" + method_desc + "' does not " +
				      "match delegate '" + delegate_desc + "'");
		}
		
		public override void Emit (EmitContext ec)
		{
			if (method_group.InstanceExpression == null ||
			    delegate_method.IsStatic)
				ec.ig.Emit (OpCodes.Ldnull);
			else
				method_group.InstanceExpression.Emit (ec);
			
			if (delegate_method.IsVirtual && !method_group.IsBase) {
				ec.ig.Emit (OpCodes.Dup);
				ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
			} else
				ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
			ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
		}

		protected bool ResolveConstructorMethod (EmitContext ec)
		{
			Expression ml = Expression.MemberLookup (
				ec, type, ".ctor", loc);

			if (!(ml is MethodGroupExpr)) {
				Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
				return false;
			}

			constructor_method = ((MethodGroupExpr) ml).Methods [0];
			return true;
		}

		protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg)
		{
			foreach (MethodInfo mi in mg.Methods){
				delegate_method  = Delegate.VerifyMethod (ec, type, mi, loc);
				
				if (delegate_method != null)
					break;
			}
			
			if (delegate_method == null) {
				Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
				return null;
			}
			
			//
			// Check safe/unsafe of the delegate
			//
			if (!ec.InUnsafe){
				ParameterData param = Invocation.GetParameterData (delegate_method);
				int count = param.Count;
				
				for (int i = 0; i < count; i++){
					if (param.ParameterType (i).IsPointer){
						Expression.UnsafeError (loc);
						return null;
					}
				}
			}
			
			//TODO: implement caching when performance will be low
			IMethodData md = TypeManager.GetMethod (delegate_method);
			if (md == null) {
				if (System.Attribute.GetCustomAttribute (delegate_method, TypeManager.conditional_attribute_type) != null) {
					// Cannot create delegate with '{0}' because it has a Conditional attribute
					Report.Error_T (1618, loc, TypeManager.CSharpSignature (delegate_method));
				}
			} else {
				if (md.OptAttributes != null && md.OptAttributes.Search (TypeManager.conditional_attribute_type, ec) != null) {
					// Cannot create delegate with '{0}' because it has a Conditional attribute
					Report.Error_T (1618, loc, TypeManager.CSharpSignature (delegate_method));
				}
			}
			
			if (mg.InstanceExpression != null)
				mg.InstanceExpression = mg.InstanceExpression.Resolve (ec);
			else if (ec.IsStatic) {
				if (!delegate_method.IsStatic) {
					Report.Error (120, loc,
						      "An object reference is required for the non-static method " +
						      delegate_method.Name);
					return null;
				}
				mg.InstanceExpression = null;
			} else
				mg.InstanceExpression = ec.GetThis (loc);
			
			if (mg.InstanceExpression != null && mg.InstanceExpression.Type.IsValueType)
				mg.InstanceExpression = new BoxedCast (mg.InstanceExpression);
			
			method_group = mg;
			eclass = ExprClass.Value;
			return this;
		}
	}

	//
	// Created from the conversion code
	//
	public class ImplicitDelegateCreation : DelegateCreation {

		ImplicitDelegateCreation (Type t, Location l)
		{
			type = t;
			loc = l;
		}

		public override Expression DoResolve (EmitContext ec)
		{
			return this;
		}
		
		static public Expression Create (EmitContext ec, MethodGroupExpr mge, Type target_type, Location loc)
		{
			ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
			if (d.ResolveConstructorMethod (ec))
				return d.ResolveMethodGroupExpr (ec, mge);
			else
				return null;
		}
	}
	
	//
	// A delegate-creation-expression, invoked from the `New' class 
	//
	public class NewDelegate : DelegateCreation {
		public ArrayList Arguments;

		//
		// This constructor is invoked from the `New' expression
		//
		public NewDelegate (Type type, ArrayList Arguments, Location loc)
		{
			this.type = type;
			this.Arguments = Arguments;
			this.loc  = loc; 
		}

		public override Expression DoResolve (EmitContext ec)
		{
			if (Arguments == null || Arguments.Count != 1) {
				Report.Error (149, loc,
					      "Method name expected");
				return null;
			}

			if (!ResolveConstructorMethod (ec))
				return null;

			Argument a = (Argument) Arguments [0];

			if (!a.ResolveMethodGroup (ec, loc))
				return null;
			
			Expression e = a.Expr;

			MethodGroupExpr mg = e as MethodGroupExpr;
			if (mg != null)
				return ResolveMethodGroupExpr (ec, mg);

			Type e_type = e.Type;

			if (!TypeManager.IsDelegateType (e_type)) {
				e.Error_UnexpectedKind ("method");
				return null;
			}

			method_group = Expression.MemberLookup (
				ec, type, "Invoke", MemberTypes.Method,
				Expression.AllBindingFlags, loc) as MethodGroupExpr;

			if (method_group == null) {
				Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
				return null;
			}

			// This is what MS' compiler reports. We could always choose
			// to be more verbose and actually give delegate-level specifics			
			if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
				Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
					      "to type '" + type + "'");
				return null;
			}
				
			method_group.InstanceExpression = e;
			delegate_method = method_group.Methods [0];
			
			eclass = ExprClass.Value;
			return this;
		}
	}

	public class DelegateInvocation : ExpressionStatement {

		public Expression InstanceExpr;
		public ArrayList  Arguments;

		MethodBase method;
		
		public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
		{
			this.InstanceExpr = instance_expr;
			this.Arguments = args;
			this.loc = loc;
		}

		public override Expression DoResolve (EmitContext ec)
		{
			if (InstanceExpr is EventExpr) {
				
				EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
				
				Expression ml = MemberLookup (
					ec, ec.ContainerType, ei.Name,
					MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);

				if (ml == null) {
				        //
					// If this is the case, then the Event does not belong 
					// to this Type and so, according to the spec
					// cannot be accessed directly
					//
					// Note that target will not appear as an EventExpr
					// in the case it is being referenced within the same type container;
					// it will appear as a FieldExpr in that case.
					//
					
					Assign.error70 (ei, loc);
					return null;
				}
			}
			
			
			Type del_type = InstanceExpr.Type;
			if (del_type == null)
				return null;
			
			if (Arguments != null){
				foreach (Argument a in Arguments){
					if (!a.Resolve (ec, loc))
						return null;
				}
			}
			
			if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
				return null;

			Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
			if (!(lookup is MethodGroupExpr)) {
				Report.Error (-100, loc, "Internal error: could not find Invoke method!");
				return null;
			}
			
			method = ((MethodGroupExpr) lookup).Methods [0];
			type = ((MethodInfo) method).ReturnType;
			eclass = ExprClass.Value;
			
			return this;
		}

		public override void Emit (EmitContext ec)
		{
			//
			// Invocation on delegates call the virtual Invoke member
			// so we are always `instance' calls
			//
			Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
		}

		public override void EmitStatement (EmitContext ec)
		{
			Emit (ec);
			// 
			// Pop the return value if there is one
			//
			if (method is MethodInfo){
				if (((MethodInfo) method).ReturnType != TypeManager.void_type)
					ec.ig.Emit (OpCodes.Pop);
			}
		}

	}
}