2 // anonymous.cs: Support for anonymous methods
5 // Miguel de Icaza (miguel@ximain.com)
7 // (C) 2003, 2004 Novell, Inc.
9 // TODO: Ideally, we should have the helper classes emited as a hierarchy to map
10 // their nesting, and have the visibility set to private, instead of NestedAssembly
17 using System.Collections;
18 using System.Reflection;
19 using System.Reflection.Emit;
21 namespace Mono.CSharp {
23 public abstract class CompilerGeneratedClass : Class
25 GenericMethod generic_method;
26 static int next_index = 0;
28 private static MemberName MakeProxyName (GenericMethod generic, Location loc)
30 string name = MakeName ("CompilerGenerated");
31 if (generic != null) {
32 TypeArguments args = new TypeArguments (loc);
33 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
34 args.Add (new SimpleName (tparam.Name, loc));
35 return new MemberName (name, args, loc);
37 return new MemberName (name, loc);
40 public static string MakeName (string prefix)
42 return "<>c__" + prefix + next_index++;
45 protected CompilerGeneratedClass (DeclSpace parent, GenericMethod generic,
46 int mod, Location loc)
47 : base (parent.NamespaceEntry, parent,
48 MakeProxyName (generic, loc), mod | Modifiers.COMPILER_GENERATED, null)
50 this.generic_method = generic;
52 if (generic != null) {
53 ArrayList list = new ArrayList ();
54 foreach (TypeParameter tparam in generic.TypeParameters) {
55 if (tparam.Constraints != null)
56 list.Add (tparam.Constraints.Clone ());
58 SetParameterInfo (list);
61 parent.PartialContainer.AddCompilerGeneratedClass (this);
64 protected override bool DefineNestedTypes ()
66 RootContext.RegisterCompilerGeneratedType (TypeBuilder);
67 return base.DefineNestedTypes ();
70 protected override bool DoDefineMembers ()
72 members_defined = true;
74 if (!base.DoDefineMembers ())
77 if (CompilerGenerated != null) {
78 foreach (CompilerGeneratedClass c in CompilerGenerated) {
79 if (!c.DefineMembers ())
80 throw new InternalErrorException ();
87 protected override bool DoResolveMembers ()
89 if (CompilerGenerated != null) {
90 foreach (CompilerGeneratedClass c in CompilerGenerated) {
91 if (!c.ResolveMembers ())
96 return base.DoResolveMembers ();
99 public GenericMethod GenericMethod {
100 get { return generic_method; }
103 public Parameters InflateParameters (Parameters ps)
105 if (generic_method == null)
112 Parameter[] inflated_params = new Parameter [n];
113 Type[] inflated_types = new Type [n];
115 for (int i = 0; i < n; ++i) {
116 Parameter p = ps [i];
117 Type it = InflateType (p.ExternalType ()).ResolveAsTypeTerminal (this, false).Type;
118 inflated_types [i] = it;
119 inflated_params [i] = new Parameter (it, p.Name, p.ModFlags, p.OptAttributes, p.Location);
121 return new Parameters (inflated_params, inflated_types);
124 public TypeExpr InflateType (Type it)
127 if (generic_method == null)
128 return new TypeExpression (it, Location);
130 if (it.IsGenericParameter && (it.DeclaringMethod != null)) {
131 int pos = it.GenericParameterPosition;
132 it = CurrentTypeParameters [pos].Type;
133 } else if (it.IsGenericType) {
134 Type[] args = it.GetGenericArguments ();
136 TypeArguments inflated = new TypeArguments (Location);
137 foreach (Type t in args)
138 inflated.Add (InflateType (t));
140 return new ConstructedType (it, inflated, Location);
141 } else if (it.IsArray) {
142 TypeExpr et_expr = InflateType (it.GetElementType ());
143 int rank = it.GetArrayRank ();
145 Type et = et_expr.ResolveAsTypeTerminal (this, false).Type;
146 it = et.MakeArrayType (rank);
150 return new TypeExpression (it, Location);
153 public Field CaptureVariable (string name, TypeExpr type)
156 throw new InternalErrorException ("Helper class already defined!");
158 throw new ArgumentNullException ();
160 return new CapturedVariableField (this, name, type);
163 bool members_defined;
165 internal void CheckMembersDefined ()
168 throw new InternalErrorException ("Helper class already defined!");
171 protected class CapturedVariableField : Field
173 public CapturedVariableField (CompilerGeneratedClass helper, string name,
175 : base (helper, type, Modifiers.INTERNAL, name, null, helper.Location)
177 helper.AddField (this);
182 public class ScopeInfo : CompilerGeneratedClass
184 protected readonly RootScopeInfo RootScope;
185 new public readonly DeclSpace Parent;
186 public readonly int ID = ++next_id;
187 public Block ScopeBlock;
191 public static ScopeInfo CreateScope (Block block)
193 ToplevelBlock toplevel = block.Toplevel;
194 AnonymousContainer ac = toplevel.AnonymousContainer;
196 Report.Debug (128, "CREATE SCOPE", block, block.ScopeInfo, toplevel, ac);
199 return new ScopeInfo (block, toplevel.RootScope.Parent,
200 toplevel.RootScope.GenericMethod);
202 Report.Debug (128, "CREATE SCOPE #1", ac, ac.Host, ac.Scope, ac.Block,
203 ac.Container, ac.ContainerAnonymousMethod,
207 ScopeInfo parent = null;
209 for (b = ac.Block; b != null; b = b.Parent) {
210 if (b.ScopeInfo != null) {
211 parent = b.ScopeInfo;
216 Report.Debug (128, "CREATE SCOPE #2", parent);
218 ScopeInfo new_scope = new ScopeInfo (block, parent, null);
220 Report.Debug (128, "CREATE SCOPE #3", new_scope);
225 private static int default_modflags (DeclSpace parent)
227 return parent is CompilerGeneratedClass ? Modifiers.PUBLIC : Modifiers.PRIVATE;
230 protected ScopeInfo (Block block, DeclSpace parent, GenericMethod generic)
231 : base (parent, generic, default_modflags (parent), block.StartLocation)
234 RootScope = block.Toplevel.RootScope;
237 Report.Debug (128, "NEW SCOPE", this, block,
238 block.Parent, block.Toplevel);
240 RootScope.AddScope (this);
243 protected ScopeInfo (ToplevelBlock toplevel, DeclSpace parent,
244 GenericMethod generic, Location loc)
245 : base (parent, generic, default_modflags (parent), loc)
248 RootScope = (RootScopeInfo) this;
249 ScopeBlock = toplevel;
251 Report.Debug (128, "NEW ROOT SCOPE", this, toplevel, loc);
254 protected ScopeInitializer scope_initializer;
256 Hashtable locals = new Hashtable ();
257 Hashtable captured_scopes = new Hashtable ();
258 Hashtable captured_params;
260 protected CapturedScope[] CapturedScopes {
262 CapturedScope[] list = new CapturedScope [captured_scopes.Count];
263 captured_scopes.Values.CopyTo (list, 0);
268 protected CapturedVariable GetCapturedScope (ScopeInfo scope)
270 return (CapturedVariable) captured_scopes [scope];
273 protected void EmitScopeInstance (EmitContext ec)
275 if (scope_initializer == null) {
277 // This is needed if someone overwrites the Emit method
278 // of Statement and manually calls Block.Emit without
279 // this snippet first:
281 // ec.EmitScopeInitFromBlock (The_Block);
282 // The_Block.Emit (ec);
284 throw new InternalErrorException ();
287 scope_initializer.Emit (ec);
290 public ExpressionStatement GetScopeInitializer (EmitContext ec)
292 Report.Debug (128, "GET SCOPE INITIALIZER",
293 this, GetType (), scope_initializer, ScopeBlock);
295 if (scope_initializer == null) {
296 scope_initializer = CreateScopeInitializer ();
297 if (scope_initializer.Resolve (ec) == null)
298 throw new InternalErrorException ();
301 return scope_initializer;
304 public Type GetScopeType (EmitContext ec)
309 TypeArguments targs = new TypeArguments (Location);
311 if (ec.DeclContainer.Parent.IsGeneric)
312 foreach (TypeParameter t in ec.DeclContainer.Parent.TypeParameters)
313 targs.Add (new TypeParameterExpr (t, Location));
314 if (ec.DeclContainer.IsGeneric)
315 foreach (TypeParameter t in ec.DeclContainer.CurrentTypeParameters)
316 targs.Add (new TypeParameterExpr (t, Location));
318 Report.Debug (128, "GET SCOPE TYPE", this, TypeBuilder, targs,
319 ec.DeclContainer, ec.DeclContainer.GetType (),
320 ec.DeclContainer.Parent.Name);
322 TypeExpr te = new ConstructedType (TypeBuilder, targs, Location);
323 te = te.ResolveAsTypeTerminal (ec, false);
324 if ((te == null) || (te.Type == null))
329 protected override bool DoDefineMembers ()
331 Report.Debug (64, "SCOPE INFO DEFINE MEMBERS", this, GetType (), IsGeneric,
332 Parent.IsGeneric, GenericMethod);
334 foreach (CapturedScope child in CapturedScopes) {
335 if (!child.DefineMembers ())
339 return base.DoDefineMembers ();
342 protected override bool DoResolveMembers ()
344 Report.Debug (64, "SCOPE INFO RESOLVE MEMBERS", this, GetType (), IsGeneric,
345 Parent.IsGeneric, GenericMethod);
347 return base.DoResolveMembers ();
350 public Variable CaptureScope (ScopeInfo child)
352 CheckMembersDefined ();
353 Report.Debug (128, "CAPTURE SCOPE", this, GetType (), child, child.GetType ());
355 throw new InternalErrorException ();
356 CapturedScope captured = (CapturedScope) captured_scopes [child];
357 if (captured == null) {
358 captured = new CapturedScope (this, child);
359 captured_scopes.Add (child, captured);
364 public Variable AddLocal (LocalInfo local)
366 Report.Debug (128, "CAPTURE LOCAL", this, local);
367 Variable var = (Variable) locals [local];
369 var = new CapturedLocal (this, local);
370 locals.Add (local, var);
371 local.IsCaptured = true;
376 public Variable GetCapturedVariable (LocalInfo local)
378 return (Variable) locals [local];
381 public bool HostsParameters {
382 get { return captured_params != null; }
385 public Variable GetCapturedParameter (Parameter par)
387 if (captured_params != null)
388 return (Variable) captured_params [par];
393 public bool IsParameterCaptured (string name)
395 if (captured_params != null)
396 return captured_params [name] != null;
400 public Variable AddParameter (Parameter par, int idx)
402 if (captured_params == null)
403 captured_params = new Hashtable ();
405 Variable var = (Variable) captured_params [par];
407 var = new CapturedParameter (this, par, idx);
408 captured_params.Add (par, var);
409 par.IsCaptured = true;
415 protected string MakeFieldName (string local_name)
417 return "<" + ID + ":" + local_name + ">";
420 protected virtual ScopeInitializer CreateScopeInitializer ()
422 return new ScopeInitializer (this);
425 protected abstract class CapturedVariable : Variable
427 public readonly ScopeInfo Scope;
428 public readonly string Name;
430 public FieldExpr FieldInstance;
431 protected Field field;
433 protected CapturedVariable (ScopeInfo scope, string name)
439 protected CapturedVariable (ScopeInfo scope, string name, Type type)
442 this.field = scope.CaptureVariable (
443 scope.MakeFieldName (name), scope.RootScope.InflateType (type));
447 get { return field; }
450 public override Type Type {
451 get { return Field.MemberType; }
454 public override bool HasInstance {
458 public override bool NeedsTemporary {
462 protected FieldInfo GetField (EmitContext ec)
464 if ((ec.CurrentBlock != null) &&
465 (ec.CurrentBlock.Toplevel != Scope.ScopeBlock.Toplevel))
466 return Field.FieldBuilder;
468 return FieldInstance.FieldInfo;
471 public override void EmitInstance (EmitContext ec)
473 if ((ec.CurrentAnonymousMethod != null) &&
474 (ec.CurrentAnonymousMethod.Scope == Scope)) {
475 ec.ig.Emit (OpCodes.Ldarg_0);
479 Scope.EmitScopeInstance (ec);
482 public override void Emit (EmitContext ec)
484 ec.ig.Emit (OpCodes.Ldfld, GetField (ec));
487 public override void EmitAssign (EmitContext ec)
489 ec.ig.Emit (OpCodes.Stfld, GetField (ec));
492 public override void EmitAddressOf (EmitContext ec)
494 ec.ig.Emit (OpCodes.Ldflda, GetField (ec));
498 protected class CapturedParameter : CapturedVariable {
499 public readonly Parameter Parameter;
500 public readonly int Idx;
502 public CapturedParameter (ScopeInfo scope, Parameter par, int idx)
503 : base (scope, par.Name, par.ParameterType)
505 this.Parameter = par;
509 public override string ToString ()
511 return String.Format ("{0} ({1}:{2}:{3})", GetType (), Field,
512 Parameter.Name, Idx);
516 protected class CapturedLocal : CapturedVariable {
517 public readonly LocalInfo Local;
519 public CapturedLocal (ScopeInfo scope, LocalInfo local)
520 : base (scope, local.Name, local.VariableType)
525 public override string ToString ()
527 return String.Format ("{0} ({1}:{2})", GetType (), Field,
532 protected class CapturedThis : CapturedVariable {
533 public CapturedThis (RootScopeInfo host)
534 : base (host, "<>THIS", host.ParentType)
538 protected class CapturedScope : CapturedVariable {
539 public readonly ScopeInfo ChildScope;
541 public CapturedScope (ScopeInfo root, ScopeInfo child)
542 : base (root, "scope" + child.ID)
544 this.ChildScope = child;
547 public bool DefineMembers ()
549 Type type = ChildScope.IsGeneric ?
550 ChildScope.CurrentType : ChildScope.TypeBuilder;
551 Report.Debug (128, "CAPTURED SCOPE DEFINE MEMBERS", this, Scope,
552 ChildScope, Name, type);
554 throw new InternalErrorException ();
555 field = Scope.CaptureVariable (
556 Scope.MakeFieldName (Name), Scope.InflateType (type));
560 public override string ToString ()
562 return String.Format ("CapturedScope ({1} captured in {0})",
567 static void DoPath (StringBuilder sb, ScopeInfo start)
569 sb.Append ((start.ID).ToString ());
572 public override string ToString ()
574 StringBuilder sb = new StringBuilder ();
580 return sb.ToString ();
583 protected class ScopeInitializer : ExpressionStatement
586 CapturedVariable captured_scope;
587 LocalBuilder scope_instance;
588 ConstructorInfo scope_ctor;
592 public ScopeInitializer (ScopeInfo scope)
595 this.loc = scope.Location;
596 eclass = ExprClass.Value;
599 public ScopeInfo Scope {
600 get { return scope; }
603 public override Expression DoResolve (EmitContext ec)
605 if (scope_ctor != null)
608 Report.Debug (64, "RESOLVE SCOPE INITIALIZER BASE", this, Scope,
609 ec, ec.CurrentBlock);
611 type = Scope.GetScopeType (ec);
613 throw new InternalErrorException ();
615 if (!DoResolveInternal (ec))
616 throw new InternalErrorException ();
621 protected virtual bool DoResolveInternal (EmitContext ec)
623 MethodGroupExpr mg = (MethodGroupExpr) Expression.MemberLookupFinal (
624 ec, ec.ContainerType, type, ".ctor", MemberTypes.Constructor,
625 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
627 throw new InternalErrorException ();
629 scope_ctor = (ConstructorInfo) mg.Methods [0];
631 Report.Debug (128, "RESOLVE THE INIT", this, Scope, Scope.RootScope,
632 Scope.RootScope.GetType ());
634 ScopeInfo host = Scope.RootScope;
635 if ((Scope != host) && (Scope.RootScope is IteratorHost)) {
636 captured_scope = host.GetCapturedScope (Scope);
637 Type root = host.GetScopeType (ec);
638 FieldExpr fe = (FieldExpr) Expression.MemberLookup (
639 type, root, captured_scope.Field.Name, loc);
641 throw new InternalErrorException ();
643 fe.InstanceExpression = this;
644 captured_scope.FieldInstance = fe;
646 Report.Debug (128, "RESOLVE THE INIT #1", this,
649 scope_instance = ec.ig.DeclareLocal (type);
651 foreach (CapturedLocal local in Scope.locals.Values) {
652 FieldExpr fe = (FieldExpr) Expression.MemberLookup (
653 ec.ContainerType, type, local.Field.Name, loc);
654 Report.Debug (64, "RESOLVE SCOPE INITIALIZER #2", this, Scope,
655 Scope, ec, ec.ContainerType, type,
656 local.Field, local.Field.Name, loc, fe);
658 throw new InternalErrorException ();
660 fe.InstanceExpression = this;
661 local.FieldInstance = fe;
664 if (Scope.HostsParameters) {
665 foreach (CapturedParameter cp in Scope.captured_params.Values) {
666 FieldExpr fe = (FieldExpr) Expression.MemberLookup (
667 ec.ContainerType, type, cp.Field.Name, loc);
669 throw new InternalErrorException ();
671 fe.InstanceExpression = this;
672 cp.FieldInstance = fe;
676 foreach (CapturedScope scope in Scope.CapturedScopes) {
677 FieldExpr fe = (FieldExpr) Expression.MemberLookup (
678 ec.ContainerType, type, scope.Field.Name, loc);
679 Report.Debug (64, "RESOLVE SCOPE INITIALIZER #3", this, Scope,
680 scope, ec, ec.ContainerType, type,
681 scope.Field, scope.Field.Name, loc, fe);
683 throw new InternalErrorException ();
685 fe.InstanceExpression = this;
686 scope.FieldInstance = fe;
692 protected virtual void EmitParameterReference (EmitContext ec,
693 CapturedParameter cp)
695 int extra = ec.MethodIsStatic ? 0 : 1;
696 ParameterReference.EmitLdArg (ec.ig, cp.Idx + extra);
702 protected virtual void DoEmit (EmitContext ec)
704 if ((ec.CurrentBlock != null) &&
705 (ec.CurrentBlock.Toplevel != Scope.ScopeBlock.Toplevel)) {
706 ec.ig.Emit (OpCodes.Ldarg_0);
708 if (ec.CurrentAnonymousMethod != null) {
709 ScopeInfo host = ec.CurrentAnonymousMethod.Scope;
710 Variable captured = host.GetCapturedScope (scope);
711 Report.Debug (128, "EMIT SCOPE INSTANCE #2",
712 ec.CurrentAnonymousMethod, host,
714 if (captured != null)
717 } else if (scope_instance != null)
718 ec.ig.Emit (OpCodes.Ldloc, scope_instance);
720 Report.Debug (128, "DO EMIT", this, Scope, ec,
721 scope_instance, captured_scope);
722 captured_scope.EmitInstance (ec);
723 captured_scope.Emit (ec);
727 protected void DoEmitInstance (EmitContext ec)
729 Report.Debug (128, "DO EMIT INSTANCE", this, Scope, ec,
730 scope_instance, captured_scope);
732 if (scope_instance != null)
733 ec.ig.Emit (OpCodes.Ldloc, scope_instance);
735 captured_scope.EmitInstance (ec);
738 protected virtual void EmitScopeConstructor (EmitContext ec)
740 ec.ig.Emit (OpCodes.Newobj, scope_ctor);
743 public override void Emit (EmitContext ec)
746 throw new InternalErrorException (
747 "Scope {0} not initialized yet", scope);
752 public override void EmitStatement (EmitContext ec)
757 DoEmitStatement (ec);
761 protected virtual void DoEmitStatement (EmitContext ec)
763 Report.Debug (128, "EMIT SCOPE INITIALIZER STATEMENT", this, id,
764 Scope, scope_instance, ec);
766 ec.ig.Emit (OpCodes.Nop);
767 ec.ig.Emit (OpCodes.Ldc_I4, id);
768 ec.ig.Emit (OpCodes.Pop);
769 ec.ig.Emit (OpCodes.Nop);
771 if (scope_instance == null)
772 ec.ig.Emit (OpCodes.Ldarg_0);
773 EmitScopeConstructor (ec);
774 if (scope_instance != null)
775 ec.ig.Emit (OpCodes.Stloc, scope_instance);
777 captured_scope.EmitAssign (ec);
779 if (Scope.HostsParameters) {
780 foreach (CapturedParameter cp in Scope.captured_params.Values) {
781 Report.Debug (128, "EMIT SCOPE INIT #6", this,
782 ec, ec.IsStatic, Scope, cp, cp.Field.Name);
784 EmitParameterReference (ec, cp);
785 ec.ig.Emit (OpCodes.Stfld, cp.FieldInstance.FieldInfo);
789 if (Scope is IteratorHost)
792 foreach (CapturedScope scope in Scope.CapturedScopes) {
793 ScopeInfo child = scope.ChildScope;
795 Report.Debug (128, "EMIT SCOPE INIT #5", this, Scope,
796 scope.Scope, scope.ChildScope);
798 ExpressionStatement init = child.GetScopeInitializer (ec);
799 init.EmitStatement (ec);
802 scope.ChildScope.EmitScopeInstance (ec);
803 scope.EmitAssign (ec);
809 public class RootScopeInfo : ScopeInfo
811 public RootScopeInfo (ToplevelBlock toplevel, DeclSpace parent,
812 GenericMethod generic, Location loc)
813 : base (toplevel, parent, generic, loc)
815 scopes = new ArrayList ();
818 TypeExpr parent_type;
819 CapturedVariableField parent_link;
820 CapturedThis this_variable;
821 protected ArrayList scopes;
823 public virtual bool IsIterator {
824 get { return false; }
827 public RootScopeInfo ParentHost {
828 get { return Parent.PartialContainer as RootScopeInfo; }
831 public Type ParentType {
832 get { return parent_type.Type; }
835 public Field ParentLink {
836 get { return parent_link; }
839 protected CapturedThis THIS {
840 get { return this_variable; }
843 public Variable CaptureThis ()
845 if (ParentHost != null)
846 return ParentHost.CaptureThis ();
848 CheckMembersDefined ();
849 if (this_variable == null)
850 this_variable = new CapturedThis (this);
851 return this_variable;
854 public void AddScope (ScopeInfo scope)
860 public void LinkScopes ()
862 Report.Debug (128, "LINK SCOPES", this, linked, scopes);
868 if (ParentHost != null)
869 ParentHost.LinkScopes ();
871 foreach (ScopeInfo si in scopes) {
873 throw new InternalErrorException ();
874 if (si.DefineType () == null)
875 throw new InternalErrorException ();
876 if (!si.ResolveType ())
877 throw new InternalErrorException ();
880 foreach (ScopeInfo si in scopes) {
881 if (!si.ResolveMembers ())
882 throw new InternalErrorException ();
883 if (!si.DefineMembers ())
884 throw new InternalErrorException ();
888 protected override ScopeInitializer CreateScopeInitializer ()
890 return new RootScopeInitializer (this);
893 protected override bool DefineNestedTypes ()
895 if (Parent.IsGeneric) {
896 parent_type = new ConstructedType (
897 Parent.TypeBuilder, Parent.TypeParameters, Location);
898 parent_type = parent_type.ResolveAsTypeTerminal (this, false);
899 if ((parent_type == null) || (parent_type.Type == null))
902 parent_type = new TypeExpression (Parent.TypeBuilder, Location);
905 CompilerGeneratedClass parent = Parent.PartialContainer as CompilerGeneratedClass;
907 parent_link = new CapturedVariableField (this, "<>parent", parent_type);
909 return base.DefineNestedTypes ();
912 protected override bool DoDefineMembers ()
914 ArrayList args = new ArrayList ();
915 if (this is IteratorHost)
916 args.Add (new Parameter (
917 TypeManager.int32_type, "$PC", Parameter.Modifier.NONE,
921 if (Parent is CompilerGeneratedClass)
922 pfield = parent_link;
924 pfield = this_variable != null ? this_variable.Field : null;
926 args.Add (new Parameter (
927 pfield.MemberType, "parent", Parameter.Modifier.NONE,
930 Parameter[] ctor_params = new Parameter [args.Count];
931 args.CopyTo (ctor_params, 0);
932 Constructor ctor = new Constructor (
933 this, MemberName.Name, Modifiers.PUBLIC,
934 new Parameters (ctor_params),
935 new GeneratedBaseInitializer (Location),
937 AddConstructor (ctor);
939 ctor.Block = new ToplevelBlock (null, Location);
940 ctor.Block.AddStatement (new TheCtor (this));
942 return base.DoDefineMembers ();
945 protected virtual void EmitScopeConstructor (EmitContext ec)
947 int pos = (this is IteratorHost) ? 2 : 1;
950 if (Parent is CompilerGeneratedClass)
951 pfield = parent_link;
953 pfield = this_variable != null ? this_variable.Field : null;
955 if (pfield != null) {
956 ec.ig.Emit (OpCodes.Ldarg_0);
957 ec.ig.Emit (OpCodes.Ldarg, pos);
958 ec.ig.Emit (OpCodes.Stfld, pfield.FieldBuilder);
963 protected class TheCtor : Statement
967 public TheCtor (RootScopeInfo host)
972 public override bool Resolve (EmitContext ec)
977 protected override void DoEmit (EmitContext ec)
979 host.EmitScopeConstructor (ec);
983 protected class RootScopeInitializer : ScopeInitializer
987 public RootScopeInitializer (RootScopeInfo host)
993 public RootScopeInfo Host {
997 protected override bool DoResolveInternal (EmitContext ec)
999 Report.Debug (64, "RESOLVE ANONYMOUS METHOD HOST INITIALIZER",
1000 this, Host, Host.ParentType, loc);
1002 if (Host.THIS != null) {
1003 FieldExpr fe = (FieldExpr) Expression.MemberLookup (
1004 ec.ContainerType, type, Host.THIS.Field.Name, loc);
1006 throw new InternalErrorException ();
1008 fe.InstanceExpression = this;
1009 Host.THIS.FieldInstance = fe;
1012 return base.DoResolveInternal (ec);
1015 protected virtual bool IsGetEnumerator {
1016 get { return false; }
1019 protected override void EmitScopeConstructor (EmitContext ec)
1021 if (host.THIS != null) {
1022 ec.ig.Emit (OpCodes.Ldarg_0);
1023 if (IsGetEnumerator)
1024 ec.ig.Emit (OpCodes.Ldfld, host.THIS.Field.FieldBuilder);
1025 else if (host.THIS.Type.IsValueType)
1026 Expression.LoadFromPtr (ec.ig, host.THIS.Type);
1027 } else if (host.ParentLink != null)
1028 ec.ig.Emit (OpCodes.Ldarg_0);
1030 base.EmitScopeConstructor (ec);
1036 public interface IAnonymousContainer
1042 GenericMethod GenericMethod {
1046 RootScopeInfo RootScope {
1055 public interface IAnonymousHost
1058 // Invoked if a yield statement is found in the body
1063 // Invoked if an anonymous method is found in the body
1065 void AddAnonymousMethod (AnonymousMethodExpression anonymous);
1068 public class AnonymousMethodExpression : Expression, IAnonymousContainer, IAnonymousHost
1070 public readonly AnonymousMethodExpression Parent;
1071 public readonly TypeContainer Host;
1072 public Parameters Parameters;
1074 public ToplevelBlock Block;
1075 protected AnonymousMethod anonymous;
1077 protected Block container;
1078 protected readonly GenericMethod generic;
1080 public Block Container {
1081 get { return container; }
1084 public GenericMethod GenericMethod {
1085 get { return generic; }
1088 public AnonymousMethod AnonymousMethod {
1089 get { return anonymous; }
1092 public RootScopeInfo RootScope {
1093 get { return root_scope; }
1096 public AnonymousMethodExpression (AnonymousMethodExpression parent,
1097 GenericMethod generic, TypeContainer host,
1098 Parameters parameters, Block container,
1101 this.Parent = parent;
1102 this.generic = parent != null ? null : generic;
1104 this.Parameters = parameters;
1105 this.container = container;
1108 Report.Debug (64, "NEW ANONYMOUS METHOD EXPRESSION", this, parent, host,
1112 parent.AddAnonymousMethod (this);
1116 RootScopeInfo root_scope;
1118 static int next_index;
1120 void IAnonymousHost.SetYields ()
1122 throw new InvalidOperationException ();
1125 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
1127 if (children == null)
1128 children = new ArrayList ();
1129 children.Add (anonymous);
1132 public bool CreateAnonymousHelpers ()
1134 Report.Debug (64, "ANONYMOUS METHOD EXPRESSION CREATE ROOT SCOPE",
1135 this, Host, container, loc);
1137 if (container != null)
1138 root_scope = container.Toplevel.CreateRootScope (Host);
1140 if (children != null) {
1141 foreach (AnonymousMethodExpression child in children) {
1142 if (!child.CreateAnonymousHelpers ())
1150 public override string ExprClassName {
1152 return "anonymous method";
1156 void Error_ParameterMismatch (Type t)
1158 Report.Error (1661, loc, "Anonymous method could not be converted to delegate `" +
1159 "{0}' since there is a parameter mismatch",
1160 TypeManager.CSharpName (t));
1163 public virtual bool ImplicitStandardConversionExists (Type delegate_type)
1165 if (Parameters == null)
1168 MethodGroupExpr invoke_mg = Delegate.GetInvokeMethod (
1169 Host.TypeBuilder, delegate_type, loc);
1170 MethodInfo invoke_mb = (MethodInfo) invoke_mg.Methods [0];
1171 ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
1173 if (Parameters.Count != invoke_pd.Count)
1176 for (int i = 0; i < Parameters.Count; ++i) {
1177 if (invoke_pd.ParameterType (i) != Parameters.ParameterType (i))
1183 protected Expression CompatibleChecks (EmitContext ec, Type delegate_type)
1185 if (!ec.IsAnonymousMethodAllowed) {
1186 Report.Error (1706, loc,
1187 "Anonymous methods are not allowed in the " +
1188 "attribute declaration");
1192 if (!TypeManager.IsDelegateType (delegate_type)){
1193 Report.Error (1660, loc,
1194 "Cannot convert anonymous method block to type " +
1195 "`{0}' because it is not a delegate type",
1196 TypeManager.CSharpName (delegate_type));
1202 protected bool VerifyExplicitParameterCompatibility (Type delegate_type, ParameterData invoke_pd)
1204 if (Parameters.Count != invoke_pd.Count) {
1205 Report.SymbolRelatedToPreviousError (delegate_type);
1206 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
1207 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
1208 Error_ParameterMismatch (delegate_type);
1212 for (int i = 0; i < Parameters.Count; ++i) {
1213 Parameter.Modifier p_mod = invoke_pd.ParameterModifier (i);
1214 if (Parameters.ParameterModifier (i) != p_mod && p_mod != Parameter.Modifier.PARAMS) {
1215 if (p_mod == Parameter.Modifier.NONE)
1216 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
1217 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.ParameterModifier (i)));
1219 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
1220 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
1221 Error_ParameterMismatch (delegate_type);
1225 // We assume that generic parameters are always inflated
1226 if (TypeManager.IsGenericParameter (invoke_pd.Types[i]))
1229 if (invoke_pd.ParameterType (i) != Parameters.ParameterType (i)) {
1230 Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
1232 TypeManager.CSharpName (Parameters.ParameterType (i)),
1233 TypeManager.CSharpName (invoke_pd.ParameterType (i)));
1234 Error_ParameterMismatch (delegate_type);
1242 // Returns true if this anonymous method can be implicitly
1243 // converted to the delegate type `delegate_type'
1245 public virtual Expression Compatible (EmitContext ec, Type delegate_type)
1247 if (anonymous != null)
1248 return anonymous.AnonymousDelegate;
1250 if (CompatibleChecks (ec, delegate_type) == null)
1255 // At this point its the first time we know the return type that is
1256 // needed for the anonymous method. We create the method here.
1259 MethodGroupExpr invoke_mg = Delegate.GetInvokeMethod (
1260 ec.ContainerType, delegate_type, loc);
1261 MethodInfo invoke_mb = (MethodInfo) invoke_mg.Methods [0];
1262 ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
1265 Type[] infered_arguments = null;
1266 if (TypeManager.IsGenericType (delegate_type)) {
1268 Type[] g_arguments = delegate_type.GetGenericArguments ();
1269 infered_arguments = new Type[g_arguments.Length];
1270 for (int i = 0; i < g_arguments.Length; ++i) {
1271 infered_arguments [i] = g_arguments[i];
1274 for (int i = 0; i < invoke_pd.Count; ++i) {
1275 if (!invoke_pd.Types[i].IsGenericParameter)
1278 infered_arguments [invoke_pd.Types[i].GenericParameterPosition] = Parameters.Types[i];
1282 int return_type_pos = -1;
1283 if (TypeManager.IsGenericParameter (invoke_mb.ReturnType)) {
1284 ec.InferReturnType = true;
1285 return_type_pos = invoke_mb.ReturnType.GenericParameterPosition;
1289 Parameters parameters;
1290 if (Parameters == null) {
1292 // We provide a set of inaccessible parameters
1294 Parameter [] fixedpars = new Parameter [invoke_pd.Count];
1296 for (int i = 0; i < invoke_pd.Count; i++) {
1297 Parameter.Modifier i_mod = invoke_pd.ParameterModifier (i);
1298 if ((i_mod & Parameter.Modifier.OUTMASK) != 0) {
1299 Report.Error (1688, loc, "Cannot convert anonymous " +
1300 "method block without a parameter list " +
1301 "to delegate type `{0}' because it has " +
1302 "one or more `out' parameters.",
1303 TypeManager.CSharpName (delegate_type));
1306 fixedpars [i] = new Parameter (
1307 invoke_pd.ParameterType (i), "+" + (++next_index),
1308 invoke_pd.ParameterModifier (i), null, loc);
1311 parameters = new Parameters (fixedpars);
1312 if (!parameters.Resolve (ec))
1315 if (!VerifyExplicitParameterCompatibility (delegate_type, invoke_pd))
1318 parameters = Parameters;
1322 // Second: the return type of the delegate must be compatible with
1323 // the anonymous type. Instead of doing a pass to examine the block
1324 // we satisfy the rule by setting the return type on the EmitContext
1325 // to be the delegate type return type.
1328 //MethodBuilder builder = method_data.MethodBuilder;
1329 //ILGenerator ig = builder.GetILGenerator ();
1331 Report.Debug (64, "COMPATIBLE", this, Parent, GenericMethod, Host,
1332 Container, Block, invoke_mb.ReturnType, delegate_type,
1333 TypeManager.IsGenericType (delegate_type), loc);
1335 anonymous = new AnonymousMethod (
1336 Parent != null ? Parent.AnonymousMethod : null, RootScope, Host,
1337 GenericMethod, parameters, Container, Block, invoke_mb.ReturnType,
1338 delegate_type, loc);
1340 if (!anonymous.Resolve (ec))
1344 if (return_type_pos != -1) {
1345 if (infered_arguments == null)
1346 infered_arguments = new Type [delegate_type.GetGenericArguments ().Length];
1348 infered_arguments [return_type_pos] = anonymous.ReturnType;
1351 if (infered_arguments != null & TypeManager.IsGenericType (delegate_type)) {
1352 anonymous.AnonymousDelegate.Type = delegate_type.GetGenericTypeDefinition ().MakeGenericType (infered_arguments);
1353 anonymous.DelegateType = anonymous.AnonymousDelegate.Type;
1356 return anonymous.AnonymousDelegate;
1359 public override Expression DoResolve (EmitContext ec)
1362 // Set class type, set type
1365 eclass = ExprClass.Value;
1368 // This hack means `The type is not accessible
1369 // anywhere', we depend on special conversion
1372 type = TypeManager.anonymous_method_type;
1374 if ((Parameters != null) && !Parameters.Resolve (ec))
1380 public override void Emit (EmitContext ec)
1382 // nothing, as we only exist to not do anything.
1385 public bool IsIterator {
1386 get { return false; }
1389 protected override void CloneTo (CloneContext clonectx, Expression t)
1391 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1393 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1394 target.container = clonectx.LookupBlock (Block);
1395 target.Parameters = Parameters.Clone ();
1399 public abstract class AnonymousContainer : IAnonymousContainer
1401 public readonly Location Location;
1403 public Parameters Parameters;
1406 // The block that makes up the body for the anonymous mehtod
1408 public readonly ToplevelBlock Block;
1410 public readonly int ModFlags;
1411 public Type ReturnType;
1412 public readonly DeclSpace Host;
1415 // The implicit method we create
1417 protected Method method;
1418 protected EmitContext aec;
1420 // The emit context for the anonymous method
1421 protected bool unreachable;
1422 protected readonly Block container;
1423 protected readonly GenericMethod generic;
1426 // Points to our container anonymous method if its present
1428 public readonly AnonymousContainer ContainerAnonymousMethod;
1430 protected AnonymousContainer (AnonymousContainer parent, DeclSpace host,
1431 GenericMethod generic, Parameters parameters,
1432 Block container, ToplevelBlock block,
1433 Type return_type, int mod, Location loc)
1435 this.ContainerAnonymousMethod = parent;
1436 this.ReturnType = return_type;
1437 this.ModFlags = mod;
1440 this.container = container;
1441 this.generic = parent != null ? null : generic;
1442 this.Parameters = parameters;
1444 this.Location = loc;
1446 block.AnonymousContainer = this;
1449 public Method Method {
1450 get { return method; }
1453 public abstract RootScopeInfo RootScope {
1457 public abstract ScopeInfo Scope {
1461 public abstract string GetSignatureForError ();
1463 public virtual bool ResolveNoDefine (EmitContext ec)
1465 Report.Debug (64, "RESOLVE ANONYMOUS METHOD", this, Location, ec,
1466 RootScope, Parameters, ec.IsStatic);
1468 if (ReturnType != null) {
1469 TypeExpr return_type_expr;
1470 if (RootScope != null)
1471 return_type_expr = RootScope.InflateType (ReturnType);
1473 return_type_expr = new TypeExpression (ReturnType, Location);
1474 return_type_expr = return_type_expr.ResolveAsTypeTerminal (ec, false);
1475 if ((return_type_expr == null) || (return_type_expr.Type == null))
1477 ReturnType = return_type_expr.Type;
1480 if (RootScope != null)
1481 Parameters = RootScope.InflateParameters (Parameters);
1483 aec = new EmitContext (
1484 ec.ResolveContext, ec.TypeContainer,
1485 RootScope != null ? RootScope : Host, Location, null, ReturnType,
1486 /* REVIEW */ (ec.InIterator ? Modifiers.METHOD_YIELDS : 0) |
1487 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1489 aec.CurrentAnonymousMethod = this;
1490 aec.IsFieldInitializer = ec.IsFieldInitializer;
1491 aec.IsStatic = ec.IsStatic;
1492 aec.InferReturnType = ec.InferReturnType;
1494 Report.Debug (64, "RESOLVE ANONYMOUS METHOD #1", this, Location, ec, aec,
1495 RootScope, Parameters, Block);
1498 if (!aec.ResolveTopBlock (ec, Block, Parameters, null, out unreachable))
1504 public virtual bool Resolve (EmitContext ec)
1506 if (!ResolveNoDefine (ec))
1509 Report.Debug (64, "RESOLVE ANONYMOUS METHOD #3", this, ec, aec, Block);
1511 if (aec.InferReturnType)
1512 ReturnType = aec.ReturnType;
1514 method = DoCreateMethodHost (ec);
1519 if (!method.ResolveMembers ())
1521 return method.Define ();
1524 protected abstract Method DoCreateMethodHost (EmitContext ec);
1526 public Block Container {
1527 get { return container; }
1530 public GenericMethod GenericMethod {
1531 get { return generic; }
1534 public abstract bool IsIterator {
1538 protected class AnonymousMethodMethod : Method
1540 public readonly AnonymousContainer AnonymousMethod;
1541 public readonly ScopeInfo Scope;
1543 public AnonymousMethodMethod (AnonymousContainer am, ScopeInfo scope,
1544 GenericMethod generic, TypeExpr return_type,
1545 int mod, MemberName name, Parameters parameters)
1546 : base (scope != null ? scope : am.Host,
1547 generic, return_type, mod | Modifiers.COMPILER_GENERATED, false, name, parameters, null)
1549 this.AnonymousMethod = am;
1552 if (scope != null) {
1553 scope.CheckMembersDefined ();
1554 scope.AddMethod (this);
1556 ModFlags |= Modifiers.STATIC;
1557 am.Host.PartialContainer.AddMethod (this);
1562 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1564 EmitContext aec = AnonymousMethod.aec;
1566 aec.MethodIsStatic = Scope == null;
1572 public class AnonymousMethod : AnonymousContainer
1574 public Type DelegateType;
1577 // The value return by the Compatible call, this ensure that
1578 // the code works even if invoked more than once (Resolve called
1579 // more than once, due to the way Convert.ImplicitConversion works
1581 Expression anonymous_delegate;
1582 RootScopeInfo root_scope;
1585 public AnonymousMethod (AnonymousMethod parent, RootScopeInfo root_scope,
1586 DeclSpace host, GenericMethod generic,
1587 Parameters parameters, Block container,
1588 ToplevelBlock block, Type return_type, Type delegate_type,
1590 : base (parent, host, generic, parameters, container, block,
1591 return_type, 0, loc)
1593 this.DelegateType = delegate_type;
1594 this.root_scope = root_scope;
1597 public override RootScopeInfo RootScope {
1598 get { return root_scope; }
1601 public override ScopeInfo Scope {
1602 get { return scope; }
1605 public override bool IsIterator {
1606 get { return false; }
1609 public Expression AnonymousDelegate {
1610 get { return anonymous_delegate; }
1613 public override string GetSignatureForError ()
1615 return TypeManager.CSharpName (DelegateType);
1619 // Creates the host for the anonymous method
1621 protected override Method DoCreateMethodHost (EmitContext ec)
1623 string name = CompilerGeneratedClass.MakeName ("AnonymousMethod");
1624 MemberName member_name;
1626 Report.Debug (128, "CREATE METHOD HOST #0", RootScope);
1631 Report.Debug (128, "CREATE METHOD HOST #1", this, Block, Block.ScopeInfo,
1632 RootScope, Location);
1634 for (b = Block.Parent; b != null; b = b.Parent) {
1635 Report.Debug (128, "CREATE METHOD HOST #2", this, Block,
1637 if (b.ScopeInfo != null) {
1638 scope = b.ScopeInfo;
1644 scope.CheckMembersDefined ();
1646 ArrayList scopes = new ArrayList ();
1648 for (b = b.Parent; b != null; b = b.Parent) {
1649 if (b.ScopeInfo != null)
1650 scopes.Add (b.ScopeInfo);
1654 Report.Debug (128, "CREATE METHOD HOST #1", this, scope, scopes);
1656 foreach (ScopeInfo si in scopes)
1657 scope.CaptureScope (si);
1659 Report.Debug (128, "CREATE METHOD HOST", this, Block, container,
1660 RootScope, scope, scopes, Location,
1661 ContainerAnonymousMethod);
1663 GenericMethod generic_method = null;
1665 if (TypeManager.IsGenericType (DelegateType)) {
1666 TypeArguments args = new TypeArguments (Location);
1668 Type dt = DelegateType.GetGenericTypeDefinition ();
1670 Type[] tparam = TypeManager.GetTypeArguments (dt);
1671 for (int i = 0; i < tparam.Length; i++)
1672 args.Add (new SimpleName (tparam [i].Name, Location));
1674 member_name = new MemberName (name, args, Location);
1676 Report.Debug (128, "CREATE METHOD HOST #5", this, DelegateType,
1677 TypeManager.GetTypeArguments (DelegateType),
1680 generic_method = new GenericMethod (
1681 Host.NamespaceEntry, scope, member_name,
1682 new TypeExpression (ReturnType, Location), Parameters);
1684 generic_method.SetParameterInfo (null);
1687 member_name = new MemberName (name, Location);
1689 return new AnonymousMethodMethod (
1690 this, scope, generic_method, new TypeExpression (ReturnType, Location),
1691 Modifiers.INTERNAL, member_name, Parameters);
1694 bool ResolveAnonymousDelegate (EmitContext ec)
1696 // If we are inferring the return type, set it to the discovered value.
1697 if (DelegateType == null){
1698 DelegateType = aec.ReturnType;
1700 // The special value pointing to our internal type means it failed.
1701 if (DelegateType == typeof (AnonymousDelegate))
1705 anonymous_delegate = new AnonymousDelegate (
1706 this, DelegateType, Location).Resolve (ec);
1707 if (anonymous_delegate == null)
1712 public override bool Resolve (EmitContext ec)
1714 if (!base.Resolve (ec))
1717 return ResolveAnonymousDelegate (ec);
1720 public override bool ResolveNoDefine (EmitContext ec)
1722 if (!base.ResolveNoDefine (ec))
1725 return ResolveAnonymousDelegate (ec);
1729 public MethodInfo GetMethodBuilder (EmitContext ec)
1731 MethodInfo builder = method.MethodBuilder;
1732 if ((Scope != null) && Scope.IsGeneric) {
1733 Type scope_type = Scope.GetScopeType (ec);
1734 if (scope_type == null)
1735 throw new InternalErrorException ();
1737 MethodGroupExpr mg = (MethodGroupExpr) Expression.MemberLookup (
1738 ec.ContainerType, scope_type, builder.Name, Location);
1741 throw new InternalErrorException ();
1742 builder = (MethodInfo) mg.Methods [0];
1746 if (!DelegateType.IsGenericType)
1749 Type[] targs = TypeManager.GetTypeArguments (DelegateType);
1750 return builder.MakeGenericMethod (targs);
1756 public static void Error_AddressOfCapturedVar (string name, Location loc)
1758 Report.Error (1686, loc,
1759 "Local variable `{0}' or its members cannot have their " +
1760 "address taken and be used inside an anonymous method block",
1766 // This will emit the code for the delegate, as well delegate creation on the host
1768 public class AnonymousDelegate : DelegateCreation {
1772 // if target_type is null, this means that we do not know the type
1773 // for this delegate, and we want to infer it from the various
1774 // returns (implicit and explicit) from the body of this anonymous
1777 // for example, the lambda: x => 1
1779 public AnonymousDelegate (AnonymousMethod am, Type target_type, Location l)
1786 public override Expression DoResolve (EmitContext ec)
1788 eclass = ExprClass.Value;
1791 // If we are inferencing
1794 type = ec.ReturnType;
1796 // No type was infered
1804 public override void Emit (EmitContext ec)
1806 //ec.ig.Emit (OpCodes.Ldstr, "EMIT ANONYMOUS DELEGATE");
1807 //ec.ig.Emit (OpCodes.Pop);
1810 // Now emit the delegate creation.
1812 if ((am.Method.ModFlags & Modifiers.STATIC) == 0) {
1813 Report.Debug (128, "EMIT ANONYMOUS DELEGATE", this, am, am.Scope, loc);
1814 delegate_instance_expression = am.Scope.GetScopeInitializer (ec);
1816 if (delegate_instance_expression == null)
1817 throw new InternalErrorException ();
1820 Expression ml = Expression.MemberLookup (
1821 ec.ContainerType, type, ".ctor", MemberTypes.Constructor,
1822 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
1825 constructor_method = ((MethodGroupExpr) ml).Methods [0];
1827 if (type.IsGenericType)
1828 constructor_method = TypeBuilder.GetConstructor (type, (ConstructorInfo)constructor_method);
1831 delegate_method = am.GetMethodBuilder (ec);
1834 //ec.ig.Emit (OpCodes.Ldstr, "EMIT ANONYMOUS DELEGATE DONE");
1835 //ec.ig.Emit (OpCodes.Pop);
1837 Report.Debug (128, "EMIT ANONYMOUS DELEGATE DONE", this, am, am.Scope, loc);
1841 public class AnonymousClass : CompilerGeneratedClass
1843 public AnonymousClass (TypeContainer parent, Location loc)
1844 : base (parent, null, 0, loc)