2 // anonymous.cs: Support for anonymous methods and types
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.
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
18 namespace Mono.CSharp {
20 public abstract class CompilerGeneratedClass : Class
22 public static string MakeName (string host, string typePrefix, string name, int id)
24 return "<" + host + ">" + typePrefix + "__" + name + id.ToString ();
27 protected CompilerGeneratedClass (DeclSpace parent, MemberName name, int mod, Location loc)
28 : base (parent.NamespaceEntry, parent, name, mod | Modifiers.COMPILER_GENERATED | Modifiers.SEALED, null)
30 parent.PartialContainer.AddCompilerGeneratedClass (this);
33 protected CompilerGeneratedClass (DeclSpace parent, GenericMethod generic, MemberName name, int mod, Location loc)
34 : this (parent, name, mod, loc)
36 if (generic != null) {
37 ArrayList list = new ArrayList ();
38 foreach (TypeParameter tparam in generic.TypeParameters) {
39 if (tparam.Constraints != null)
40 list.Add (tparam.Constraints.Clone ());
42 SetParameterInfo (list);
46 protected void CheckMembersDefined ()
49 throw new InternalErrorException ("Helper class already defined!");
54 // Anonymous method storey is created when an anonymous method uses
55 // variable or parameter from outer scope. They are then hoisted to
56 // anonymous method storey (captured)
58 public class AnonymousMethodStorey : CompilerGeneratedClass
60 class StoreyFieldPair {
61 public AnonymousMethodStorey Storey;
64 public StoreyFieldPair (AnonymousMethodStorey storey)
69 public override int GetHashCode ()
71 return Storey.ID.GetHashCode ();
74 public override bool Equals (object obj)
76 return (AnonymousMethodStorey)obj == Storey;
80 class HoistedGenericField : Field
82 public HoistedGenericField (DeclSpace parent, FullNamedExpression type, int mod, string name,
83 Attributes attrs, Location loc)
84 : base (parent, type, mod, name, attrs, loc)
88 public override bool Define ()
90 type_name.Type = ((AnonymousMethodStorey) Parent).MutateType (type_name.Type);
91 return base.Define ();
95 // TODO: Why is it required by debugger ?
96 public readonly int ID;
99 public readonly Block OriginalSourceBlock;
101 // A list of StoreyFieldPair with local field keeping parent storey instance
102 ArrayList used_parent_storeys;
104 // A list of hoisted parameters
105 protected ArrayList hoisted_params;
108 HoistedThis hoisted_this;
110 // Local variable which holds this storey instance
111 public LocalTemporary Instance;
113 bool references_defined;
115 public AnonymousMethodStorey (Block block, DeclSpace parent, MemberBase host, GenericMethod generic, string name)
116 : base (parent, generic, MakeMemberName (host, name, generic, block.StartLocation), Modifiers.PRIVATE, block.StartLocation)
119 OriginalSourceBlock = block;
123 static MemberName MakeMemberName (MemberBase host, string name, GenericMethod generic, Location loc)
125 string host_name = host == null ? null : host.Name;
126 string tname = MakeName (host_name, "c", name, unique_id);
127 TypeArguments args = null;
128 if (generic != null) {
129 args = new TypeArguments (loc);
130 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
131 args.Add (new SimpleName (tparam.Name, loc));
134 return new MemberName (tname, args, loc);
137 public Field AddCapturedVariable (string name, Type type)
139 CheckMembersDefined ();
141 FullNamedExpression field_type = new TypeExpression (type, Location);
143 return AddCompilerGeneratedField (name, field_type);
145 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
146 Field f = new HoistedGenericField (this, field_type, mod, name, null, Location);
151 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
153 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
154 Field f = new Field (this, type, mod, name, null, Location);
159 public void AddParentStoreyReference (AnonymousMethodStorey s)
161 CheckMembersDefined ();
163 if (used_parent_storeys == null)
164 used_parent_storeys = new ArrayList ();
165 else if (used_parent_storeys.IndexOf (s) != -1)
168 used_parent_storeys.Add (new StoreyFieldPair (s));
171 public void CaptureLocalVariable (EmitContext ec, LocalInfo local_info)
173 if (local_info.HoistedVariableReference != null)
176 HoistedVariable var = new HoistedLocalVariable (this, local_info, GetVariableMangledName (local_info));
177 local_info.HoistedVariableReference = var;
180 public void CaptureParameter (EmitContext ec, ParameterReference param_ref)
182 if (param_ref.HoistedVariable != null)
185 if (hoisted_params == null)
186 hoisted_params = new ArrayList ();
188 HoistedVariable expr = new HoistedParameter (this, param_ref);
189 param_ref.Parameter.HoistedVariableReference = expr;
190 hoisted_params.Add (expr);
193 public HoistedThis CaptureThis (EmitContext ec, This t)
195 hoisted_this = new HoistedThis (this, t);
199 void DefineStoreyReferences ()
201 if (used_parent_storeys == null || references_defined)
204 references_defined = true;
207 // For each used variable from parent scope we allocate its local reference point
209 for (int i = 0; i < used_parent_storeys.Count; ++i) {
210 StoreyFieldPair sf = (StoreyFieldPair) used_parent_storeys [i];
211 AnonymousMethodStorey p_storey = sf.Storey;
212 TypeExpr type_expr = new TypeExpression (p_storey.TypeBuilder, Location);
214 sf.Field = AddCompilerGeneratedField ("<>f__ref$" + p_storey.ID, type_expr);
220 // Initializes all hoisted variables
222 public void EmitHoistedVariables (EmitContext ec)
224 // There can be only one instance variable for each storey type
225 if (Instance != null)
226 throw new InternalErrorException ();
229 // A storey with hoisted `this' is an instance method
231 if (!HasHoistedVariables) {
232 throw new NotImplementedException ();
235 DefineStoreyReferences ();
238 // Create an instance of storey type
240 Expression storey_type_expr;
243 // Use current method type parameter (MVAR) for top level storey only. All
244 // nested storeys use class type parameter (VAR)
246 TypeParameter[] tparams = ec.CurrentAnonymousMethod != null ?
247 ec.CurrentAnonymousMethod.Storey.CurrentTypeParameters :
248 ec.GenericDeclContainer.CurrentTypeParameters;
250 if (tparams.Length != CountTypeParameters) {
251 TypeParameter [] full = new TypeParameter [CountTypeParameters];
252 DeclSpace parent = ec.DeclContainer.Parent;
253 parent.CurrentTypeParameters.CopyTo (full, 0);
254 tparams.CopyTo (full, parent.CountTypeParameters);
258 storey_type_expr = new ConstructedType (TypeBuilder, tparams, Location);
260 storey_type_expr = new TypeExpression (TypeBuilder, Location);
263 Expression e = new New (storey_type_expr, new ArrayList (0), Location).Resolve (ec);
266 Instance = new LocalTemporary (storey_type_expr.Type);
269 EmitHoistedFieldsInitialization (ec);
272 void EmitHoistedFieldsInitialization (EmitContext ec)
275 // Initialize all storey reference fields by using local or hoisted variables
277 if (used_parent_storeys != null) {
278 foreach (StoreyFieldPair sf in used_parent_storeys) {
280 // Setting local field
282 FieldExpr f_set_expr = new FieldExpr (sf.Field.FieldBuilder, Location);
283 f_set_expr.InstanceExpression = GetStoreyInstanceExpression (ec);
285 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
286 if (a.Resolve (ec) != null)
287 a.EmitStatement (ec);
292 // Setting currect anonymous method to null blocks any further variable hoisting
294 AnonymousExpression ae = ec.CurrentAnonymousMethod;
295 ec.CurrentAnonymousMethod = null;
297 if (hoisted_params != null) {
298 foreach (HoistedParameter hp in hoisted_params) {
299 hp.EmitHoistingAssignment (ec);
303 if (hoisted_this != null) {
304 hoisted_this.EmitHoistingAssignment (ec);
307 ec.CurrentAnonymousMethod = ae;
310 public override void EmitType ()
312 DefineStoreyReferences ();
317 // Returns a field which holds referenced storey instance
319 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
321 if (used_parent_storeys == null)
324 foreach (StoreyFieldPair sf in used_parent_storeys) {
325 if (sf.Storey == storey)
333 // Creates storey instance expression regardless of currect IP
335 public Expression GetStoreyInstanceExpression (EmitContext ec)
337 AnonymousExpression am = ec.CurrentAnonymousMethod;
340 // Access from original block -> storey
346 // Access from anonymous method implemented as a static -> storey
348 if (am.Storey == null)
351 Field f = am.Storey.GetReferencedStoreyField (this);
353 if (am.Storey == this) {
355 // Access inside of same storey (S -> S)
357 return new CompilerGeneratedThis (TypeBuilder, Location);
360 // External field access
366 // Storey was cached to local field
368 FieldExpr f_ind = new FieldExpr (f.FieldBuilder, Location);
369 f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
373 protected virtual string GetVariableMangledName (LocalInfo local_info)
376 // No need to mangle anonymous method hoisted variables cause they
377 // are hoisted in their own scopes
379 return local_info.Name;
382 public bool HasHoistedVariables {
384 return true; // TODO: Finish this optimization
389 // Mutate type dispatcher
391 public Type MutateType (Type type)
394 if (TypeManager.IsGenericType (type))
395 return MutateGenericType (type);
397 if (TypeManager.IsGenericParameter (type))
398 return MutateGenericArgument (type);
401 return MutateArrayType (type);
407 // Changes method type arguments (MVAR) to storey (VAR) type arguments
409 public MethodInfo MutateGenericMethod (MethodInfo method)
412 if (TypeManager.IsGenericType (method.DeclaringType)) {
413 Type t = MutateGenericType (method.DeclaringType);
414 if (t != method.DeclaringType)
415 method = TypeBuilder.GetMethod (t, method);
418 Type [] t_args = TypeManager.GetGenericArguments (method);
419 if (t_args == null || t_args.Length == 0)
422 for (int i = 0; i < t_args.Length; ++i)
423 t_args [i] = MutateType (t_args [i]);
425 return method.GetGenericMethodDefinition ().MakeGenericMethod (t_args);
427 throw new NotSupportedException ();
431 public ConstructorInfo MutateConstructor (ConstructorInfo ctor)
434 if (TypeManager.IsGenericType (ctor.DeclaringType)) {
435 Type t = MutateGenericType (ctor.DeclaringType);
436 if (t != ctor.DeclaringType) {
437 // TODO: It should throw on imported types
438 return TypeBuilder.GetConstructor (t, ctor);
446 protected Type MutateArrayType (Type array)
448 int rank = array.GetArrayRank ();
449 Type element = TypeManager.GetElementType (array);
451 throw new NotImplementedException ();
453 if (TypeManager.IsGenericParameter (element)) {
454 element = MutateGenericArgument (element);
455 } else if (TypeManager.IsGenericType (element)) {
456 element = MutateGenericType (element);
461 return element.MakeArrayType (rank);
464 protected Type MutateGenericType (Type type)
466 Type [] t_args = TypeManager.GetTypeArguments (type);
467 if (t_args == null || t_args.Length == 0)
470 for (int i = 0; i < t_args.Length; ++i)
471 t_args [i] = MutateType (t_args [i]);
473 return type.GetGenericTypeDefinition ().MakeGenericType (t_args);
478 // Changes method generic argument (MVAR) to type generic argument (VAR)
480 public Type MutateGenericArgument (Type type)
482 foreach (TypeParameter tp in CurrentTypeParameters) {
483 if (tp.Name == type.Name) {
491 public static void Reset ()
497 public abstract class HoistedVariable
499 protected readonly AnonymousMethodStorey storey;
500 protected Field field;
501 Hashtable cached_inner_access; // TODO: Hashtable is too heavyweight
503 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
505 this.storey = storey;
507 this.field = storey.AddCapturedVariable (name, type);
510 public void AddressOf (EmitContext ec, AddressOp mode)
512 GetFieldExpression (ec).AddressOf (ec, mode);
515 public void Emit (EmitContext ec)
517 GetFieldExpression (ec).Emit (ec);
521 // Creates field access expression for hoisted variable
523 protected FieldExpr GetFieldExpression (EmitContext ec)
525 if (ec.CurrentAnonymousMethod == null) {
527 // When setting top-level hoisted variable in generic storey
528 // change storey generic types to method generic types (VAR -> MVAR)
530 FieldExpr outer_access = storey.MemberName.IsGeneric ?
531 new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
532 new FieldExpr (field.FieldBuilder, field.Location);
534 outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
535 outer_access.Resolve (ec);
539 FieldExpr inner_access;
540 if (cached_inner_access != null) {
541 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
544 cached_inner_access = new Hashtable (4);
547 if (inner_access == null) {
548 inner_access = new FieldExpr (field.FieldBuilder, field.Location);
549 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
550 inner_access.Resolve (ec);
551 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
557 public abstract void EmitSymbolInfo ();
559 public void Emit (EmitContext ec, bool leave_copy)
561 GetFieldExpression (ec).Emit (ec, leave_copy);
564 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
566 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
570 class HoistedParameter : HoistedVariable
572 class HoistedFieldAssign : Assign
574 public HoistedFieldAssign (Expression target, Expression source)
575 : base (target, source, source.Location)
579 protected override Expression ResolveConversions (EmitContext ec)
582 // Implicit conversion check fails for hoisted type arguments
583 // as they are of different types (!!0 x !0)
589 readonly ParameterReference parameter;
591 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
592 : base (scope, par.Name, par.Type)
594 this.parameter = par;
597 public void EmitHoistingAssignment (EmitContext ec)
600 // Remove hoisted redirection to emit assignment from original parameter
602 HoistedVariable temp = parameter.Parameter.HoistedVariableReference;
603 parameter.Parameter.HoistedVariableReference = null;
605 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
606 if (a.Resolve (ec) != null)
607 a.EmitStatement (ec);
609 parameter.Parameter.HoistedVariableReference = temp;
612 public override void EmitSymbolInfo ()
614 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
618 get { return field; }
622 class HoistedLocalVariable : HoistedVariable
624 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
625 : base (scope, name, local.VariableType)
629 public override void EmitSymbolInfo ()
631 SymbolWriter.DefineCapturedLocal (storey.ID, field.Name, field.Name);
635 public class HoistedThis : HoistedVariable
637 readonly This this_reference;
639 public HoistedThis (AnonymousMethodStorey storey, This this_reference)
640 : base (storey, "<>f__this", this_reference.Type)
642 this.this_reference = this_reference;
645 public void EmitHoistingAssignment (EmitContext ec)
647 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), this_reference);
648 if (a.Resolve (ec) != null)
649 a.EmitStatement (ec);
652 public override void EmitSymbolInfo ()
654 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
658 // TODO: Remove, it should be done in block
659 public interface IAnonymousHost
662 // Invoked if a yield statement is found in the body
668 // Anonymous method expression as created by parser
670 public class AnonymousMethodExpression : Expression
672 protected readonly TypeContainer Host;
673 public readonly Parameters Parameters;
675 public ToplevelBlock Block;
677 public AnonymousMethodExpression (TypeContainer host, Parameters parameters, Location loc)
680 this.Parameters = parameters;
684 public override string ExprClassName {
686 return "anonymous method";
690 public virtual bool HasExplicitParameters {
692 return Parameters != null;
697 // Returns true if the body of lambda expression can be implicitly
698 // converted to the delegate of type `delegate_type'
700 public bool ImplicitStandardConversionExists (EmitContext ec, Type delegate_type)
702 using (ec.Set (EmitContext.Flags.ProbingMode)) {
703 return Compatible (ec, delegate_type) != null;
707 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
709 if (TypeManager.IsDelegateType (delegate_type))
710 return delegate_type;
713 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
714 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
715 if (TypeManager.IsDelegateType (delegate_type))
716 return delegate_type;
718 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
719 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
724 Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
725 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
729 protected bool VerifyExplicitParameters (Type delegate_type, ParameterData parameters, bool ignore_error)
731 if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
735 Report.Error (1661, loc,
736 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
737 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
742 protected bool VerifyParameterCompatibility (Type delegate_type, ParameterData invoke_pd, bool ignore_errors)
744 if (Parameters.Count != invoke_pd.Count) {
748 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
749 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
753 if (!HasExplicitParameters)
757 for (int i = 0; i < Parameters.Count; ++i) {
758 Parameter.Modifier p_mod = invoke_pd.ParameterModifier (i);
759 if (Parameters.ParameterModifier (i) != p_mod && p_mod != Parameter.Modifier.PARAMS) {
763 if (p_mod == Parameter.Modifier.NONE)
764 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
765 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.ParameterModifier (i)));
767 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
768 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
773 Type type = invoke_pd.Types [i];
775 // We assume that generic parameters are always inflated
776 if (TypeManager.IsGenericParameter (type))
779 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
782 if (invoke_pd.ParameterType (i) != Parameters.ParameterType (i)) {
786 Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
788 TypeManager.CSharpName (Parameters.ParameterType (i)),
789 TypeManager.CSharpName (invoke_pd.ParameterType (i)));
798 // Infers type arguments based on explicit arguments
800 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
802 if (!HasExplicitParameters)
805 if (!TypeManager.IsDelegateType (delegate_type)) {
807 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
810 delegate_type = delegate_type.GetGenericArguments () [0];
811 if (!TypeManager.IsDelegateType (delegate_type))
818 ParameterData d_params = TypeManager.GetDelegateParameters (delegate_type);
819 if (d_params.Count != Parameters.Count)
822 for (int i = 0; i < Parameters.Count; ++i) {
823 Type itype = d_params.Types [i];
824 if (!TypeManager.IsGenericParameter (itype)) {
825 if (!TypeManager.HasElementType (itype))
828 if (!TypeManager.IsGenericParameter (itype.GetElementType ()))
831 type_inference.ExactInference (Parameters.FixedParameters[i].ParameterType, itype);
836 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
838 AnonymousMethodBody am;
839 using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
840 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
846 if (am.ReturnType == TypeManager.null_type)
847 am.ReturnType = null;
849 return am.ReturnType;
853 // Returns AnonymousMethod container if this anonymous method
854 // expression can be implicitly converted to the delegate type `delegate_type'
856 public Expression Compatible (EmitContext ec, Type type)
858 Type delegate_type = CompatibleChecks (ec, type);
859 if (delegate_type == null)
863 // At this point its the first time we know the return type that is
864 // needed for the anonymous method. We create the method here.
867 MethodInfo invoke_mb = Delegate.GetInvokeMethod (
868 ec.ContainerType, delegate_type);
869 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
872 Type[] g_args = delegate_type.GetGenericArguments ();
873 if (return_type.IsGenericParameter)
874 return_type = g_args [return_type.GenericParameterPosition];
878 // Second: the return type of the delegate must be compatible with
879 // the anonymous type. Instead of doing a pass to examine the block
880 // we satisfy the rule by setting the return type on the EmitContext
881 // to be the delegate type return type.
885 int errors = Report.Errors;
886 AnonymousMethodBody am = CompatibleMethod (ec, null, return_type, delegate_type);
887 if (am != null && delegate_type != type && errors == Report.Errors)
888 return CreateExpressionTree (ec, delegate_type);
891 } catch (Exception e) {
892 throw new InternalErrorException (e, loc);
896 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
898 return CreateExpressionTree (ec);
901 public override Expression CreateExpressionTree (EmitContext ec)
903 Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
907 protected virtual Parameters ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
909 ParameterData delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
911 if (Parameters == null) {
913 // We provide a set of inaccessible parameters
915 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
917 for (int i = 0; i < delegate_parameters.Count; i++) {
918 Parameter.Modifier i_mod = delegate_parameters.ParameterModifier (i);
919 if ((i_mod & Parameter.Modifier.OUTMASK) != 0) {
920 Report.Error (1688, loc, "Cannot convert anonymous " +
921 "method block without a parameter list " +
922 "to delegate type `{0}' because it has " +
923 "one or more `out' parameters.",
924 TypeManager.CSharpName (delegate_type));
927 fixedpars[i] = new Parameter (
928 delegate_parameters.ParameterType (i), null,
929 delegate_parameters.ParameterModifier (i), null, loc);
932 return Parameters.CreateFullyResolved (fixedpars, delegate_parameters.Types);
935 if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
942 public override Expression DoResolve (EmitContext ec)
944 if (!ec.IsAnonymousMethodAllowed) {
945 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
950 // Set class type, set type
953 eclass = ExprClass.Value;
956 // This hack means `The type is not accessible
957 // anywhere', we depend on special conversion
960 type = TypeManager.anonymous_method_type;
962 if ((Parameters != null) && !Parameters.Resolve (ec))
965 // FIXME: The emitted code isn't very careful about reachability
966 // so, ensure we have a 'ret' at the end
967 if (ec.CurrentBranching != null &&
968 ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
969 ec.NeedReturnLabel ();
974 public override void Emit (EmitContext ec)
976 // nothing, as we only exist to not do anything.
979 public override string GetSignatureForError ()
981 return ExprClassName;
984 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
986 Parameters p = ResolveParameters (ec, tic, delegate_type);
990 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
992 AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
993 if (!anonymous.Compatible (ec))
999 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, Parameters p, ToplevelBlock b)
1001 return new AnonymousMethodBody (Host,
1003 delegate_type, loc);
1006 protected override void CloneTo (CloneContext clonectx, Expression t)
1008 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1010 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1015 // Abstract expression for any block which requires variables hoisting
1017 public abstract class AnonymousExpression : Expression
1019 protected class AnonymousMethodMethod : Method
1021 public readonly AnonymousExpression AnonymousMethod;
1022 public readonly AnonymousMethodStorey Storey;
1023 readonly string RealName;
1025 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1026 GenericMethod generic, TypeExpr return_type,
1027 int mod, string real_name, MemberName name,
1028 Parameters parameters)
1029 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1030 false, name, parameters, null)
1032 this.AnonymousMethod = am;
1033 this.Storey = storey;
1034 this.RealName = real_name;
1036 Parent.PartialContainer.AddMethod (this);
1040 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1042 EmitContext aec = AnonymousMethod.aec;
1044 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1048 public override bool Define ()
1050 if (Storey != null && Storey.IsGeneric) {
1051 if (!Parameters.Empty) {
1052 Type [] ptypes = Parameters.Types;
1053 for (int i = 0; i < ptypes.Length; ++i) {
1054 if (TypeManager.IsGenericParameter (ptypes [i]))
1055 ptypes [i] = Storey.MutateType (ptypes [i]);
1059 member_type = Storey.MutateType (ReturnType);
1062 return base.Define ();
1065 public override void Emit ()
1068 // Before emitting any code we have to change all MVAR references to VAR
1069 // when the method is of generic type and has hoisted variables
1071 if (Storey == Parent && Storey.IsGeneric) {
1072 AnonymousMethod.aec.ReturnType = Storey.MutateType (ReturnType);
1073 block.MutateHoistedGenericType (Storey);
1079 public override void EmitExtraSymbolInfo (SourceMethod source)
1081 source.SetRealMethodName (RealName);
1086 // The block that makes up the body for the anonymous method
1088 protected readonly ToplevelBlock Block;
1090 public Type ReturnType;
1091 public readonly DeclSpace Host;
1094 // The implicit method we create
1096 protected AnonymousMethodMethod method;
1097 protected EmitContext aec;
1099 protected AnonymousExpression (DeclSpace host, ToplevelBlock block, Type return_type, Location loc)
1101 this.ReturnType = return_type;
1108 public abstract void AddStoreyReference (AnonymousMethodStorey storey);
1109 public abstract string ContainerType { get; }
1110 public abstract bool IsIterator { get; }
1111 public abstract AnonymousMethodStorey Storey { get; }
1113 public bool Compatible (EmitContext ec)
1115 // TODO: Implement clone
1116 aec = new EmitContext (
1117 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1118 Location, null, ReturnType,
1119 /* REVIEW */ (ec.InIterator ? Modifiers.METHOD_YIELDS : 0) |
1120 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1122 aec.CurrentAnonymousMethod = this;
1123 aec.IsStatic = ec.IsStatic;
1125 IDisposable aec_dispose = null;
1126 EmitContext.Flags flags = 0;
1127 if (ec.InferReturnType)
1128 flags |= EmitContext.Flags.InferReturnType;
1130 if (ec.IsInProbingMode)
1131 flags |= EmitContext.Flags.ProbingMode;
1133 if (ec.IsInFieldInitializer)
1134 flags |= EmitContext.Flags.InFieldInitializer;
1136 if (ec.IsInUnsafeScope)
1137 flags |= EmitContext.Flags.InUnsafe;
1139 // HACK: Flag with 0 cannot be set
1141 aec_dispose = aec.Set (flags);
1144 bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1146 if (ec.InferReturnType)
1147 ReturnType = aec.ReturnType;
1149 if (aec_dispose != null) {
1150 aec_dispose.Dispose ();
1157 public class AnonymousMethodBody : AnonymousExpression
1159 ArrayList referenced_storeys;
1160 readonly Parameters parameters;
1161 static int unique_id;
1163 public AnonymousMethodBody (
1165 Parameters parameters,
1166 ToplevelBlock block, Type return_type, Type delegate_type,
1168 : base (host, block, return_type, loc)
1170 this.type = delegate_type;
1171 this.parameters = parameters;
1174 public override string ContainerType {
1175 get { return "anonymous method"; }
1178 public override AnonymousMethodStorey Storey {
1179 get { return method.Storey; }
1182 public override bool IsIterator {
1183 get { return false; }
1187 // Adds new storey reference to track out of scope variables
1189 public override void AddStoreyReference (AnonymousMethodStorey storey)
1191 if (referenced_storeys == null) {
1192 referenced_storeys = new ArrayList ();
1194 foreach (AnonymousMethodStorey ams in referenced_storeys) {
1200 referenced_storeys.Add (storey);
1203 public override Expression CreateExpressionTree (EmitContext ec)
1205 Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1209 bool Define (EmitContext ec)
1211 if (aec == null && !Compatible (ec))
1214 // Don't define anything when we are in probing scope (nested anonymous methods)
1215 if (ec.IsInProbingMode)
1218 method = DoCreateMethodHost (ec);
1221 // Define method only when is not inside AnonymousMethodStorey because a container passed its Define
1223 if (method.Storey != null && method.Storey.HasHoistedVariables)
1226 method.ResolveMembers ();
1227 return method.Define ();
1231 // Creates a host for the anonymous method
1233 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1235 AnonymousMethodStorey storey = FindBestMethodStorey ();
1236 if (referenced_storeys != null && referenced_storeys.Count > 1) {
1237 foreach (AnonymousMethodStorey s in referenced_storeys) {
1241 storey.AddParentStoreyReference (s);
1242 Block.Parent.Explicit.PropagateStoreyReference (s);
1247 // Anonymous method body can be converted to
1249 // 1, an instance method in current scope when only `this' is hoisted
1250 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1251 // 3, an instance method in compiler generated storey when any hoisted variable exists
1255 if (storey != null) {
1256 modifiers = storey.HasHoistedVariables ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1258 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1261 DeclSpace parent = (modifiers & Modifiers.PRIVATE) != 0 ? Host : storey;
1263 MemberCore mc = ec.ResolveContext as MemberCore;
1264 string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1265 "m", null, unique_id++);
1267 MemberName member_name;
1268 GenericMethod generic_method;
1269 if ((modifiers & Modifiers.PRIVATE) != 0 && mc.MemberName.IsGeneric) {
1270 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1272 generic_method = new GenericMethod (
1273 Host.NamespaceEntry, storey, member_name,
1274 new TypeExpression (ReturnType, Location), parameters);
1275 generic_method.SetParameterInfo (null);
1277 member_name = new MemberName (name, Location);
1278 generic_method = null;
1281 string real_name = String.Format (
1282 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1283 parameters.GetSignatureForError ());
1285 return new AnonymousMethodMethod (parent,
1286 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1287 real_name, member_name, parameters);
1290 public override Expression DoResolve (EmitContext ec)
1295 eclass = ExprClass.Value;
1299 public override void Emit (EmitContext ec)
1302 // Load method delegate implementation
1304 if ((method.ModFlags & Modifiers.STATIC) != 0) {
1305 ec.ig.Emit (OpCodes.Ldnull);
1307 Expression e = Storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1312 MethodInfo delegate_method = method.MethodBuilder;
1314 if (Storey != null && Storey.IsGeneric)
1315 delegate_method = TypeBuilder.GetMethod (Storey.Instance.Type, delegate_method);
1317 ec.ig.Emit (OpCodes.Ldftn, delegate_method);
1319 ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1321 if (type.IsGenericType && type is TypeBuilder)
1322 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1324 ec.ig.Emit (OpCodes.Newobj, constructor_method);
1328 // Look for the best storey for this anonymous method
1330 AnonymousMethodStorey FindBestMethodStorey ()
1332 if (referenced_storeys == null) {
1333 for (Block b = Block.Parent; b != null; b = b.Parent) {
1334 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1342 if (referenced_storeys.Count == 1)
1343 return (AnonymousMethodStorey) referenced_storeys [0];
1345 for (Block b = Block.Parent; b != null; b = b.Parent) {
1346 foreach (AnonymousMethodStorey storey in referenced_storeys) {
1347 if (storey.OriginalSourceBlock == b)
1355 public override string GetSignatureForError ()
1357 return TypeManager.CSharpName (type);
1360 public static void Error_AddressOfCapturedVar (string name, Location loc)
1362 Report.Error (1686, loc,
1363 "Local variable `{0}' or its members cannot have their " +
1364 "address taken and be used inside an anonymous method block",
1368 public static void Reset ()
1375 // Anonymous type container
1377 public class AnonymousTypeClass : CompilerGeneratedClass
1379 static int types_counter;
1380 public const string ClassNamePrefix = "<>__AnonType";
1381 public const string SignatureForError = "anonymous type";
1383 readonly ArrayList parameters;
1385 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1386 : base (parent, name, Modifiers.SEALED, loc)
1388 this.parameters = parameters;
1391 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1393 if (RootContext.Version <= LanguageVersion.ISO_2)
1394 Report.FeatureIsNotAvailable (loc, "anonymous types");
1396 string name = ClassNamePrefix + types_counter++;
1398 SimpleName [] t_args = new SimpleName [parameters.Count];
1399 Parameter [] ctor_params = new Parameter [parameters.Count];
1400 for (int i = 0; i < parameters.Count; ++i) {
1401 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1403 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1404 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1408 // Create generic anonymous type host with generic arguments
1409 // named upon properties names
1411 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1412 new MemberName (name, new TypeArguments (loc, t_args), loc), parameters, loc);
1414 if (parameters.Count > 0)
1415 a_type.SetParameterInfo (null);
1417 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC,
1418 new Parameters (ctor_params), null, loc);
1419 c.OptAttributes = a_type.GetDebuggerHiddenAttribute ();
1420 c.Block = new ToplevelBlock (c.Parameters, loc);
1423 // Create fields and contructor body with field initialization
1426 for (int i = 0; i < parameters.Count; ++i) {
1427 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1429 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1430 "<" + p.Name + ">", null, p.Location);
1432 if (!a_type.AddField (f)) {
1434 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1439 c.Block.AddStatement (new StatementExpression (
1440 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1441 c.Block.GetParameterReference (p.Name, p.Location))));
1443 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1444 get_block.AddStatement (new Return (
1445 new MemberAccess (new This (p.Location), f.Name), p.Location));
1446 Accessor get_accessor = new Accessor (get_block, 0, null, p.Location);
1447 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC, false,
1448 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1449 a_type.AddProperty (prop);
1455 a_type.AddConstructor (c);
1459 public new static void Reset ()
1464 protected override bool AddToContainer (MemberCore symbol, string name)
1466 MemberCore mc = (MemberCore) defined_names [name];
1469 defined_names.Add (name, symbol);
1473 Report.SymbolRelatedToPreviousError (mc);
1477 void DefineOverrides ()
1479 Location loc = Location;
1481 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1482 Modifiers.PUBLIC | Modifiers.OVERRIDE, false, new MemberName ("Equals", loc),
1483 new Parameters (new Parameter (TypeManager.system_object_expr, "obj", 0, null, loc)),
1484 GetDebuggerHiddenAttribute ());
1486 Method tostring = new Method (this, null, TypeManager.system_string_expr,
1487 Modifiers.PUBLIC | Modifiers.OVERRIDE, false, new MemberName ("ToString", loc),
1488 Mono.CSharp.Parameters.EmptyReadOnlyParameters, GetDebuggerHiddenAttribute ());
1490 ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1491 TypeExpr current_type;
1493 current_type = new ConstructedType (TypeBuilder, TypeParameters, loc);
1495 current_type = new TypeExpression (TypeBuilder, loc);
1497 equals_block.AddVariable (current_type, "other", loc);
1498 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1500 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1501 new SimpleName ("System", loc), "Collections", loc), "Generic", loc);
1503 Expression rs_equals = null;
1504 Expression string_concat = new StringConstant ("<empty type>", loc);
1505 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1506 for (int i = 0; i < parameters.Count; ++i) {
1507 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1508 Field f = (Field) Fields [i];
1510 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1511 system_collections_generic, "EqualityComparer",
1512 new TypeArguments (loc, new SimpleName (TypeParameters [i].Name, loc)), loc),
1515 ArrayList arguments_equal = new ArrayList (2);
1516 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1517 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1519 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1520 "Equals", loc), arguments_equal);
1522 ArrayList arguments_hashcode = new ArrayList (1);
1523 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1524 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1525 "GetHashCode", loc), arguments_hashcode);
1527 IntConstant FNV_prime = new IntConstant (16777619, loc);
1528 rs_hashcode = new Binary (Binary.Operator.Multiply,
1529 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1532 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1533 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1534 new Invocation (new MemberAccess (
1535 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1536 new StringConstant ("<null>", loc));
1538 if (rs_equals == null) {
1539 rs_equals = field_equal;
1540 string_concat = new Binary (Binary.Operator.Addition,
1541 new StringConstant (p.Name + " = ", loc),
1547 // Implementation of ToString () body using string concatenation
1549 string_concat = new Binary (Binary.Operator.Addition,
1550 new Binary (Binary.Operator.Addition,
1552 new StringConstant (", " + p.Name + " = ", loc)),
1555 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1559 // Equals (object obj) override
1561 equals_block.AddStatement (new StatementExpression (
1562 new SimpleAssign (other_variable,
1563 new As (equals_block.GetParameterReference ("obj", loc),
1564 current_type, loc), loc)));
1566 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1567 if (rs_equals != null)
1568 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1569 equals_block.AddStatement (new Return (equals_test, loc));
1571 equals.Block = equals_block;
1572 equals.ResolveMembers ();
1576 // GetHashCode () override
1578 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1579 Modifiers.PUBLIC | Modifiers.OVERRIDE, false, new MemberName ("GetHashCode", loc),
1580 Mono.CSharp.Parameters.EmptyReadOnlyParameters, GetDebuggerHiddenAttribute ());
1583 // Modified FNV with good avalanche behavior and uniform
1584 // distribution with larger hash sizes.
1586 // const int FNV_prime = 16777619;
1587 // int hash = (int) 2166136261;
1588 // foreach (int d in data)
1589 // hash = (hash ^ d) * FNV_prime;
1590 // hash += hash << 13;
1591 // hash ^= hash >> 7;
1592 // hash += hash << 3;
1593 // hash ^= hash >> 17;
1594 // hash += hash << 5;
1596 ToplevelBlock hashcode_block = new ToplevelBlock (loc);
1597 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1598 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1599 hashcode_block.AddStatement (new StatementExpression (
1600 new SimpleAssign (hash_variable, rs_hashcode)));
1602 hashcode_block.AddStatement (new StatementExpression (
1603 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1604 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1605 hashcode_block.AddStatement (new StatementExpression (
1606 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1607 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1608 hashcode_block.AddStatement (new StatementExpression (
1609 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1610 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1611 hashcode_block.AddStatement (new StatementExpression (
1612 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1613 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1614 hashcode_block.AddStatement (new StatementExpression (
1615 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1616 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1618 hashcode_block.AddStatement (new Return (hash_variable, loc));
1619 hashcode.Block = hashcode_block;
1620 hashcode.ResolveMembers ();
1621 AddMethod (hashcode);
1624 // ToString () override
1627 ToplevelBlock tostring_block = new ToplevelBlock (loc);
1628 tostring_block.AddStatement (new Return (string_concat, loc));
1629 tostring.Block = tostring_block;
1630 tostring.ResolveMembers ();
1631 AddMethod (tostring);
1634 public override bool DefineMembers ()
1638 return base.DefineMembers ();
1641 Attributes GetDebuggerHiddenAttribute ()
1643 return new Attributes (new Attribute (null, null,
1644 "System.Diagnostics.DebuggerHiddenAttribute", null, Location, false));
1647 public override string GetSignatureForError ()
1649 return SignatureForError;
1652 public ArrayList Parameters {