In class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine:
[mcs.git] / mcs / anonymous.cs
blob5411271375d58c4b845cb2bb9a2c37c5428f7cab
1 //
2 // anonymous.cs: Support for anonymous methods and types
3 //
4 // Author:
5 // Miguel de Icaza (miguel@ximain.com)
6 // Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003-2008 Novell, Inc.
12 using System;
13 using System.Text;
14 using System.Collections;
15 using System.Collections.Specialized;
16 using System.Reflection;
17 using System.Reflection.Emit;
19 namespace Mono.CSharp {
21 public abstract class CompilerGeneratedClass : Class
23 public static string MakeName (string host, string typePrefix, string name, int id)
25 return "<" + host + ">" + typePrefix + "__" + name + id.ToString ("X");
28 protected CompilerGeneratedClass (DeclSpace parent, MemberName name, int mod)
29 : base (parent.NamespaceEntry, parent, name, mod | Modifiers.COMPILER_GENERATED | Modifiers.SEALED, null)
33 protected CompilerGeneratedClass (DeclSpace parent, GenericMethod generic, MemberName name, int mod)
34 : this (parent, name, mod)
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 ()
48 if (members_defined)
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 readonly AnonymousMethodStorey Storey;
62 public readonly Field Field;
64 public StoreyFieldPair (AnonymousMethodStorey storey, Field field)
66 this.Storey = storey;
67 this.Field = field;
70 public override int GetHashCode ()
72 return Storey.ID.GetHashCode ();
75 public override bool Equals (object obj)
77 return (AnonymousMethodStorey)obj == Storey;
81 sealed class HoistedGenericField : Field
83 public HoistedGenericField (DeclSpace parent, FullNamedExpression type, int mod, string name,
84 Attributes attrs, Location loc)
85 : base (parent, type, mod, new MemberName (name, loc), attrs)
89 protected override bool ResolveMemberType ()
91 if (!base.ResolveMemberType ())
92 return false;
94 AnonymousMethodStorey parent = ((AnonymousMethodStorey) Parent).GetGenericStorey ();
95 if (parent != null)
96 member_type = parent.MutateType (member_type);
98 return true;
103 // Needed to delay hoisted _this_ initialization. When an anonymous
104 // method is used inside ctor and _this_ is hoisted, base ctor has to
105 // be called first, otherwise _this_ will be initialized with
106 // uninitialized value.
108 sealed class ThisInitializer : Statement
110 readonly HoistedThis hoisted_this;
112 public ThisInitializer (HoistedThis hoisted_this)
114 this.hoisted_this = hoisted_this;
117 protected override void DoEmit (EmitContext ec)
119 hoisted_this.EmitHoistingAssignment (ec);
122 protected override void CloneTo (CloneContext clonectx, Statement target)
124 // Nothing to clone
127 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
129 // Nothing to mutate
133 // Unique storey ID
134 public readonly int ID;
135 static int unique_id;
137 public readonly Block OriginalSourceBlock;
139 // A list of StoreyFieldPair with local field keeping parent storey instance
140 ArrayList used_parent_storeys;
141 ArrayList children_references;
143 // A list of hoisted parameters
144 protected ArrayList hoisted_params;
145 protected ArrayList hoisted_locals;
147 // Hoisted this
148 protected HoistedThis hoisted_this;
150 // Local variable which holds this storey instance
151 public LocalTemporary Instance;
153 public AnonymousMethodStorey (Block block, DeclSpace parent, MemberBase host, GenericMethod generic, string name)
154 : base (parent, generic, MakeMemberName (host, name, generic, block.StartLocation), Modifiers.PRIVATE)
156 Parent = parent;
157 OriginalSourceBlock = block;
158 ID = unique_id++;
161 static MemberName MakeMemberName (MemberBase host, string name, GenericMethod generic, Location loc)
163 string host_name = host == null ? null : host.Name;
164 string tname = MakeName (host_name, "c", name, unique_id);
165 TypeArguments args = null;
166 if (generic != null) {
167 args = new TypeArguments ();
168 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
169 args.Add (new TypeParameterName (tparam.Name, null, loc));
172 return new MemberName (tname, args, loc);
175 public void AddCapturedThisField (EmitContext ec)
177 TypeExpr type_expr = new TypeExpression (ec.ContainerType, Location);
178 Field f = AddCompilerGeneratedField ("<>f__this", type_expr);
179 f.Define ();
180 hoisted_this = new HoistedThis (this, f);
183 public Field AddCapturedVariable (string name, Type type)
185 CheckMembersDefined ();
187 FullNamedExpression field_type = new TypeExpression (type, Location);
188 if (!IsGeneric)
189 return AddCompilerGeneratedField (name, field_type);
191 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
192 Field f = new HoistedGenericField (this, field_type, mod, name, null, Location);
193 AddField (f);
194 return f;
197 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
199 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
200 Field f = new Field (this, type, mod, new MemberName (name, Location), null);
201 AddField (f);
202 return f;
206 // Creates a link between block and the anonymous method storey
208 // An anonymous method can reference variables from any outer block, but they are
209 // hoisted in their own ExplicitBlock. When more than one block is referenced we
210 // need to create another link between those variable storeys
212 public void AddReferenceFromChildrenBlock (ExplicitBlock block)
214 if (children_references == null)
215 children_references = new ArrayList ();
217 if (!children_references.Contains (block))
218 children_references.Add (block);
221 public void AddParentStoreyReference (AnonymousMethodStorey storey)
223 CheckMembersDefined ();
225 if (used_parent_storeys == null)
226 used_parent_storeys = new ArrayList ();
227 else if (used_parent_storeys.IndexOf (storey) != -1)
228 return;
230 TypeExpr type_expr = new TypeExpression (storey.TypeBuilder, Location);
231 Field f = AddCompilerGeneratedField ("<>f__ref$" + storey.ID, type_expr);
232 used_parent_storeys.Add (new StoreyFieldPair (storey, f));
235 public void CaptureLocalVariable (EmitContext ec, LocalInfo local_info)
237 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
238 if (ec.CurrentBlock.Explicit != local_info.Block.Explicit)
239 AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
241 if (local_info.HoistedVariableReference != null)
242 return;
244 HoistedVariable var = new HoistedLocalVariable (this, local_info, GetVariableMangledName (local_info));
245 local_info.HoistedVariableReference = var;
247 if (hoisted_locals == null)
248 hoisted_locals = new ArrayList ();
250 hoisted_locals.Add (var);
253 public void CaptureParameter (EmitContext ec, ParameterReference param_ref)
255 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
256 AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
258 if (param_ref.GetHoistedVariable (ec) != null)
259 return;
261 if (hoisted_params == null)
262 hoisted_params = new ArrayList (2);
264 HoistedVariable expr = new HoistedParameter (this, param_ref);
265 param_ref.Parameter.HoistedVariableReference = expr;
266 hoisted_params.Add (expr);
269 public void ChangeParentStorey (AnonymousMethodStorey parentStorey)
271 Parent = parentStorey;
272 type_params = null;
276 // Initializes all hoisted variables
278 public void EmitStoreyInstantiation (EmitContext ec)
280 // There can be only one instance variable for each storey type
281 if (Instance != null)
282 throw new InternalErrorException ();
284 SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
287 // Create an instance of storey type
289 Expression storey_type_expr;
290 if (is_generic) {
292 // Use current method type parameter (MVAR) for top level storey only. All
293 // nested storeys use class type parameter (VAR)
295 TypeParameter[] tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
296 ec.CurrentAnonymousMethod.Storey.TypeParameters :
297 ec.GenericDeclContainer.TypeParameters;
299 TypeArguments targs = new TypeArguments ();
301 if (tparams.Length < CountTypeParameters) {
302 TypeParameter[] parent_tparams = ec.DeclContainer.Parent.PartialContainer.TypeParameters;
303 for (int i = 0; i < parent_tparams.Length; ++i)
304 targs.Add (new TypeParameterExpr (parent_tparams[i], Location));
307 for (int i = 0; i < tparams.Length; ++i)
308 targs.Add (new TypeParameterExpr (tparams[i], Location));
310 storey_type_expr = new GenericTypeExpr (TypeBuilder, targs, Location);
311 } else {
312 storey_type_expr = new TypeExpression (TypeBuilder, Location);
315 Expression e = new New (storey_type_expr, null, Location).Resolve (ec);
316 e.Emit (ec);
318 Instance = new LocalTemporary (storey_type_expr.Type);
319 Instance.Store (ec);
321 EmitHoistedFieldsInitialization (ec);
323 SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
324 SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
327 void EmitHoistedFieldsInitialization (EmitContext ec)
330 // Initialize all storey reference fields by using local or hoisted variables
332 if (used_parent_storeys != null) {
333 foreach (StoreyFieldPair sf in used_parent_storeys) {
335 // Setting local field
337 Expression instace_expr = GetStoreyInstanceExpression (ec);
338 FieldExpr f_set_expr = TypeManager.IsGenericType (instace_expr.Type) ?
339 new FieldExpr (sf.Field.FieldBuilder, instace_expr.Type, Location) :
340 new FieldExpr (sf.Field.FieldBuilder, Location);
341 f_set_expr.InstanceExpression = instace_expr;
343 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
344 if (a.Resolve (ec) != null)
345 a.EmitStatement (ec);
350 // Define hoisted `this' in top-level storey only
352 if (OriginalSourceBlock.Explicit.HasCapturedThis && !(Parent is AnonymousMethodStorey)) {
353 AddCapturedThisField (ec);
354 OriginalSourceBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
358 // Setting currect anonymous method to null blocks any further variable hoisting
360 AnonymousExpression ae = ec.CurrentAnonymousMethod;
361 ec.CurrentAnonymousMethod = null;
363 if (hoisted_params != null) {
364 EmitHoistedParameters (ec, hoisted_params);
367 ec.CurrentAnonymousMethod = ae;
370 protected virtual void EmitHoistedParameters (EmitContext ec, ArrayList hoisted)
372 foreach (HoistedParameter hp in hoisted) {
373 hp.EmitHoistingAssignment (ec);
377 public override void EmitType ()
379 SymbolWriter.DefineAnonymousScope (ID);
381 if (hoisted_this != null)
382 hoisted_this.EmitSymbolInfo ();
384 if (hoisted_locals != null) {
385 foreach (HoistedVariable local in hoisted_locals)
386 local.EmitSymbolInfo ();
389 if (hoisted_params != null) {
390 foreach (HoistedParameter param in hoisted_params)
391 param.EmitSymbolInfo ();
394 if (used_parent_storeys != null) {
395 foreach (StoreyFieldPair sf in used_parent_storeys) {
396 SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
400 base.EmitType ();
403 public AnonymousMethodStorey GetGenericStorey ()
405 DeclSpace storey = this;
406 while (storey != null && storey.CurrentTypeParameters.Length == 0)
407 storey = storey.Parent;
409 return storey as AnonymousMethodStorey;
413 // Returns a field which holds referenced storey instance
415 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
417 if (used_parent_storeys == null)
418 return null;
420 foreach (StoreyFieldPair sf in used_parent_storeys) {
421 if (sf.Storey == storey)
422 return sf.Field;
425 return null;
429 // Creates storey instance expression regardless of currect IP
431 public Expression GetStoreyInstanceExpression (EmitContext ec)
433 AnonymousExpression am = ec.CurrentAnonymousMethod;
436 // Access from original block -> storey
438 if (am == null)
439 return Instance;
442 // Access from anonymous method implemented as a static -> storey
444 if (am.Storey == null)
445 return Instance;
447 Field f = am.Storey.GetReferencedStoreyField (this);
448 if (f == null) {
449 if (am.Storey == this) {
451 // Access inside of same storey (S -> S)
453 return new CompilerGeneratedThis (TypeBuilder, Location);
456 // External field access
458 return Instance;
462 // Storey was cached to local field
464 FieldExpr f_ind = new FieldExpr (f.FieldBuilder, Location);
465 f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
466 return f_ind;
469 protected virtual string GetVariableMangledName (LocalInfo local_info)
472 // No need to mangle anonymous method hoisted variables cause they
473 // are hoisted in their own scopes
475 return local_info.Name;
478 public HoistedThis HoistedThis {
479 get { return hoisted_this; }
483 // Mutate type dispatcher
485 public Type MutateType (Type type)
487 #if GMCS_SOURCE
488 if (TypeManager.IsGenericType (type))
489 return MutateGenericType (type);
491 if (TypeManager.IsGenericParameter (type))
492 return MutateGenericArgument (type);
494 if (type.IsArray)
495 return MutateArrayType (type);
496 #endif
497 return type;
501 // Changes method type arguments (MVAR) to storey (VAR) type arguments
503 public MethodInfo MutateGenericMethod (MethodInfo method)
505 #if GMCS_SOURCE
506 Type [] t_args = TypeManager.GetGenericArguments (method);
507 if (TypeManager.IsGenericType (method.DeclaringType)) {
508 Type t = MutateGenericType (method.DeclaringType);
509 if (t != method.DeclaringType) {
510 method = (MethodInfo) TypeManager.DropGenericMethodArguments (method);
511 if (method.Module == Module.Builder)
512 method = TypeBuilder.GetMethod (t, method);
513 else
514 method = (MethodInfo) MethodInfo.GetMethodFromHandle (method.MethodHandle, t.TypeHandle);
518 if (t_args == null || t_args.Length == 0)
519 return method;
521 for (int i = 0; i < t_args.Length; ++i)
522 t_args [i] = MutateType (t_args [i]);
524 return method.GetGenericMethodDefinition ().MakeGenericMethod (t_args);
525 #else
526 throw new NotSupportedException ();
527 #endif
530 public ConstructorInfo MutateConstructor (ConstructorInfo ctor)
532 #if GMCS_SOURCE
533 if (TypeManager.IsGenericType (ctor.DeclaringType)) {
534 Type t = MutateGenericType (ctor.DeclaringType);
535 if (t != ctor.DeclaringType) {
536 ctor = (ConstructorInfo) TypeManager.DropGenericMethodArguments (ctor);
537 if (ctor.Module == Module.Builder)
538 return TypeBuilder.GetConstructor (t, ctor);
540 return (ConstructorInfo) ConstructorInfo.GetMethodFromHandle (ctor.MethodHandle, t.TypeHandle);
543 #endif
544 return ctor;
547 public FieldInfo MutateField (FieldInfo field)
549 #if GMCS_SOURCE
550 if (TypeManager.IsGenericType (field.DeclaringType)) {
551 Type t = MutateGenericType (field.DeclaringType);
552 if (t != field.DeclaringType) {
553 field = TypeManager.DropGenericTypeArguments (field.DeclaringType).GetField (field.Name, TypeManager.AllMembers);
554 if (field.Module == Module.Builder)
555 return TypeBuilder.GetField (t, field);
557 return FieldInfo.GetFieldFromHandle (field.FieldHandle, t.TypeHandle);
560 #endif
561 return field;
564 #if GMCS_SOURCE
565 protected Type MutateArrayType (Type array)
567 Type element = TypeManager.GetElementType (array);
568 if (element.IsArray) {
569 element = MutateArrayType (element);
570 } else if (TypeManager.IsGenericParameter (element)) {
571 element = MutateGenericArgument (element);
572 } else if (TypeManager.IsGenericType (element)) {
573 element = MutateGenericType (element);
574 } else {
575 return array;
578 int rank = array.GetArrayRank ();
579 if (rank == 1)
580 return element.MakeArrayType ();
582 return element.MakeArrayType (rank);
585 protected Type MutateGenericType (Type type)
587 Type [] t_args = TypeManager.GetTypeArguments (type);
588 if (t_args == null || t_args.Length == 0)
589 return type;
591 for (int i = 0; i < t_args.Length; ++i)
592 t_args [i] = MutateType (t_args [i]);
594 return TypeManager.DropGenericTypeArguments (type).MakeGenericType (t_args);
596 #endif
599 // Changes method generic argument (MVAR) to type generic argument (VAR)
601 public Type MutateGenericArgument (Type type)
603 foreach (TypeParameter tp in CurrentTypeParameters) {
604 if (tp.Name == type.Name) {
605 return tp.Type;
609 return type;
612 public ArrayList ReferencesFromChildrenBlock {
613 get { return children_references; }
616 public static void Reset ()
618 unique_id = 0;
622 public abstract class HoistedVariable
624 class ExpressionTreeProxy : Expression
626 readonly HoistedVariable hv;
628 public ExpressionTreeProxy (HoistedVariable hv)
630 this.hv = hv;
633 public override Expression CreateExpressionTree (EmitContext ec)
635 throw new NotSupportedException ("ET");
638 public override Expression DoResolve (EmitContext ec)
640 eclass = ExprClass.Value;
641 type = TypeManager.expression_type_expr.Type;
642 return this;
645 public override void Emit (EmitContext ec)
647 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (ec);
648 // This should never fail
649 e = e.Resolve (ec);
650 if (e != null)
651 e.Emit (ec);
655 protected readonly AnonymousMethodStorey storey;
656 protected Field field;
657 Hashtable cached_inner_access; // TODO: Hashtable is too heavyweight
658 FieldExpr cached_outer_access;
660 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
661 : this (storey, storey.AddCapturedVariable (name, type))
665 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
667 this.storey = storey;
668 this.field = field;
671 public void AddressOf (EmitContext ec, AddressOp mode)
673 GetFieldExpression (ec).AddressOf (ec, mode);
676 public Expression CreateExpressionTree (EmitContext ec)
678 return new ExpressionTreeProxy (this);
681 public void Emit (EmitContext ec)
683 GetFieldExpression (ec).Emit (ec);
687 // Creates field access expression for hoisted variable
689 protected FieldExpr GetFieldExpression (EmitContext ec)
691 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
692 if (cached_outer_access != null)
693 return cached_outer_access;
696 // When setting top-level hoisted variable in generic storey
697 // change storey generic types to method generic types (VAR -> MVAR)
699 cached_outer_access = storey.MemberName.IsGeneric ?
700 new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
701 new FieldExpr (field.FieldBuilder, field.Location);
703 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
704 cached_outer_access.Resolve (ec);
705 return cached_outer_access;
708 FieldExpr inner_access;
709 if (cached_inner_access != null) {
710 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
711 } else {
712 inner_access = null;
713 cached_inner_access = new Hashtable (4);
716 if (inner_access == null) {
717 // TODO: It should be something like this to work correctly with expression trees
718 // inner_access = ec.CurrentAnonymousMethod.Storey != storey && storey.MemberName.IsGeneric ?
719 // new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
720 // new FieldExpr (field.FieldBuilder, field.Location);
722 inner_access = new FieldExpr (field.FieldBuilder, field.Location);
723 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
724 inner_access.Resolve (ec);
725 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
728 return inner_access;
731 public abstract void EmitSymbolInfo ();
733 public void Emit (EmitContext ec, bool leave_copy)
735 GetFieldExpression (ec).Emit (ec, leave_copy);
738 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
740 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
744 class HoistedParameter : HoistedVariable
746 sealed class HoistedFieldAssign : Assign
748 public HoistedFieldAssign (Expression target, Expression source)
749 : base (target, source, source.Location)
753 protected override Expression ResolveConversions (EmitContext ec)
756 // Implicit conversion check fails for hoisted type arguments
757 // as they are of different types (!!0 x !0)
759 return this;
763 readonly ParameterReference parameter;
765 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
766 : base (scope, par.Name, par.Type)
768 this.parameter = par;
771 public HoistedParameter (HoistedParameter hp, string name)
772 : base (hp.storey, name, hp.parameter.Type)
774 this.parameter = hp.parameter;
777 public void EmitHoistingAssignment (EmitContext ec)
780 // Remove hoisted redirection to emit assignment from original parameter
782 HoistedVariable temp = parameter.Parameter.HoistedVariableReference;
783 parameter.Parameter.HoistedVariableReference = null;
785 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
786 if (a.Resolve (ec) != null)
787 a.EmitStatement (ec);
789 parameter.Parameter.HoistedVariableReference = temp;
792 public override void EmitSymbolInfo ()
794 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
797 public Field Field {
798 get { return field; }
802 class HoistedLocalVariable : HoistedVariable
804 readonly string name;
806 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
807 : base (scope, name, local.VariableType)
809 this.name = local.Name;
812 public override void EmitSymbolInfo ()
814 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
818 public class HoistedThis : HoistedVariable
820 public HoistedThis (AnonymousMethodStorey storey, Field field)
821 : base (storey, field)
825 public void EmitHoistingAssignment (EmitContext ec)
827 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), ec.GetThis (field.Location));
828 if (a.Resolve (ec) != null)
829 a.EmitStatement (ec);
832 public override void EmitSymbolInfo ()
834 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
837 public Field Field {
838 get { return field; }
843 // Anonymous method expression as created by parser
845 public class AnonymousMethodExpression : Expression
847 ListDictionary compatibles;
848 public ToplevelBlock Block;
850 public AnonymousMethodExpression (Location loc)
852 this.loc = loc;
853 this.compatibles = new ListDictionary ();
856 public override string ExprClassName {
857 get {
858 return "anonymous method";
862 public virtual bool HasExplicitParameters {
863 get {
864 return Parameters != ParametersCompiled.Undefined;
868 public ParametersCompiled Parameters {
869 get { return Block.Parameters; }
873 // Returns true if the body of lambda expression can be implicitly
874 // converted to the delegate of type `delegate_type'
876 public bool ImplicitStandardConversionExists (EmitContext ec, Type delegate_type)
878 using (ec.With (EmitContext.Flags.InferReturnType, false)) {
879 using (ec.Set (EmitContext.Flags.ProbingMode)) {
880 return Compatible (ec, delegate_type) != null;
885 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
887 if (TypeManager.IsDelegateType (delegate_type))
888 return delegate_type;
890 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
891 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
892 if (TypeManager.IsDelegateType (delegate_type))
893 return delegate_type;
895 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
896 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
897 return null;
900 Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
901 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
902 return null;
905 protected bool VerifyExplicitParameters (Type delegate_type, AParametersCollection parameters, bool ignore_error)
907 if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
908 return true;
910 if (!ignore_error)
911 Report.Error (1661, loc,
912 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
913 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
915 return false;
918 protected bool VerifyParameterCompatibility (Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
920 if (Parameters.Count != invoke_pd.Count) {
921 if (ignore_errors)
922 return false;
924 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
925 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
926 return false;
929 bool has_implicit_parameters = !HasExplicitParameters;
930 bool error = false;
932 for (int i = 0; i < Parameters.Count; ++i) {
933 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
934 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
935 if (ignore_errors)
936 return false;
938 if (p_mod == Parameter.Modifier.NONE)
939 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
940 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
941 else
942 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
943 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
944 error = true;
947 if (has_implicit_parameters)
948 continue;
950 Type type = invoke_pd.Types [i];
952 // We assume that generic parameters are always inflated
953 if (TypeManager.IsGenericParameter (type))
954 continue;
956 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
957 continue;
959 if (invoke_pd.Types [i] != Parameters.Types [i]) {
960 if (ignore_errors)
961 return false;
963 Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
964 (i+1).ToString (),
965 TypeManager.CSharpName (Parameters.Types [i]),
966 TypeManager.CSharpName (invoke_pd.Types [i]));
967 error = true;
971 return !error;
975 // Infers type arguments based on explicit arguments
977 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
979 if (!HasExplicitParameters)
980 return false;
982 if (!TypeManager.IsDelegateType (delegate_type)) {
983 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
984 return false;
986 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
987 if (!TypeManager.IsDelegateType (delegate_type))
988 return false;
991 AParametersCollection d_params = TypeManager.GetDelegateParameters (delegate_type);
992 if (d_params.Count != Parameters.Count)
993 return false;
995 for (int i = 0; i < Parameters.Count; ++i) {
996 Type itype = d_params.Types [i];
997 if (!TypeManager.IsGenericParameter (itype)) {
998 if (!TypeManager.HasElementType (itype))
999 continue;
1001 if (!TypeManager.IsGenericParameter (TypeManager.GetElementType (itype)))
1002 continue;
1004 type_inference.ExactInference (Parameters.Types [i], itype);
1006 return true;
1009 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1011 AnonymousMethodBody am;
1012 using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
1013 am = CompatibleMethod (ec, tic, TypeManager.null_type, delegate_type);
1016 if (am == null)
1017 return null;
1019 // Stop referencing gmcs NullLiteral type
1020 if (am.ReturnType == TypeManager.null_type)
1021 am.ReturnType = null;
1023 return am.ReturnType;
1027 // Returns AnonymousMethod container if this anonymous method
1028 // expression can be implicitly converted to the delegate type `delegate_type'
1030 public Expression Compatible (EmitContext ec, Type type)
1032 Expression am = (Expression) compatibles [type];
1033 if (am != null)
1034 return am;
1036 Type delegate_type = CompatibleChecks (ec, type);
1037 if (delegate_type == null)
1038 return null;
1041 // At this point its the first time we know the return type that is
1042 // needed for the anonymous method. We create the method here.
1045 MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1046 ec.ContainerType, delegate_type);
1047 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1049 #if MS_COMPATIBLE
1050 Type[] g_args = delegate_type.GetGenericArguments ();
1051 if (return_type.IsGenericParameter)
1052 return_type = g_args [return_type.GenericParameterPosition];
1053 #endif
1056 // Second: the return type of the delegate must be compatible with
1057 // the anonymous type. Instead of doing a pass to examine the block
1058 // we satisfy the rule by setting the return type on the EmitContext
1059 // to be the delegate type return type.
1062 try {
1063 int errors = Report.Errors;
1064 am = CompatibleMethod (ec, null, return_type, delegate_type);
1065 if (am != null && delegate_type != type && errors == Report.Errors)
1066 am = CreateExpressionTree (ec, delegate_type);
1068 if (!ec.IsInProbingMode)
1069 compatibles.Add (type, am == null ? EmptyExpression.Null : am);
1071 return am;
1072 } catch (CompletionResult){
1073 throw;
1074 } catch (Exception e) {
1075 throw new InternalErrorException (e, loc);
1079 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1081 return CreateExpressionTree (ec);
1084 public override Expression CreateExpressionTree (EmitContext ec)
1086 Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1087 return null;
1090 protected virtual ParametersCompiled ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1092 AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1094 if (Parameters == ParametersCompiled.Undefined) {
1096 // We provide a set of inaccessible parameters
1098 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1100 for (int i = 0; i < delegate_parameters.Count; i++) {
1101 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1102 if (i_mod == Parameter.Modifier.OUT) {
1103 Report.Error (1688, loc, "Cannot convert anonymous " +
1104 "method block without a parameter list " +
1105 "to delegate type `{0}' because it has " +
1106 "one or more `out' parameters.",
1107 TypeManager.CSharpName (delegate_type));
1108 return null;
1110 fixedpars[i] = new Parameter (
1111 null, null,
1112 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1115 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1118 if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1119 return null;
1122 return Parameters;
1125 public override Expression DoResolve (EmitContext ec)
1127 if (!ec.IsAnonymousMethodAllowed) {
1128 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1129 return null;
1133 // Set class type, set type
1136 eclass = ExprClass.Value;
1139 // This hack means `The type is not accessible
1140 // anywhere', we depend on special conversion
1141 // rules.
1143 type = InternalType.AnonymousMethod;
1145 if ((Parameters != null) && !Parameters.Resolve (ec))
1146 return null;
1148 // FIXME: The emitted code isn't very careful about reachability
1149 // so, ensure we have a 'ret' at the end
1150 if (ec.CurrentBranching != null &&
1151 ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
1152 ec.NeedReturnLabel ();
1154 return this;
1157 public override void Emit (EmitContext ec)
1159 // nothing, as we only exist to not do anything.
1162 public static void Error_AddressOfCapturedVar (IVariableReference var, Location loc)
1164 Report.Error (1686, loc,
1165 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1166 var.Name);
1169 public override string GetSignatureForError ()
1171 return ExprClassName;
1174 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1176 ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1177 if (p == null)
1178 return null;
1180 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1182 AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1183 if (!anonymous.Compatible (ec))
1184 return null;
1186 return anonymous;
1189 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, ParametersCompiled p, ToplevelBlock b)
1191 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1194 protected override void CloneTo (CloneContext clonectx, Expression t)
1196 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1198 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1203 // Abstract expression for any block which requires variables hoisting
1205 public abstract class AnonymousExpression : Expression
1207 protected class AnonymousMethodMethod : Method
1209 public readonly AnonymousExpression AnonymousMethod;
1210 public readonly AnonymousMethodStorey Storey;
1211 readonly string RealName;
1213 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1214 GenericMethod generic, TypeExpr return_type,
1215 int mod, string real_name, MemberName name,
1216 ParametersCompiled parameters)
1217 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1218 name, parameters, null)
1220 this.AnonymousMethod = am;
1221 this.Storey = storey;
1222 this.RealName = real_name;
1224 Parent.PartialContainer.AddMethod (this);
1225 Block = am.Block;
1228 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1230 EmitContext aec = AnonymousMethod.aec;
1231 aec.ig = ig;
1232 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1233 return aec;
1236 protected override bool ResolveMemberType ()
1238 if (!base.ResolveMemberType ())
1239 return false;
1241 if (Storey != null && Storey.IsGeneric) {
1242 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1243 if (gstorey != null) {
1244 if (!Parameters.IsEmpty) {
1245 Type [] ptypes = Parameters.Types;
1246 for (int i = 0; i < ptypes.Length; ++i)
1247 ptypes [i] = gstorey.MutateType (ptypes [i]);
1250 member_type = gstorey.MutateType (member_type);
1254 return true;
1257 public override void Emit ()
1260 // Before emitting any code we have to change all MVAR references to VAR
1261 // when the method is of generic type and has hoisted variables
1263 if (Storey == Parent && Storey.IsGeneric) {
1264 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1265 if (gstorey != null) {
1266 AnonymousMethod.aec.ReturnType = gstorey.MutateType (ReturnType);
1267 block.MutateHoistedGenericType (gstorey);
1271 if (MethodBuilder == null) {
1272 Define ();
1275 base.Emit ();
1278 public override void EmitExtraSymbolInfo (SourceMethod source)
1280 source.SetRealMethodName (RealName);
1285 // The block that makes up the body for the anonymous method
1287 protected readonly ToplevelBlock Block;
1289 public Type ReturnType;
1290 protected EmitContext aec;
1292 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1294 this.ReturnType = return_type;
1295 this.Block = block;
1296 this.loc = loc;
1299 public abstract string ContainerType { get; }
1300 public abstract bool IsIterator { get; }
1301 public abstract AnonymousMethodStorey Storey { get; }
1303 public bool Compatible (EmitContext ec)
1305 // TODO: Implement clone
1306 aec = new EmitContext (
1307 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1308 Location, null, ReturnType,
1309 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1311 aec.CurrentAnonymousMethod = this;
1312 aec.IsStatic = ec.IsStatic;
1314 IDisposable aec_dispose = null;
1315 EmitContext.Flags flags = 0;
1316 if (ec.InferReturnType)
1317 flags |= EmitContext.Flags.InferReturnType;
1319 if (ec.IsInProbingMode)
1320 flags |= EmitContext.Flags.ProbingMode;
1322 if (ec.IsInFieldInitializer)
1323 flags |= EmitContext.Flags.InFieldInitializer;
1325 if (ec.IsInUnsafeScope)
1326 flags |= EmitContext.Flags.InUnsafe;
1328 // HACK: Flag with 0 cannot be set
1329 if (flags != 0)
1330 aec_dispose = aec.Set (flags);
1332 bool unreachable;
1333 bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1335 if (ec.InferReturnType)
1336 ReturnType = aec.ReturnType;
1338 if (aec_dispose != null) {
1339 aec_dispose.Dispose ();
1342 return res;
1345 public void SetHasThisAccess ()
1347 Block.HasCapturedThis = true;
1348 ExplicitBlock b = Block.Parent.Explicit;
1350 while (b != null) {
1351 if (b.HasCapturedThis)
1352 return;
1354 b.HasCapturedThis = true;
1355 b = b.Parent == null ? null : b.Parent.Explicit;
1360 public class AnonymousMethodBody : AnonymousExpression
1362 protected readonly ParametersCompiled parameters;
1363 AnonymousMethodStorey storey;
1365 AnonymousMethodMethod method;
1366 Field am_cache;
1368 static int unique_id;
1370 public AnonymousMethodBody (ParametersCompiled parameters,
1371 ToplevelBlock block, Type return_type, Type delegate_type,
1372 Location loc)
1373 : base (block, return_type, loc)
1375 this.type = delegate_type;
1376 this.parameters = parameters;
1379 public override string ContainerType {
1380 get { return "anonymous method"; }
1383 public override AnonymousMethodStorey Storey {
1384 get { return storey; }
1387 public override bool IsIterator {
1388 get { return false; }
1391 public override Expression CreateExpressionTree (EmitContext ec)
1393 Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1394 return null;
1397 bool Define (EmitContext ec)
1399 if (aec == null && !Compatible (ec))
1400 return false;
1402 return true;
1406 // Creates a host for the anonymous method
1408 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1411 // Anonymous method body can be converted to
1413 // 1, an instance method in current scope when only `this' is hoisted
1414 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1415 // 3, an instance method in compiler generated storey when any hoisted variable exists
1418 int modifiers;
1419 if (Block.HasCapturedVariable || Block.HasCapturedThis) {
1420 storey = FindBestMethodStorey ();
1421 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1422 } else {
1423 if (ec.CurrentAnonymousMethod != null)
1424 storey = ec.CurrentAnonymousMethod.Storey;
1426 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1429 DeclSpace parent = storey != null ? storey : ec.TypeContainer;
1431 MemberCore mc = ec.ResolveContext as MemberCore;
1432 string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1433 "m", null, unique_id++);
1435 MemberName member_name;
1436 GenericMethod generic_method;
1437 if (storey == null && mc.MemberName.IsGeneric) {
1438 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1440 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1441 new TypeExpression (ReturnType, Location), parameters);
1443 ArrayList list = new ArrayList ();
1444 foreach (TypeParameter tparam in ((IMethodData)mc).GenericMethod.CurrentTypeParameters) {
1445 if (tparam.Constraints != null)
1446 list.Add (tparam.Constraints.Clone ());
1448 generic_method.SetParameterInfo (list);
1449 } else {
1450 member_name = new MemberName (name, Location);
1451 generic_method = null;
1454 string real_name = String.Format (
1455 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1456 parameters.GetSignatureForError ());
1458 return new AnonymousMethodMethod (parent,
1459 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1460 real_name, member_name, parameters);
1463 public override Expression DoResolve (EmitContext ec)
1465 if (eclass == ExprClass.Invalid) {
1466 if (!Define (ec))
1467 return null;
1470 eclass = ExprClass.Value;
1471 return this;
1474 public override void Emit (EmitContext ec)
1477 // Use same anonymous method implementation for scenarios where same
1478 // code is used from multiple blocks, e.g. field initializers
1480 if (method == null) {
1482 // Delay an anonymous method definition to avoid emitting unused code
1483 // for unreachable blocks or expression trees
1485 method = DoCreateMethodHost (ec);
1486 method.Define ();
1489 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1490 if (is_static && am_cache == null) {
1492 // Creates a field cache to store delegate instance if it's not generic
1494 if (!method.MemberName.IsGeneric) {
1495 TypeContainer parent = method.Parent.PartialContainer;
1496 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1497 am_cache = new Field (parent, new TypeExpression (type, loc),
1498 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1499 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1500 am_cache.Define ();
1501 parent.AddField (am_cache);
1502 } else {
1503 // TODO: Implement caching of generated generic static methods
1505 // Idea:
1507 // Some extra class is needed to capture variable generic type
1508 // arguments. Maybe we could re-use anonymous types, with a unique
1509 // anonymous method id, but they are quite heavy.
1511 // Consider : "() => typeof(T);"
1513 // We need something like
1514 // static class Wrap<Tn, Tm, DelegateType> {
1515 // public static DelegateType cache;
1516 // }
1518 // We then specialize local variable to capture all generic parameters
1519 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1524 ILGenerator ig = ec.ig;
1525 Label l_initialized = ig.DefineLabel ();
1527 if (am_cache != null) {
1528 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1529 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1533 // Load method delegate implementation
1536 if (is_static) {
1537 ig.Emit (OpCodes.Ldnull);
1538 } else if (storey != null) {
1539 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1540 if (e != null)
1541 e.Emit (ec);
1542 } else {
1543 ig.Emit (OpCodes.Ldarg_0);
1546 MethodInfo delegate_method = method.MethodBuilder;
1547 if (storey != null && storey.MemberName.IsGeneric) {
1548 Type t = storey.Instance.Type;
1551 // Mutate anonymous method instance type if we are in nested
1552 // hoisted generic anonymous method storey
1554 if (ec.CurrentAnonymousMethod != null &&
1555 ec.CurrentAnonymousMethod.Storey != null &&
1556 ec.CurrentAnonymousMethod.Storey.IsGeneric) {
1557 t = storey.GetGenericStorey ().MutateType (t);
1560 #if GMCS_SOURCE
1561 delegate_method = TypeBuilder.GetMethod (t, delegate_method);
1562 #else
1563 throw new NotSupportedException ();
1564 #endif
1567 ig.Emit (OpCodes.Ldftn, delegate_method);
1569 ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1570 #if MS_COMPATIBLE
1571 if (type.IsGenericType && type is TypeBuilder)
1572 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1573 #endif
1574 ig.Emit (OpCodes.Newobj, constructor_method);
1576 if (am_cache != null) {
1577 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1578 ig.MarkLabel (l_initialized);
1579 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1584 // Look for the best storey for this anonymous method
1586 AnonymousMethodStorey FindBestMethodStorey ()
1589 // Use the nearest parent block which has a storey
1591 for (Block b = Block.Parent; b != null; b = b.Parent) {
1592 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1593 if (s != null)
1594 return s;
1597 return null;
1600 public override string GetSignatureForError ()
1602 return TypeManager.CSharpName (type);
1605 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1607 type = storey.MutateType (type);
1610 public static void Reset ()
1612 unique_id = 0;
1617 // Anonymous type container
1619 public class AnonymousTypeClass : CompilerGeneratedClass
1621 sealed class AnonymousParameters : ParametersCompiled
1623 public AnonymousParameters (params Parameter[] parameters)
1624 : base (parameters)
1628 protected override void ErrorDuplicateName (Parameter p)
1630 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1631 p.Name);
1635 static int types_counter;
1636 public const string ClassNamePrefix = "<>__AnonType";
1637 public const string SignatureForError = "anonymous type";
1639 readonly ArrayList parameters;
1641 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1642 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1644 this.parameters = parameters;
1647 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1649 if (RootContext.MetadataCompatibilityVersion < MetadataVersion.v2)
1650 Report.FeatureIsNotSupported (loc, "anonymous types");
1652 string name = ClassNamePrefix + types_counter++;
1654 SimpleName [] t_args = new SimpleName [parameters.Count];
1655 TypeParameterName [] t_params = new TypeParameterName [parameters.Count];
1656 Parameter [] ctor_params = new Parameter [parameters.Count];
1657 for (int i = 0; i < parameters.Count; ++i) {
1658 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1660 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1661 t_params [i] = new TypeParameterName (t_args [i].Name, null, p.Location);
1662 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1666 // Create generic anonymous type host with generic arguments
1667 // named upon properties names
1669 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1670 new MemberName (name, new TypeArguments (t_params), loc), parameters, loc);
1672 if (parameters.Count > 0)
1673 a_type.SetParameterInfo (null);
1675 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1676 null, new AnonymousParameters (ctor_params), null, loc);
1677 c.Block = new ToplevelBlock (c.Parameters, loc);
1680 // Create fields and contructor body with field initialization
1682 bool error = false;
1683 for (int i = 0; i < parameters.Count; ++i) {
1684 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1686 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1687 new MemberName ("<" + p.Name + ">", p.Location), null);
1689 if (!a_type.AddField (f)) {
1690 error = true;
1691 continue;
1694 c.Block.AddStatement (new StatementExpression (
1695 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1696 c.Block.GetParameterReference (p.Name, p.Location))));
1698 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1699 get_block.AddStatement (new Return (
1700 new MemberAccess (new This (p.Location), f.Name), p.Location));
1701 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1702 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1703 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1704 a_type.AddProperty (prop);
1707 if (error)
1708 return null;
1710 a_type.AddConstructor (c);
1711 return a_type;
1714 public static void Reset ()
1716 types_counter = 0;
1719 protected override bool AddToContainer (MemberCore symbol, string name)
1721 MemberCore mc = (MemberCore) defined_names [name];
1723 if (mc == null) {
1724 defined_names.Add (name, symbol);
1725 return true;
1728 Report.SymbolRelatedToPreviousError (mc);
1729 return false;
1732 void DefineOverrides ()
1734 Location loc = Location;
1736 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1737 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1738 Mono.CSharp.ParametersCompiled.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1740 Method tostring = new Method (this, null, TypeManager.system_string_expr,
1741 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1742 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1744 ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1745 TypeExpr current_type;
1746 if (IsGeneric)
1747 current_type = new GenericTypeExpr (this, loc);
1748 else
1749 current_type = new TypeExpression (TypeBuilder, loc);
1751 equals_block.AddVariable (current_type, "other", loc);
1752 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1754 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1755 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1757 Expression rs_equals = null;
1758 Expression string_concat = new StringConstant ("{", loc);
1759 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1760 for (int i = 0; i < parameters.Count; ++i) {
1761 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1762 Field f = (Field) Fields [i];
1764 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1765 system_collections_generic, "EqualityComparer",
1766 new TypeArguments (new SimpleName (TypeParameters [i].Name, loc)), loc),
1767 "Default", loc);
1769 Arguments arguments_equal = new Arguments (2);
1770 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1771 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1773 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1774 "Equals", loc), arguments_equal);
1776 Arguments arguments_hashcode = new Arguments (1);
1777 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1778 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1779 "GetHashCode", loc), arguments_hashcode);
1781 IntConstant FNV_prime = new IntConstant (16777619, loc);
1782 rs_hashcode = new Binary (Binary.Operator.Multiply,
1783 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1784 FNV_prime);
1786 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1787 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1788 new Invocation (new MemberAccess (
1789 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1790 new StringConstant (string.Empty, loc));
1792 if (rs_equals == null) {
1793 rs_equals = field_equal;
1794 string_concat = new Binary (Binary.Operator.Addition,
1795 string_concat,
1796 new Binary (Binary.Operator.Addition,
1797 new StringConstant (" " + p.Name + " = ", loc),
1798 field_to_string));
1799 continue;
1803 // Implementation of ToString () body using string concatenation
1805 string_concat = new Binary (Binary.Operator.Addition,
1806 new Binary (Binary.Operator.Addition,
1807 string_concat,
1808 new StringConstant (", " + p.Name + " = ", loc)),
1809 field_to_string);
1811 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1814 string_concat = new Binary (Binary.Operator.Addition,
1815 string_concat,
1816 new StringConstant (" }", loc));
1819 // Equals (object obj) override
1821 LocalVariableReference other_variable_assign = new LocalVariableReference (equals_block, "other", loc);
1822 equals_block.AddStatement (new StatementExpression (
1823 new SimpleAssign (other_variable_assign,
1824 new As (equals_block.GetParameterReference ("obj", loc),
1825 current_type, loc), loc)));
1827 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1828 if (rs_equals != null)
1829 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1830 equals_block.AddStatement (new Return (equals_test, loc));
1832 equals.Block = equals_block;
1833 equals.Define ();
1834 AddMethod (equals);
1837 // GetHashCode () override
1839 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1840 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1841 new MemberName ("GetHashCode", loc),
1842 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1845 // Modified FNV with good avalanche behavior and uniform
1846 // distribution with larger hash sizes.
1848 // const int FNV_prime = 16777619;
1849 // int hash = (int) 2166136261;
1850 // foreach (int d in data)
1851 // hash = (hash ^ d) * FNV_prime;
1852 // hash += hash << 13;
1853 // hash ^= hash >> 7;
1854 // hash += hash << 3;
1855 // hash ^= hash >> 17;
1856 // hash += hash << 5;
1858 ToplevelBlock hashcode_top = new ToplevelBlock (loc);
1859 Block hashcode_block = new Block (hashcode_top);
1860 hashcode_top.AddStatement (new Unchecked (hashcode_block));
1862 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1863 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1864 LocalVariableReference hash_variable_assign = new LocalVariableReference (hashcode_block, "hash", loc);
1865 hashcode_block.AddStatement (new StatementExpression (
1866 new SimpleAssign (hash_variable_assign, rs_hashcode)));
1868 hashcode_block.AddStatement (new StatementExpression (
1869 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1870 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1871 hashcode_block.AddStatement (new StatementExpression (
1872 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1873 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1874 hashcode_block.AddStatement (new StatementExpression (
1875 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1876 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1877 hashcode_block.AddStatement (new StatementExpression (
1878 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1879 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1880 hashcode_block.AddStatement (new StatementExpression (
1881 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1882 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1884 hashcode_block.AddStatement (new Return (hash_variable, loc));
1885 hashcode.Block = hashcode_top;
1886 hashcode.Define ();
1887 AddMethod (hashcode);
1890 // ToString () override
1893 ToplevelBlock tostring_block = new ToplevelBlock (loc);
1894 tostring_block.AddStatement (new Return (string_concat, loc));
1895 tostring.Block = tostring_block;
1896 tostring.Define ();
1897 AddMethod (tostring);
1900 public override bool Define ()
1902 if (!base.Define ())
1903 return false;
1905 DefineOverrides ();
1906 return true;
1909 public override string GetSignatureForError ()
1911 return SignatureForError;
1914 public ArrayList Parameters {
1915 get {
1916 return parameters;