2 // anonymous.cs: Support for anonymous methods
5 // Miguel de Icaza (miguel@ximain.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003-2008 Novell, Inc.
11 // TODO: Ideally, we should have the helper classes emited as a hierarchy to map
12 // their nesting, and have the visibility set to private, instead of NestedAssembly
19 using System.Collections;
20 using System.Reflection;
21 using System.Reflection.Emit;
23 namespace Mono.CSharp {
25 public abstract class CompilerGeneratedClass : Class
27 GenericMethod generic_method;
28 static int next_index = 0;
30 private static MemberName MakeProxyName (GenericMethod generic, Location loc)
32 string name = MakeName (null, "CompilerGenerated");
33 if (generic != null) {
34 TypeArguments args = new TypeArguments (loc);
35 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
36 args.Add (new SimpleName (tparam.Name, loc));
37 return new MemberName (name, args, loc);
39 return new MemberName (name, loc);
42 public static string MakeName (string host, string prefix)
44 return "<" + host + ">c__" + prefix + next_index++;
47 public static void Reset ()
52 protected CompilerGeneratedClass (DeclSpace parent,
53 MemberName name, int mod, Location loc) :
54 base (parent.NamespaceEntry, parent, name, mod | Modifiers.COMPILER_GENERATED, null)
56 parent.PartialContainer.AddCompilerGeneratedClass (this);
59 protected CompilerGeneratedClass (DeclSpace parent, GenericMethod generic,
60 int mod, Location loc)
61 : this (parent, MakeProxyName (generic, loc), mod, loc)
63 this.generic_method = generic;
65 if (generic != null) {
66 ArrayList list = new ArrayList ();
67 foreach (TypeParameter tparam in generic.TypeParameters) {
68 if (tparam.Constraints != null)
69 list.Add (tparam.Constraints.Clone ());
71 SetParameterInfo (list);
76 protected override bool DefineNestedTypes ()
78 RootContext.RegisterCompilerGeneratedType (TypeBuilder);
79 return base.DefineNestedTypes ();
82 protected override bool DoDefineMembers ()
84 members_defined = true;
86 if (!base.DoDefineMembers ())
89 if (CompilerGenerated != null) {
90 foreach (CompilerGeneratedClass c in CompilerGenerated) {
91 if (!c.DefineMembers ())
92 throw new InternalErrorException ();
99 protected override bool DoResolveMembers ()
101 if (CompilerGenerated != null) {
102 foreach (CompilerGeneratedClass c in CompilerGenerated) {
103 if (!c.ResolveMembers ())
108 return base.DoResolveMembers ();
111 public GenericMethod GenericMethod {
112 get { return generic_method; }
115 public Parameters InflateParameters (Parameters ps)
117 if (generic_method == null)
124 Parameter[] inflated_params = new Parameter [n];
125 Type[] inflated_types = new Type [n];
127 for (int i = 0; i < n; ++i) {
128 Parameter p = ps [i];
129 Type it = InflateType (p.ExternalType ()).ResolveAsTypeTerminal (this, false).Type;
130 inflated_types [i] = it;
131 inflated_params [i] = new Parameter (it, p.Name, p.ModFlags, p.OptAttributes, p.Location);
133 return Parameters.CreateFullyResolved (inflated_params, inflated_types);
136 public TypeExpr InflateType (Type it)
139 if (generic_method == null)
140 return new TypeExpression (it, Location);
142 if (it.IsGenericParameter && (it.DeclaringMethod != null)) {
143 int pos = it.GenericParameterPosition;
144 it = CurrentTypeParameters [pos].Type;
145 } else if (it.IsGenericType) {
146 Type[] args = it.GetGenericArguments ();
148 TypeArguments inflated = new TypeArguments (Location);
149 foreach (Type t in args)
150 inflated.Add (InflateType (t));
152 return new ConstructedType (it, inflated, Location);
153 } else if (it.IsArray) {
154 TypeExpr et_expr = InflateType (it.GetElementType ());
155 int rank = it.GetArrayRank ();
157 Type et = et_expr.ResolveAsTypeTerminal (this, false).Type;
158 it = et.MakeArrayType (rank);
162 return new TypeExpression (it, Location);
165 public Field CaptureVariable (string name, TypeExpr type)
168 throw new InternalErrorException ("Helper class already defined!");
170 throw new ArgumentNullException ();
172 return new CapturedVariableField (this, name, type);
175 bool members_defined;
177 internal void CheckMembersDefined ()
180 throw new InternalErrorException ("Helper class already defined!");
183 protected class CapturedVariableField : Field
185 public CapturedVariableField (CompilerGeneratedClass helper, string name,
187 : base (helper, type, Modifiers.INTERNAL, name, null, helper.Location)
189 helper.AddField (this);
194 public class ScopeInfo : CompilerGeneratedClass
196 protected readonly RootScopeInfo RootScope;
197 new public readonly DeclSpace Parent;
198 public readonly int ID = ++next_id;
199 public readonly Block ScopeBlock;
200 protected ScopeInitializer scope_initializer;
202 readonly Hashtable locals = new Hashtable ();
203 readonly Hashtable captured_scopes = new Hashtable ();
204 Hashtable captured_params;
208 public static ScopeInfo CreateScope (Block block)
210 ToplevelBlock toplevel = block.Toplevel;
211 AnonymousContainer ac = toplevel.AnonymousContainer;
213 Report.Debug (128, "CREATE SCOPE", block, block.ScopeInfo, toplevel, ac);
216 return new ScopeInfo (block, toplevel.RootScope.Parent,
217 toplevel.RootScope.GenericMethod);
219 Report.Debug (128, "CREATE SCOPE #1", ac, ac.Host, ac.Scope, ac.Block,
224 ScopeInfo parent = null;
226 for (b = ac.Block; b != null; b = b.Parent) {
227 if (b.ScopeInfo != null) {
228 parent = b.ScopeInfo;
233 Report.Debug (128, "CREATE SCOPE #2", parent);
235 ScopeInfo new_scope = new ScopeInfo (block, parent, null);
237 Report.Debug (128, "CREATE SCOPE #3", new_scope);
242 private static int default_modflags (DeclSpace parent)
244 return parent is CompilerGeneratedClass ? Modifiers.PUBLIC : Modifiers.PRIVATE;
247 protected ScopeInfo (Block block, DeclSpace parent, GenericMethod generic)
248 : base (parent, generic, default_modflags (parent), block.StartLocation)
251 RootScope = block.Toplevel.RootScope;
254 Report.Debug (128, "NEW SCOPE", this, block,
255 block.Parent, block.Toplevel);
257 RootScope.AddScope (this);
260 protected ScopeInfo (ToplevelBlock toplevel, DeclSpace parent,
261 GenericMethod generic, Location loc)
262 : base (parent, generic, default_modflags (parent), loc)
265 RootScope = (RootScopeInfo) this;
266 ScopeBlock = toplevel;
268 Report.Debug (128, "NEW ROOT SCOPE", this, toplevel, loc);
271 protected CapturedScope[] CapturedScopes {
273 CapturedScope[] list = new CapturedScope [captured_scopes.Count];
274 captured_scopes.Values.CopyTo (list, 0);
279 protected CapturedVariable GetCapturedScope (ScopeInfo scope)
281 return (CapturedVariable) captured_scopes [scope];
284 protected void EmitScopeInstance (EmitContext ec)
286 if (scope_initializer == null) {
288 // This is needed if someone overwrites the Emit method
289 // of Statement and manually calls Block.Emit without
290 // this snippet first:
292 // ec.EmitScopeInitFromBlock (The_Block);
293 // The_Block.Emit (ec);
295 throw new InternalErrorException ();
298 scope_initializer.Emit (ec);
301 public ExpressionStatement GetScopeInitializer (EmitContext ec)
303 Report.Debug (128, "GET SCOPE INITIALIZER",
304 this, GetType (), scope_initializer, ScopeBlock);
306 if (scope_initializer == null) {
307 scope_initializer = CreateScopeInitializer ();
308 if (scope_initializer.Resolve (ec) == null)
309 throw new InternalErrorException ();
312 return scope_initializer;
315 public Type GetScopeType (EmitContext ec)
320 TypeArguments targs = new TypeArguments (Location);
322 if (ec.DeclContainer.Parent.IsGeneric)
323 foreach (TypeParameter t in ec.DeclContainer.Parent.TypeParameters)
324 targs.Add (new TypeParameterExpr (t, Location));
325 if (ec.DeclContainer.IsGeneric)
326 foreach (TypeParameter t in ec.DeclContainer.CurrentTypeParameters)
327 targs.Add (new TypeParameterExpr (t, Location));
329 Report.Debug (128, "GET SCOPE TYPE", this, TypeBuilder, targs,
330 ec.DeclContainer, ec.DeclContainer.GetType (),
331 ec.DeclContainer.Parent.Name);
333 TypeExpr te = new ConstructedType (TypeBuilder, targs, Location);
334 te = te.ResolveAsTypeTerminal (ec, false);
335 if ((te == null) || (te.Type == null))
340 protected override bool DoDefineMembers ()
342 Report.Debug (64, "SCOPE INFO DEFINE MEMBERS", this, GetType (), IsGeneric,
343 Parent.IsGeneric, GenericMethod);
345 foreach (CapturedScope child in CapturedScopes) {
346 if (!child.DefineMembers ())
350 return base.DoDefineMembers ();
353 protected override bool DoResolveMembers ()
355 Report.Debug (64, "SCOPE INFO RESOLVE MEMBERS", this, GetType (), IsGeneric,
356 Parent.IsGeneric, GenericMethod);
358 return base.DoResolveMembers ();
361 public Variable CaptureScope (ScopeInfo child)
363 CheckMembersDefined ();
364 Report.Debug (128, "CAPTURE SCOPE", this, GetType (), child, child.GetType ());
366 throw new InternalErrorException ();
367 CapturedScope captured = (CapturedScope) captured_scopes [child];
368 if (captured == null) {
369 captured = new CapturedScope (this, child);
370 captured_scopes.Add (child, captured);
375 public Variable AddLocal (LocalInfo local)
377 Report.Debug (128, "CAPTURE LOCAL", this, local);
378 Variable var = (Variable) locals [local];
380 var = new CapturedLocal (this, local);
381 locals.Add (local, var);
382 local.IsCaptured = true;
387 public Variable GetCapturedVariable (LocalInfo local)
389 return (Variable) locals [local];
392 public bool HostsParameters {
393 get { return captured_params != null; }
396 public Variable GetCapturedParameter (Parameter par)
398 if (captured_params != null)
399 return (Variable) captured_params [par];
404 public Variable AddParameter (Parameter par, int idx)
406 if (captured_params == null)
407 captured_params = new Hashtable ();
409 Variable var = (Variable) captured_params [par];
411 var = new CapturedParameter (this, par, idx);
412 captured_params.Add (par, var);
413 par.IsCaptured = true;
419 public override void EmitType ()
421 SymbolWriter.DefineAnonymousScope (ID);
422 foreach (CapturedLocal local in locals.Values)
423 local.EmitSymbolInfo ();
425 if (captured_params != null) {
426 foreach (CapturedParameter param in captured_params.Values)
427 param.EmitSymbolInfo ();
430 foreach (CapturedScope scope in CapturedScopes) {
431 scope.EmitSymbolInfo ();
437 protected string MakeFieldName (string local_name)
439 return "<" + ID + ":" + local_name + ">";
442 protected virtual ScopeInitializer CreateScopeInitializer ()
444 return new ScopeInitializer (this);
447 protected abstract class CapturedVariable : Variable
449 public readonly ScopeInfo Scope;
450 public readonly string Name;
452 public FieldExpr FieldInstance;
453 protected Field field;
455 protected CapturedVariable (ScopeInfo scope, string name)
461 protected CapturedVariable (ScopeInfo scope, string name, Type type)
464 this.field = scope.CaptureVariable (
465 scope.MakeFieldName (name), scope.RootScope.InflateType (type));
469 get { return field; }
472 public override Type Type {
473 get { return Field.MemberType; }
476 public override bool HasInstance {
480 public override bool NeedsTemporary {
484 protected FieldInfo GetField (EmitContext ec)
486 if ((ec.CurrentBlock != null) &&
487 (ec.CurrentBlock.Toplevel != Scope.ScopeBlock.Toplevel))
488 return Field.FieldBuilder;
490 return FieldInstance.FieldInfo;
493 public abstract void EmitSymbolInfo ();
495 public override void EmitInstance (EmitContext ec)
497 if ((ec.CurrentAnonymousMethod != null) &&
498 (ec.CurrentAnonymousMethod.Scope == Scope)) {
499 ec.ig.Emit (OpCodes.Ldarg_0);
503 Scope.EmitScopeInstance (ec);
506 public override void Emit (EmitContext ec)
508 ec.ig.Emit (OpCodes.Ldfld, GetField (ec));
511 public override void EmitAssign (EmitContext ec)
513 ec.ig.Emit (OpCodes.Stfld, GetField (ec));
516 public override void EmitAddressOf (EmitContext ec)
518 ec.ig.Emit (OpCodes.Ldflda, GetField (ec));
522 protected class CapturedParameter : CapturedVariable {
523 public readonly Parameter Parameter;
524 public readonly int Idx;
526 public CapturedParameter (ScopeInfo scope, Parameter par, int idx)
527 : base (scope, par.Name, par.ParameterType)
529 this.Parameter = par;
533 public override void EmitSymbolInfo ()
535 SymbolWriter.DefineCapturedParameter (
536 Scope.ID, Parameter.Name, Field.Name);
539 public override string ToString ()
541 return String.Format ("{0} ({1}:{2}:{3})", GetType (), Field,
542 Parameter.Name, Idx);
546 protected class CapturedLocal : CapturedVariable {
547 public readonly LocalInfo Local;
549 public CapturedLocal (ScopeInfo scope, LocalInfo local)
550 : base (scope, local.Name, local.VariableType)
555 public override void EmitSymbolInfo ()
557 SymbolWriter.DefineCapturedLocal (
558 Scope.ID, Local.Name, Field.Name);
561 public override string ToString ()
563 return String.Format ("{0} ({1}:{2})", GetType (), Field,
568 protected class CapturedThis : CapturedVariable {
569 public CapturedThis (RootScopeInfo host)
570 : base (host, "<>THIS", host.ParentType)
573 public override void EmitSymbolInfo ()
575 SymbolWriter.DefineCapturedThis (Scope.ID, Field.Name);
579 protected class CapturedScope : CapturedVariable {
580 public readonly ScopeInfo ChildScope;
582 public CapturedScope (ScopeInfo root, ScopeInfo child)
583 : base (root, "scope" + child.ID)
585 this.ChildScope = child;
588 public override void EmitSymbolInfo ()
590 SymbolWriter.DefineCapturedScope (Scope.ID, ChildScope.ID, Field.Name);
593 public bool DefineMembers ()
595 Type type = ChildScope.IsGeneric ?
596 ChildScope.CurrentType : ChildScope.TypeBuilder;
597 Report.Debug (128, "CAPTURED SCOPE DEFINE MEMBERS", this, Scope,
598 ChildScope, Name, type);
600 throw new InternalErrorException ();
601 field = Scope.CaptureVariable (
602 Scope.MakeFieldName (Name), Scope.InflateType (type));
606 public override string ToString ()
608 return String.Format ("CapturedScope ({1} captured in {0})",
613 static void DoPath (StringBuilder sb, ScopeInfo start)
615 sb.Append ((start.ID).ToString ());
618 public override string ToString ()
620 StringBuilder sb = new StringBuilder ();
626 return sb.ToString ();
629 protected class ScopeInitializer : ExpressionStatement
632 CapturedVariable captured_scope;
633 LocalBuilder scope_instance;
634 ConstructorInfo scope_ctor;
638 public ScopeInitializer (ScopeInfo scope)
641 this.loc = scope.Location;
642 eclass = ExprClass.Value;
645 public ScopeInfo Scope {
646 get { return scope; }
649 public override Expression DoResolve (EmitContext ec)
651 if (scope_ctor != null)
654 Report.Debug (64, "RESOLVE SCOPE INITIALIZER BASE", this, Scope,
655 ec, ec.CurrentBlock);
657 type = Scope.GetScopeType (ec);
659 throw new InternalErrorException ();
661 if (!DoResolveInternal (ec))
662 throw new InternalErrorException ();
667 protected virtual bool DoResolveInternal (EmitContext ec)
669 MethodGroupExpr mg = (MethodGroupExpr) MemberLookupFinal (
670 ec, ec.ContainerType, type, ".ctor", MemberTypes.Constructor,
671 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
673 throw new InternalErrorException ();
675 scope_ctor = (ConstructorInfo) mg.Methods [0];
677 Report.Debug (128, "RESOLVE THE INIT", this, Scope, Scope.RootScope,
678 Scope.RootScope.GetType ());
680 ScopeInfo host = Scope.RootScope;
681 if ((Scope != host) && (Scope.RootScope is IteratorHost)) {
682 captured_scope = host.GetCapturedScope (Scope);
683 Type root = host.GetScopeType (ec);
684 FieldExpr fe = (FieldExpr) Expression.MemberLookup (
685 type, root, captured_scope.Field.Name, loc);
687 throw new InternalErrorException ();
689 fe.InstanceExpression = this;
690 captured_scope.FieldInstance = fe;
692 Report.Debug (128, "RESOLVE THE INIT #1", this,
695 scope_instance = ec.ig.DeclareLocal (type);
696 if (!Scope.RootScope.IsIterator)
697 SymbolWriter.DefineScopeVariable (Scope.ID, scope_instance);
700 foreach (CapturedLocal local in Scope.locals.Values) {
701 FieldExpr fe = (FieldExpr) Expression.MemberLookup (
702 ec.ContainerType, type, local.Field.Name, loc);
703 Report.Debug (64, "RESOLVE SCOPE INITIALIZER #2", this, Scope,
704 Scope, ec, ec.ContainerType, type,
705 local.Field, local.Field.Name, loc, fe);
707 throw new InternalErrorException ();
709 fe.InstanceExpression = this;
710 local.FieldInstance = fe;
713 if (Scope.HostsParameters) {
714 foreach (CapturedParameter cp in Scope.captured_params.Values) {
715 FieldExpr fe = (FieldExpr) Expression.MemberLookup (
716 ec.ContainerType, type, cp.Field.Name, loc);
718 throw new InternalErrorException ();
720 fe.InstanceExpression = this;
721 cp.FieldInstance = fe;
725 foreach (CapturedScope scope in Scope.CapturedScopes) {
726 FieldExpr fe = (FieldExpr) Expression.MemberLookup (
727 ec.ContainerType, type, scope.Field.Name, loc);
728 Report.Debug (64, "RESOLVE SCOPE INITIALIZER #3", this, Scope,
729 scope, ec, ec.ContainerType, type,
730 scope.Field, scope.Field.Name, loc, fe);
732 throw new InternalErrorException ();
734 fe.InstanceExpression = this;
735 scope.FieldInstance = fe;
741 protected virtual void EmitParameterReference (EmitContext ec,
742 CapturedParameter cp)
744 int extra = ec.MethodIsStatic ? 0 : 1;
745 ParameterReference.EmitLdArg (ec.ig, cp.Idx + extra);
751 protected virtual void DoEmit (EmitContext ec)
753 if ((ec.CurrentBlock != null) &&
754 (ec.CurrentBlock.Toplevel != Scope.ScopeBlock.Toplevel)) {
755 ec.ig.Emit (OpCodes.Ldarg_0);
757 if (ec.CurrentAnonymousMethod != null) {
758 ScopeInfo host = ec.CurrentAnonymousMethod.Scope;
759 Variable captured = host.GetCapturedScope (scope);
760 Report.Debug (128, "EMIT SCOPE INSTANCE #2",
761 ec.CurrentAnonymousMethod, host,
763 if (captured != null)
766 } else if (scope_instance != null)
767 ec.ig.Emit (OpCodes.Ldloc, scope_instance);
769 Report.Debug (128, "DO EMIT", this, Scope, ec,
770 scope_instance, captured_scope);
771 captured_scope.EmitInstance (ec);
772 captured_scope.Emit (ec);
776 protected void DoEmitInstance (EmitContext ec)
778 Report.Debug (128, "DO EMIT INSTANCE", this, Scope, ec,
779 scope_instance, captured_scope);
781 if (scope_instance != null)
782 ec.ig.Emit (OpCodes.Ldloc, scope_instance);
784 captured_scope.EmitInstance (ec);
787 protected virtual void EmitScopeConstructor (EmitContext ec)
789 ec.ig.Emit (OpCodes.Newobj, scope_ctor);
792 public override void Emit (EmitContext ec)
795 throw new InternalErrorException (
796 "Scope {0} not initialized yet", scope);
801 public override void EmitStatement (EmitContext ec)
806 DoEmitStatement (ec);
810 protected virtual void DoEmitStatement (EmitContext ec)
812 Report.Debug (128, "EMIT SCOPE INITIALIZER STATEMENT", this, id,
813 Scope, scope_instance, ec);
815 ec.ig.Emit (OpCodes.Nop);
816 ec.ig.Emit (OpCodes.Ldc_I4, id);
817 ec.ig.Emit (OpCodes.Pop);
818 ec.ig.Emit (OpCodes.Nop);
820 if (scope_instance == null)
821 ec.ig.Emit (OpCodes.Ldarg_0);
822 EmitScopeConstructor (ec);
823 if (scope_instance != null)
824 ec.ig.Emit (OpCodes.Stloc, scope_instance);
826 captured_scope.EmitAssign (ec);
828 if (Scope.HostsParameters) {
829 foreach (CapturedParameter cp in Scope.captured_params.Values) {
830 Report.Debug (128, "EMIT SCOPE INIT #6", this,
831 ec, ec.IsStatic, Scope, cp, cp.Field.Name);
833 EmitParameterReference (ec, cp);
834 ec.ig.Emit (OpCodes.Stfld, cp.FieldInstance.FieldInfo);
838 if (Scope is IteratorHost)
841 foreach (CapturedScope scope in Scope.CapturedScopes) {
842 ScopeInfo child = scope.ChildScope;
844 Report.Debug (128, "EMIT SCOPE INIT #5", this, Scope,
845 scope.Scope, scope.ChildScope);
847 ExpressionStatement init = child.GetScopeInitializer (ec);
848 init.EmitStatement (ec);
851 scope.ChildScope.EmitScopeInstance (ec);
852 scope.EmitAssign (ec);
858 public class RootScopeInfo : ScopeInfo
860 public RootScopeInfo (ToplevelBlock toplevel, DeclSpace parent,
861 GenericMethod generic, Location loc)
862 : base (toplevel, parent, generic, loc)
864 scopes = new ArrayList ();
867 TypeExpr parent_type;
868 CapturedVariableField parent_link;
869 CapturedThis this_variable;
870 protected ArrayList scopes;
872 public virtual bool IsIterator {
873 get { return false; }
876 public RootScopeInfo ParentHost {
877 get { return Parent.PartialContainer as RootScopeInfo; }
880 public Type ParentType {
881 get { return parent_type.Type; }
884 public Field ParentLink {
885 get { return parent_link; }
888 protected CapturedThis THIS {
889 get { return this_variable; }
892 public Variable CaptureThis ()
894 if (ParentHost != null)
895 return ParentHost.CaptureThis ();
897 CheckMembersDefined ();
898 if (this_variable == null)
899 this_variable = new CapturedThis (this);
900 return this_variable;
903 public void AddScope (ScopeInfo scope)
909 public void LinkScopes ()
911 Report.Debug (128, "LINK SCOPES", this, linked, scopes);
917 if (ParentHost != null)
918 ParentHost.LinkScopes ();
920 foreach (ScopeInfo si in scopes) {
922 throw new InternalErrorException ();
923 if (si.DefineType () == null)
924 throw new InternalErrorException ();
925 if (!si.ResolveType ())
926 throw new InternalErrorException ();
929 foreach (ScopeInfo si in scopes) {
930 if (!si.ResolveMembers ())
931 throw new InternalErrorException ();
932 if (!si.DefineMembers ())
933 throw new InternalErrorException ();
937 protected override ScopeInitializer CreateScopeInitializer ()
939 return new RootScopeInitializer (this);
942 protected override bool DefineNestedTypes ()
944 if (Parent.IsGeneric) {
945 parent_type = new ConstructedType (
946 Parent.TypeBuilder, Parent.TypeParameters, Location);
947 parent_type = parent_type.ResolveAsTypeTerminal (this, false);
948 if ((parent_type == null) || (parent_type.Type == null))
951 parent_type = new TypeExpression (Parent.TypeBuilder, Location);
954 CompilerGeneratedClass parent = Parent.PartialContainer as CompilerGeneratedClass;
956 parent_link = new CapturedVariableField (this, "<>parent", parent_type);
958 return base.DefineNestedTypes ();
961 protected override bool DoDefineMembers ()
963 ArrayList args = new ArrayList ();
964 if (this is IteratorHost)
965 args.Add (new Parameter (
966 TypeManager.int32_type, "$PC", Parameter.Modifier.NONE,
970 if (Parent is CompilerGeneratedClass)
971 pfield = parent_link;
973 pfield = this_variable != null ? this_variable.Field : null;
975 args.Add (new Parameter (
976 pfield.MemberType, "parent", Parameter.Modifier.NONE,
979 Parameter[] ctor_params = new Parameter [args.Count];
980 args.CopyTo (ctor_params, 0);
981 Constructor ctor = new Constructor (
982 this, MemberName.Name, Modifiers.PUBLIC,
983 new Parameters (ctor_params),
984 new GeneratedBaseInitializer (Location),
986 AddConstructor (ctor);
988 ctor.Block = new ToplevelBlock (null, Location);
989 ctor.Block.AddStatement (new TheCtor (this));
991 return base.DoDefineMembers ();
994 protected virtual void EmitScopeConstructor (EmitContext ec)
996 int pos = (this is IteratorHost) ? 2 : 1;
999 if (Parent is CompilerGeneratedClass)
1000 pfield = parent_link;
1002 pfield = this_variable != null ? this_variable.Field : null;
1004 if (pfield != null) {
1005 ec.ig.Emit (OpCodes.Ldarg_0);
1006 ec.ig.Emit (OpCodes.Ldarg, pos);
1007 ec.ig.Emit (OpCodes.Stfld, pfield.FieldBuilder);
1012 public override void EmitType ()
1016 THIS.EmitSymbolInfo ();
1019 protected class TheCtor : Statement
1023 public TheCtor (RootScopeInfo host)
1028 public override bool Resolve (EmitContext ec)
1033 protected override void DoEmit (EmitContext ec)
1035 host.EmitScopeConstructor (ec);
1039 protected class RootScopeInitializer : ScopeInitializer
1043 public RootScopeInitializer (RootScopeInfo host)
1049 public RootScopeInfo Host {
1050 get { return host; }
1053 protected override bool DoResolveInternal (EmitContext ec)
1055 Report.Debug (64, "RESOLVE ANONYMOUS METHOD HOST INITIALIZER",
1056 this, Host, Host.ParentType, loc);
1058 if (Host.THIS != null) {
1059 FieldExpr fe = (FieldExpr) Expression.MemberLookup (
1060 ec.ContainerType, type, Host.THIS.Field.Name, loc);
1062 throw new InternalErrorException ();
1064 fe.InstanceExpression = this;
1065 Host.THIS.FieldInstance = fe;
1068 return base.DoResolveInternal (ec);
1071 protected virtual bool IsGetEnumerator {
1072 get { return false; }
1075 protected override void EmitScopeConstructor (EmitContext ec)
1077 if (host.THIS != null) {
1078 ec.ig.Emit (OpCodes.Ldarg_0);
1079 if (IsGetEnumerator)
1080 ec.ig.Emit (OpCodes.Ldfld, host.THIS.Field.FieldBuilder);
1081 else if (host.THIS.Type.IsValueType)
1082 Expression.LoadFromPtr (ec.ig, host.THIS.Type);
1083 } else if (host.ParentLink != null)
1084 ec.ig.Emit (OpCodes.Ldarg_0);
1086 base.EmitScopeConstructor (ec);
1092 public interface IAnonymousContainer
1098 GenericMethod GenericMethod {
1102 RootScopeInfo RootScope {
1111 public interface IAnonymousHost
1114 // Invoked if a yield statement is found in the body
1119 // Invoked if an anonymous method is found in the body
1121 void AddAnonymousMethod (AnonymousMethodExpression anonymous);
1124 public class AnonymousMethodExpression : Expression, IAnonymousContainer, IAnonymousHost
1126 public readonly AnonymousMethodExpression Parent;
1127 public readonly TypeContainer Host;
1128 public readonly Parameters Parameters;
1130 public ToplevelBlock Block;
1132 protected Block container;
1133 protected readonly GenericMethod generic;
1135 public Block Container {
1136 get { return container; }
1139 public GenericMethod GenericMethod {
1140 get { return generic; }
1143 public RootScopeInfo RootScope {
1144 get { return root_scope; }
1147 public AnonymousMethodExpression (AnonymousMethodExpression parent,
1148 GenericMethod generic, TypeContainer host,
1149 Parameters parameters, Block container,
1152 this.Parent = parent;
1153 this.generic = parent != null ? null : generic;
1155 this.Parameters = parameters;
1156 this.container = container;
1159 Report.Debug (64, "NEW ANONYMOUS METHOD EXPRESSION", this, parent, host,
1163 parent.AddAnonymousMethod (this);
1167 RootScopeInfo root_scope;
1169 static int next_index;
1171 void IAnonymousHost.SetYields ()
1173 throw new InvalidOperationException ();
1176 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
1178 if (children == null)
1179 children = new ArrayList ();
1180 children.Add (anonymous);
1183 public bool CreateAnonymousHelpers ()
1185 // FIXME: this polutes expression trees implementation
1187 Report.Debug (64, "ANONYMOUS METHOD EXPRESSION CREATE ROOT SCOPE",
1188 this, Host, container, loc);
1190 if (container != null)
1191 root_scope = container.Toplevel.CreateRootScope (Host);
1193 if (children != null) {
1194 foreach (AnonymousMethodExpression child in children) {
1195 if (!child.CreateAnonymousHelpers ())
1203 public override string ExprClassName {
1205 return "anonymous method";
1209 public virtual bool HasExplicitParameters {
1216 // Returns true if the body of lambda expression can be implicitly
1217 // converted to the delegate of type `delegate_type'
1219 public bool ImplicitStandardConversionExists (Type delegate_type)
1221 EmitContext ec = EmitContext.TempEc;
1222 using (ec.Set (EmitContext.Flags.ProbingMode)) {
1223 return Compatible (ec, delegate_type) != null;
1227 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
1229 if (!ec.IsAnonymousMethodAllowed) {
1230 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1234 if (TypeManager.IsDelegateType (delegate_type))
1235 return delegate_type;
1238 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
1239 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
1240 if (TypeManager.IsDelegateType (delegate_type))
1241 return delegate_type;
1243 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
1244 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
1249 Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
1250 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
1254 protected bool VerifyExplicitParameters (Type delegate_type, ParameterData parameters, bool ignore_error)
1256 if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
1260 Report.Error (1661, loc,
1261 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
1262 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
1267 protected bool VerifyParameterCompatibility (Type delegate_type, ParameterData invoke_pd, bool ignore_errors)
1269 if (Parameters.Count != invoke_pd.Count) {
1273 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
1274 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
1278 if (!HasExplicitParameters)
1282 for (int i = 0; i < Parameters.Count; ++i) {
1283 Parameter.Modifier p_mod = invoke_pd.ParameterModifier (i);
1284 if (Parameters.ParameterModifier (i) != p_mod && p_mod != Parameter.Modifier.PARAMS) {
1288 if (p_mod == Parameter.Modifier.NONE)
1289 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
1290 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.ParameterModifier (i)));
1292 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
1293 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
1298 Type type = invoke_pd.Types [i];
1300 // We assume that generic parameters are always inflated
1301 if (TypeManager.IsGenericParameter (type))
1304 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
1307 if (invoke_pd.ParameterType (i) != Parameters.ParameterType (i)) {
1311 Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
1313 TypeManager.CSharpName (Parameters.ParameterType (i)),
1314 TypeManager.CSharpName (invoke_pd.ParameterType (i)));
1323 // Infers type arguments based on explicit arguments
1325 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
1327 if (!HasExplicitParameters)
1330 if (!TypeManager.IsDelegateType (delegate_type)) {
1332 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
1335 delegate_type = delegate_type.GetGenericArguments () [0];
1336 if (!TypeManager.IsDelegateType (delegate_type))
1343 ParameterData d_params = TypeManager.GetDelegateParameters (delegate_type);
1344 if (d_params.Count != Parameters.Count)
1347 for (int i = 0; i < Parameters.Count; ++i) {
1348 Type itype = d_params.Types [i];
1349 if (!TypeManager.IsGenericParameter (itype)) {
1350 if (!TypeManager.HasElementType (itype))
1353 if (!TypeManager.IsGenericParameter (itype.GetElementType ()))
1356 type_inference.ExactInference (Parameters.FixedParameters[i].ParameterType, itype);
1361 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1364 using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
1365 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
1371 if (am.ReturnType == TypeManager.null_type)
1372 am.ReturnType = null;
1374 return am.ReturnType;
1378 // Returns AnonymousMethod container if this anonymous method
1379 // expression can be implicitly converted to the delegate type `delegate_type'
1381 public Expression Compatible (EmitContext ec, Type type)
1383 Type delegate_type = CompatibleChecks (ec, type);
1384 if (delegate_type == null)
1388 // At this point its the first time we know the return type that is
1389 // needed for the anonymous method. We create the method here.
1392 MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1393 ec.ContainerType, delegate_type);
1394 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1397 Type[] g_args = delegate_type.GetGenericArguments ();
1398 if (return_type.IsGenericParameter)
1399 return_type = g_args [return_type.GenericParameterPosition];
1403 // Second: the return type of the delegate must be compatible with
1404 // the anonymous type. Instead of doing a pass to examine the block
1405 // we satisfy the rule by setting the return type on the EmitContext
1406 // to be the delegate type return type.
1409 Report.Debug (64, "COMPATIBLE", this, Parent, GenericMethod, Host,
1410 Container, Block, return_type, delegate_type,
1411 TypeManager.IsGenericType (delegate_type), loc);
1414 int errors = Report.Errors;
1415 AnonymousMethod am = CompatibleMethod (ec, null, return_type, delegate_type);
1416 if (am != null && delegate_type != type && errors == Report.Errors)
1417 return CreateExpressionTree (ec, delegate_type);
1420 } catch (Exception e) {
1421 throw new InternalErrorException (e, loc);
1425 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1427 Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1431 protected virtual Parameters ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1433 ParameterData delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1435 if (Parameters == null) {
1437 // We provide a set of inaccessible parameters
1439 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1441 for (int i = 0; i < delegate_parameters.Count; i++) {
1442 Parameter.Modifier i_mod = delegate_parameters.ParameterModifier (i);
1443 if ((i_mod & Parameter.Modifier.OUTMASK) != 0) {
1444 Report.Error (1688, loc, "Cannot convert anonymous " +
1445 "method block without a parameter list " +
1446 "to delegate type `{0}' because it has " +
1447 "one or more `out' parameters.",
1448 TypeManager.CSharpName (delegate_type));
1451 fixedpars[i] = new Parameter (
1452 delegate_parameters.ParameterType (i), "+" + (++next_index),
1453 delegate_parameters.ParameterModifier (i), null, loc);
1456 return Parameters.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1459 if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1466 public override Expression DoResolve (EmitContext ec)
1469 // Set class type, set type
1472 eclass = ExprClass.Value;
1475 // This hack means `The type is not accessible
1476 // anywhere', we depend on special conversion
1479 type = TypeManager.anonymous_method_type;
1481 if ((Parameters != null) && !Parameters.Resolve (ec))
1487 public override void Emit (EmitContext ec)
1489 // nothing, as we only exist to not do anything.
1492 public override string GetSignatureForError ()
1494 return ExprClassName;
1497 public bool IsIterator {
1498 get { return false; }
1501 protected AnonymousMethod CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1503 Parameters p = ResolveParameters (ec, tic, delegate_type);
1507 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1509 AnonymousMethod anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1510 if (!anonymous.Compatible (ec))
1516 protected virtual AnonymousMethod CompatibleMethodFactory (Type return_type, Type delegate_type, Parameters p, ToplevelBlock b)
1518 return new AnonymousMethod (RootScope, Host,
1519 GenericMethod, p, Container, b, return_type,
1520 delegate_type, loc);
1523 protected override void CloneTo (CloneContext clonectx, Expression t)
1525 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1527 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1528 target.container = clonectx.LookupBlock (Block);
1532 public abstract class AnonymousContainer : Expression, IAnonymousContainer
1534 public Parameters Parameters;
1537 // The block that makes up the body for the anonymous mehtod
1539 public readonly ToplevelBlock Block;
1541 public readonly int ModFlags;
1542 public Type ReturnType;
1543 public readonly DeclSpace Host;
1546 // The implicit method we create
1548 protected Method method;
1549 protected EmitContext aec;
1551 // The emit context for the anonymous method
1552 protected bool unreachable;
1553 protected readonly Block container;
1554 protected readonly GenericMethod generic;
1556 protected AnonymousContainer (DeclSpace host,
1557 GenericMethod generic, Parameters parameters,
1558 Block container, ToplevelBlock block,
1559 Type return_type, int mod, Location loc)
1561 this.ReturnType = return_type;
1562 this.ModFlags = mod | Modifiers.COMPILER_GENERATED;
1565 this.container = container;
1566 this.generic = generic;
1567 this.Parameters = parameters;
1571 block.AnonymousContainer = this;
1574 public Method Method {
1575 get { return method; }
1578 public abstract string ContainerType {
1582 public abstract RootScopeInfo RootScope {
1586 public abstract ScopeInfo Scope {
1590 public bool Compatible (EmitContext ec)
1592 // REFACTOR: The method should be refactor, many of the
1593 // hacks can be handled in better way
1595 Report.Debug (64, "RESOLVE ANONYMOUS METHOD", this, Location, ec,
1596 RootScope, Parameters, ec.IsStatic);
1598 if (ReturnType != null) {
1599 TypeExpr return_type_expr;
1600 if (RootScope != null)
1601 return_type_expr = RootScope.InflateType (ReturnType);
1603 return_type_expr = new TypeExpression (ReturnType, Location);
1604 return_type_expr = return_type_expr.ResolveAsTypeTerminal (ec, false);
1605 if ((return_type_expr == null) || (return_type_expr.Type == null))
1607 ReturnType = return_type_expr.Type;
1610 // Linq type inference is done differently
1611 if (RootScope != null && RootContext.Version != LanguageVersion.LINQ)
1612 Parameters = RootScope.InflateParameters (Parameters);
1614 aec = new EmitContext (
1615 ec.ResolveContext, ec.TypeContainer,
1616 RootScope != null ? RootScope : Host, Location, null, ReturnType,
1617 /* REVIEW */ (ec.InIterator ? Modifiers.METHOD_YIELDS : 0) |
1618 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1620 aec.CurrentAnonymousMethod = this;
1621 aec.IsStatic = ec.IsStatic;
1624 // HACK: Overwrite parent declaration container to currently resolved.
1625 // It's required for an anonymous container inside partial class.
1627 if (RootScope != null)
1628 aec.DeclContainer.Parent = ec.TypeContainer;
1630 IDisposable aec_dispose = null;
1631 EmitContext.Flags flags = 0;
1632 if (ec.InferReturnType)
1633 flags |= EmitContext.Flags.InferReturnType;
1635 if (ec.IsInProbingMode)
1636 flags |= EmitContext.Flags.ProbingMode;
1638 if (ec.IsInFieldInitializer)
1639 flags |= EmitContext.Flags.InFieldInitializer;
1641 // HACK: Flag with 0 cannot be set
1643 aec_dispose = aec.Set (flags);
1645 Report.Debug (64, "RESOLVE ANONYMOUS METHOD #1", this, Location, ec, aec,
1646 RootScope, Parameters, Block);
1649 bool res = aec.ResolveTopBlock (ec, Block, Parameters, null, out unreachable);
1651 if (ec.InferReturnType)
1652 ReturnType = aec.ReturnType;
1654 if (aec_dispose != null) {
1655 aec_dispose.Dispose ();
1661 public virtual bool Define (EmitContext ec)
1663 Report.Debug (64, "DEFINE ANONYMOUS METHOD #3", this, ec, aec, Block);
1665 if (aec == null && !Compatible (ec))
1668 // Don't define anything when we are in probing scope (nested anonymous methods)
1669 if (ec.IsInProbingMode)
1672 method = DoCreateMethodHost (ec);
1677 if (!method.ResolveMembers ())
1679 return method.Define ();
1682 protected abstract Method DoCreateMethodHost (EmitContext ec);
1684 public override void Emit (EmitContext ec)
1686 throw new NotSupportedException ();
1689 public Block Container {
1690 get { return container; }
1693 public GenericMethod GenericMethod {
1694 get { return generic; }
1697 public abstract bool IsIterator {
1701 protected class AnonymousMethodMethod : Method
1703 public readonly AnonymousContainer AnonymousMethod;
1704 public readonly ScopeInfo Scope;
1705 public readonly string RealName;
1707 public AnonymousMethodMethod (AnonymousContainer am, ScopeInfo scope,
1708 GenericMethod generic, TypeExpr return_type,
1709 int mod, string real_name, MemberName name,
1710 Parameters parameters)
1711 : base (scope != null ? scope : am.Host,
1712 generic, return_type, mod | Modifiers.COMPILER_GENERATED, false, name, parameters, null)
1714 this.AnonymousMethod = am;
1716 this.RealName = real_name;
1718 if (scope != null) {
1719 scope.CheckMembersDefined ();
1720 scope.AddMethod (this);
1722 ModFlags |= Modifiers.STATIC;
1723 am.Host.PartialContainer.AddMethod (this);
1728 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1730 EmitContext aec = AnonymousMethod.aec;
1732 aec.MethodIsStatic = Scope == null;
1736 public override void EmitExtraSymbolInfo ()
1738 SymbolWriter.SetRealMethodName (RealName);
1743 public class AnonymousMethod : AnonymousContainer
1748 // The value return by the Compatible call, this ensure that
1749 // the code works even if invoked more than once (Resolve called
1750 // more than once, due to the way Convert.ImplicitConversion works
1752 RootScopeInfo root_scope;
1755 public AnonymousMethod (RootScopeInfo root_scope,
1756 DeclSpace host, GenericMethod generic,
1757 Parameters parameters, Block container,
1758 ToplevelBlock block, Type return_type, Type delegate_type,
1760 : base (host, generic, parameters, container, block,
1761 return_type, 0, loc)
1763 this.DelegateType = delegate_type;
1764 this.root_scope = root_scope;
1767 public override string ContainerType {
1768 get { return "anonymous method"; }
1771 public override RootScopeInfo RootScope {
1772 get { return root_scope; }
1775 public override ScopeInfo Scope {
1776 get { return scope; }
1779 public override bool IsIterator {
1780 get { return false; }
1783 public override string GetSignatureForError ()
1785 return TypeManager.CSharpName (DelegateType);
1789 // Creates the host for the anonymous method
1791 protected override Method DoCreateMethodHost (EmitContext ec)
1793 MemberCore mc = ec.ResolveContext as MemberCore;
1794 string name = CompilerGeneratedClass.MakeName (mc.Name, null);
1795 MemberName member_name;
1797 Report.Debug (128, "CREATE METHOD HOST #0", RootScope);
1802 Report.Debug (128, "CREATE METHOD HOST #1", this, Block, Block.ScopeInfo,
1803 RootScope, Location);
1805 for (b = Block.Parent; b != null; b = b.Parent) {
1806 Report.Debug (128, "CREATE METHOD HOST #2", this, Block,
1808 if (b.ScopeInfo != null) {
1809 scope = b.ScopeInfo;
1815 scope.CheckMembersDefined ();
1817 ArrayList scopes = new ArrayList ();
1819 for (b = b.Parent; b != null; b = b.Parent) {
1820 if (b.ScopeInfo != null)
1821 scopes.Add (b.ScopeInfo);
1825 Report.Debug (128, "CREATE METHOD HOST #1", this, scope, scopes);
1827 foreach (ScopeInfo si in scopes)
1828 scope.CaptureScope (si);
1830 Report.Debug (128, "CREATE METHOD HOST", this, Block, container,
1831 RootScope, scope, scopes, Location);
1833 GenericMethod generic_method = null;
1835 if (TypeManager.IsGenericType (DelegateType)) {
1836 TypeArguments args = new TypeArguments (Location);
1838 Type dt = DelegateType.GetGenericTypeDefinition ();
1840 Type[] tparam = TypeManager.GetTypeArguments (dt);
1841 for (int i = 0; i < tparam.Length; i++)
1842 args.Add (new SimpleName (tparam [i].Name, Location));
1844 member_name = new MemberName (name, args, Location);
1846 Report.Debug (128, "CREATE METHOD HOST #5", this, DelegateType,
1847 TypeManager.GetTypeArguments (DelegateType),
1850 generic_method = new GenericMethod (
1851 Host.NamespaceEntry, scope, member_name,
1852 new TypeExpression (ReturnType, Location), Parameters);
1854 generic_method.SetParameterInfo (null);
1857 member_name = new MemberName (name, Location);
1859 string real_name = String.Format (
1860 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1861 Parameters.GetSignatureForError ());
1863 return new AnonymousMethodMethod (
1864 this, scope, generic_method, new TypeExpression (ReturnType, Location),
1865 scope == null ? Modifiers.PRIVATE : Modifiers.INTERNAL,
1866 real_name, member_name, Parameters);
1869 public override Expression DoResolve (EmitContext ec)
1874 return new AnonymousDelegate (this, DelegateType, Location).Resolve (ec);
1877 public MethodInfo GetMethodBuilder (EmitContext ec)
1879 MethodInfo builder = method.MethodBuilder;
1880 if ((Scope != null) && Scope.IsGeneric) {
1881 Type scope_type = Scope.GetScopeType (ec);
1882 if (scope_type == null)
1883 throw new InternalErrorException ();
1885 MethodGroupExpr mg = (MethodGroupExpr) Expression.MemberLookup (
1886 ec.ContainerType, scope_type, builder.Name,
1887 MemberTypes.Method, Expression.AllBindingFlags | BindingFlags.NonPublic, Location);
1890 throw new InternalErrorException ();
1891 builder = (MethodInfo) mg.Methods [0];
1895 if (!DelegateType.IsGenericType)
1898 Type[] targs = TypeManager.GetTypeArguments (DelegateType);
1899 return builder.MakeGenericMethod (targs);
1905 public static void Error_AddressOfCapturedVar (string name, Location loc)
1907 Report.Error (1686, loc,
1908 "Local variable `{0}' or its members cannot have their " +
1909 "address taken and be used inside an anonymous method block",
1915 // This will emit the code for the delegate, as well delegate creation on the host
1917 public class AnonymousDelegate : DelegateCreation {
1918 readonly AnonymousMethod am;
1921 // if target_type is null, this means that we do not know the type
1922 // for this delegate, and we want to infer it from the various
1923 // returns (implicit and explicit) from the body of this anonymous
1926 // for example, the lambda: x => 1
1928 public AnonymousDelegate (AnonymousMethod am, Type target_type, Location l)
1935 public override Expression DoResolve (EmitContext ec)
1937 eclass = ExprClass.Value;
1941 public override void Emit (EmitContext ec)
1943 //ec.ig.Emit (OpCodes.Ldstr, "EMIT ANONYMOUS DELEGATE");
1944 //ec.ig.Emit (OpCodes.Pop);
1947 // Now emit the delegate creation.
1949 if ((am.Method.ModFlags & Modifiers.STATIC) == 0) {
1950 Report.Debug (128, "EMIT ANONYMOUS DELEGATE", this, am, am.Scope, loc);
1951 delegate_instance_expression = am.Scope.GetScopeInitializer (ec);
1953 if (delegate_instance_expression == null)
1954 throw new InternalErrorException ();
1957 constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1959 if (type.IsGenericType && type is TypeBuilder)
1960 constructor_method = TypeBuilder.GetConstructor (type, (ConstructorInfo)constructor_method);
1963 delegate_method = am.GetMethodBuilder (ec);
1966 //ec.ig.Emit (OpCodes.Ldstr, "EMIT ANONYMOUS DELEGATE DONE");
1967 //ec.ig.Emit (OpCodes.Pop);
1969 Report.Debug (128, "EMIT ANONYMOUS DELEGATE DONE", this, am, am.Scope, loc);
1974 // Anonymous type container
1976 public class AnonymousTypeClass : CompilerGeneratedClass
1978 static int types_counter;
1979 public const string ClassNamePrefix = "<>__AnonType";
1980 public const string SignatureForError = "anonymous type";
1982 readonly ArrayList parameters;
1984 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1985 : base (parent, name, Modifiers.SEALED, loc)
1987 this.parameters = parameters;
1990 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1992 if (RootContext.Version <= LanguageVersion.ISO_2)
1993 Report.FeatureIsNotAvailable (loc, "anonymous types");
1995 string name = ClassNamePrefix + types_counter++;
1997 SimpleName [] t_args = new SimpleName [parameters.Count];
1998 Parameter [] ctor_params = new Parameter [parameters.Count];
1999 for (int i = 0; i < parameters.Count; ++i) {
2000 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
2002 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
2003 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
2007 // Create generic anonymous type host with generic arguments
2008 // named upon properties names
2010 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
2011 new MemberName (name, new TypeArguments (loc, t_args), loc), parameters, loc);
2013 if (parameters.Count > 0)
2014 a_type.SetParameterInfo (null);
2016 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC,
2017 new Parameters (ctor_params), null, loc);
2018 c.OptAttributes = a_type.GetDebuggerHiddenAttribute ();
2019 c.Block = new ToplevelBlock (c.Parameters, loc);
2022 // Create fields and contructor body with field initialization
2025 for (int i = 0; i < parameters.Count; ++i) {
2026 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
2028 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
2029 "<" + p.Name + ">", null, p.Location);
2031 if (!a_type.AddField (f)) {
2033 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
2038 c.Block.AddStatement (new StatementExpression (
2039 new Assign (new MemberAccess (new This (p.Location), f.Name),
2040 c.Block.GetParameterReference (p.Name, p.Location))));
2042 ToplevelBlock get_block = new ToplevelBlock (p.Location);
2043 get_block.AddStatement (new Return (
2044 new MemberAccess (new This (p.Location), f.Name), p.Location));
2045 Accessor get_accessor = new Accessor (get_block, 0, null, p.Location);
2046 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC, false,
2047 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
2048 a_type.AddProperty (prop);
2054 a_type.AddConstructor (c);
2058 public new static void Reset ()
2063 protected override bool AddToContainer (MemberCore symbol, string name)
2065 MemberCore mc = (MemberCore) defined_names [name];
2068 defined_names.Add (name, symbol);
2072 Report.SymbolRelatedToPreviousError (mc);
2076 void DefineOverrides ()
2078 Location loc = Location;
2080 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
2081 Modifiers.PUBLIC | Modifiers.OVERRIDE, false, new MemberName ("Equals", loc),
2082 new Parameters (new Parameter (TypeManager.system_object_expr, "obj", 0, null, loc)),
2083 GetDebuggerHiddenAttribute ());
2085 Method tostring = new Method (this, null, TypeManager.system_string_expr,
2086 Modifiers.PUBLIC | Modifiers.OVERRIDE, false, new MemberName ("ToString", loc),
2087 Mono.CSharp.Parameters.EmptyReadOnlyParameters, GetDebuggerHiddenAttribute ());
2089 ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
2090 TypeExpr current_type;
2092 current_type = new ConstructedType (TypeBuilder, TypeParameters, loc);
2094 current_type = new TypeExpression (TypeBuilder, loc);
2096 equals_block.AddVariable (current_type, "other", loc);
2097 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
2099 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
2100 new SimpleName ("System", loc), "Collections", loc), "Generic", loc);
2102 Expression rs_equals = null;
2103 Expression string_concat = new StringConstant ("<empty type>", loc);
2104 Expression rs_hashcode = new IntConstant (-2128831035, loc);
2105 for (int i = 0; i < parameters.Count; ++i) {
2106 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
2107 Field f = (Field) Fields [i];
2109 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
2110 system_collections_generic, "EqualityComparer",
2111 new TypeArguments (loc, new SimpleName (TypeParameters [i].Name, loc)), loc),
2114 ArrayList arguments_equal = new ArrayList (2);
2115 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
2116 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
2118 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
2119 "Equals", loc), arguments_equal);
2121 ArrayList arguments_hashcode = new ArrayList (1);
2122 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
2123 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
2124 "GetHashCode", loc), arguments_hashcode);
2126 IntConstant FNV_prime = new IntConstant (16777619, loc);
2127 rs_hashcode = new Binary (Binary.Operator.Multiply,
2128 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
2131 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
2132 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
2133 new Invocation (new MemberAccess (
2134 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
2135 new StringConstant ("<null>", loc));
2137 if (rs_equals == null) {
2138 rs_equals = field_equal;
2139 string_concat = new Binary (Binary.Operator.Addition,
2140 new StringConstant (p.Name + " = ", loc),
2146 // Implementation of ToString () body using string concatenation
2148 string_concat = new Binary (Binary.Operator.Addition,
2149 new Binary (Binary.Operator.Addition,
2151 new StringConstant (", " + p.Name + " = ", loc)),
2154 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
2158 // Equals (object obj) override
2160 equals_block.AddStatement (new StatementExpression (
2161 new Assign (other_variable,
2162 new As (equals_block.GetParameterReference ("obj", loc),
2163 current_type, loc), loc)));
2165 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
2166 if (rs_equals != null)
2167 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
2168 equals_block.AddStatement (new Return (equals_test, loc));
2170 equals.Block = equals_block;
2171 equals.ResolveMembers ();
2175 // GetHashCode () override
2177 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
2178 Modifiers.PUBLIC | Modifiers.OVERRIDE, false, new MemberName ("GetHashCode", loc),
2179 Mono.CSharp.Parameters.EmptyReadOnlyParameters, GetDebuggerHiddenAttribute ());
2182 // Modified FNV with good avalanche behavior and uniform
2183 // distribution with larger hash sizes.
2185 // const int FNV_prime = 16777619;
2186 // int hash = (int) 2166136261;
2187 // foreach (int d in data)
2188 // hash = (hash ^ d) * FNV_prime;
2189 // hash += hash << 13;
2190 // hash ^= hash >> 7;
2191 // hash += hash << 3;
2192 // hash ^= hash >> 17;
2193 // hash += hash << 5;
2195 ToplevelBlock hashcode_block = new ToplevelBlock (loc);
2196 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
2197 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
2198 hashcode_block.AddStatement (new StatementExpression (
2199 new Assign (hash_variable, rs_hashcode)));
2201 hashcode_block.AddStatement (new StatementExpression (
2202 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2203 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
2204 hashcode_block.AddStatement (new StatementExpression (
2205 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2206 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
2207 hashcode_block.AddStatement (new StatementExpression (
2208 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2209 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
2210 hashcode_block.AddStatement (new StatementExpression (
2211 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2212 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
2213 hashcode_block.AddStatement (new StatementExpression (
2214 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2215 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
2217 hashcode_block.AddStatement (new Return (hash_variable, loc));
2218 hashcode.Block = hashcode_block;
2219 hashcode.ResolveMembers ();
2220 AddMethod (hashcode);
2223 // ToString () override
2226 ToplevelBlock tostring_block = new ToplevelBlock (loc);
2227 tostring_block.AddStatement (new Return (string_concat, loc));
2228 tostring.Block = tostring_block;
2229 tostring.ResolveMembers ();
2230 AddMethod (tostring);
2233 public override bool DefineMembers ()
2237 return base.DefineMembers ();
2240 Attributes GetDebuggerHiddenAttribute ()
2242 return new Attributes (new Attribute (null, null,
2243 "System.Diagnostics.DebuggerHiddenAttribute", null, Location, false));
2246 public override string GetSignatureForError ()
2248 return SignatureForError;
2251 public ArrayList Parameters {