Fix bug #566087.
[mcs.git] / mcs / dynamic.cs
blobc5fc2d29deab3caff3894c429bf999fa3b4ff593
1 //
2 // dynamic.cs: support for dynamic expressions
3 //
4 // Authors: Marek Safar (marek.safar@gmail.com)
5 //
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
7 //
8 // Copyright 2009 Novell, Inc
9 //
11 using System;
12 using System.Reflection.Emit;
13 using SLE = System.Linq.Expressions;
15 #if NET_4_0
16 using System.Dynamic;
17 #endif
19 namespace Mono.CSharp
22 // A copy of Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/CSharpBinderFlags.cs
23 // has to be kept in sync
25 [Flags]
26 public enum CSharpBinderFlags
28 None = 0,
29 CheckedContext = 1,
30 InvokeSimpleName = 1 << 1,
31 InvokeSpecialName = 1 << 2,
32 BinaryOperationLogical = 1 << 3,
33 ConvertExplicit = 1 << 4,
34 ConvertArrayIndex = 1 << 5,
35 ResultIndexed = 1 << 6,
36 ValueFromCompoundAssignment = 1 << 7,
37 ResultDiscarded = 1 << 8
41 // Type expression with internal dynamic type symbol
43 class DynamicTypeExpr : TypeExpr
45 public DynamicTypeExpr (Location loc)
47 this.loc = loc;
49 type = InternalType.Dynamic;
50 eclass = ExprClass.Type;
53 public override bool CheckAccessLevel (IMemberContext ds)
55 return true;
58 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
60 return this;
64 #region Dynamic runtime binder expressions
67 // Expression created from runtime dynamic object value by dynamic binder
69 public class RuntimeValueExpression : Expression, IDynamicAssign, IMemoryLocation
71 #if !NET_4_0
72 public class DynamicMetaObject
74 public Type RuntimeType;
75 public Type LimitType;
76 public SLE.Expression Expression;
78 #endif
80 readonly DynamicMetaObject obj;
82 public RuntimeValueExpression (DynamicMetaObject obj, bool isCompileTimeType)
84 this.obj = obj;
85 this.type = isCompileTimeType ? obj.LimitType : obj.RuntimeType;
86 this.type = obj.LimitType;
87 this.eclass = ExprClass.Variable;
90 public void AddressOf (EmitContext ec, AddressOp mode)
92 throw new NotImplementedException ();
95 public override Expression CreateExpressionTree (ResolveContext ec)
97 throw new NotImplementedException ();
100 protected override Expression DoResolve (ResolveContext ec)
102 return this;
105 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
107 return this;
110 public override void Emit (EmitContext ec)
112 throw new NotImplementedException ();
115 #region IAssignMethod Members
117 public void Emit (EmitContext ec, bool leave_copy)
119 throw new NotImplementedException ();
122 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
124 throw new NotImplementedException ();
127 #endregion
129 public SLE.Expression MakeAssignExpression (BuilderContext ctx)
131 return obj.Expression;
134 public override SLE.Expression MakeExpression (BuilderContext ctx)
136 return SLE.Expression.Convert (obj.Expression, type);
139 public DynamicMetaObject MetaObject {
140 get { return obj; }
145 // Wraps runtime dynamic expression into expected type. Needed
146 // to satify expected type check by dynamic binder and no conversion
147 // is required (ResultDiscarded).
149 public class DynamicResultCast : ShimExpression
151 public DynamicResultCast (Type type, Expression expr)
152 : base (expr)
154 this.type = type;
157 protected override Expression DoResolve (ResolveContext ec)
159 expr = expr.Resolve (ec);
160 eclass = ExprClass.Value;
161 return this;
164 #if NET_4_0
165 public override SLE.Expression MakeExpression (BuilderContext ctx)
167 return SLE.Expression.Block (expr.MakeExpression (ctx), SLE.Expression.Default (type));
169 #endif
172 #endregion
175 // Creates dynamic binder expression
177 interface IDynamicBinder
179 Expression CreateCallSiteBinder (ResolveContext ec, Arguments args);
183 // Extends standard assignment interface for expressions
184 // supported by dynamic resolver
186 interface IDynamicAssign : IAssignMethod
188 #if NET_4_0
189 SLE.Expression MakeAssignExpression (BuilderContext ctx);
190 #endif
194 // Base dynamic expression statement creator
196 class DynamicExpressionStatement : ExpressionStatement
198 class StaticDataClass : CompilerGeneratedClass
200 public StaticDataClass ()
201 : base (new RootDeclSpace (new NamespaceEntry (null, null, null)),
202 new MemberName (CompilerGeneratedClass.MakeName (null, "c", "DynamicSites", 0)),
203 Modifiers.INTERNAL | Modifiers.STATIC)
205 ModFlags &= ~Modifiers.SEALED;
210 // Binder flag dynamic constant, the value is combination of
211 // flags known at resolve stage and flags known only at emit
212 // stage
214 protected class BinderFlags : EnumConstant
216 DynamicExpressionStatement statement;
217 CSharpBinderFlags flags;
219 public BinderFlags (CSharpBinderFlags flags, DynamicExpressionStatement statement)
220 : base (statement.loc)
222 this.flags = flags;
223 this.statement = statement;
226 protected override Expression DoResolve (ResolveContext ec)
228 Child = new IntConstant ((int) (flags | statement.flags), statement.loc).Resolve (ec);
230 type = TypeManager.binder_flags;
231 eclass = Child.eclass;
232 return this;
236 static StaticDataClass global_site_container;
237 static int field_counter;
238 static int container_counter;
240 readonly Arguments arguments;
241 protected IDynamicBinder binder;
242 protected Expression binder_expr;
244 // Used by BinderFlags
245 protected CSharpBinderFlags flags;
247 public DynamicExpressionStatement (IDynamicBinder binder, Arguments args, Location loc)
249 this.binder = binder;
250 this.arguments = args;
251 this.loc = loc;
254 public Arguments Arguments {
255 get {
256 return arguments;
260 static TypeContainer CreateSiteContainer ()
262 if (global_site_container == null) {
263 global_site_container = new StaticDataClass ();
264 RootContext.ToplevelTypes.AddCompilerGeneratedClass (global_site_container);
265 global_site_container.DefineType ();
266 global_site_container.Define ();
267 // global_site_container.EmitType ();
269 RootContext.RegisterCompilerGeneratedType (global_site_container.TypeBuilder);
272 return global_site_container;
275 static Field CreateSiteField (FullNamedExpression type)
277 TypeContainer site_container = CreateSiteContainer ();
278 Field f = new Field (site_container, type, Modifiers.PUBLIC | Modifiers.STATIC,
279 new MemberName ("Site" + field_counter++), null);
280 f.Define ();
282 site_container.AddField (f);
283 return f;
286 public override Expression CreateExpressionTree (ResolveContext ec)
288 ec.Report.Error (1963, loc, "An expression tree cannot contain a dynamic operation");
289 return null;
292 protected override Expression DoResolve (ResolveContext ec)
294 if (DoResolveCore (ec))
295 binder_expr = binder.CreateCallSiteBinder (ec, arguments);
297 return this;
300 protected bool DoResolveCore (ResolveContext rc)
302 int errors = rc.Report.Errors;
304 if (TypeManager.binder_type == null) {
305 var t = TypeManager.CoreLookupType (rc.Compiler,
306 "Microsoft.CSharp.RuntimeBinder", "Binder", Kind.Class, true);
307 if (t != null)
308 TypeManager.binder_type = new TypeExpression (t, Location.Null);
311 if (TypeManager.call_site_type == null)
312 TypeManager.call_site_type = TypeManager.CoreLookupType (rc.Compiler,
313 "System.Runtime.CompilerServices", "CallSite", Kind.Class, true);
315 if (TypeManager.generic_call_site_type == null)
316 TypeManager.generic_call_site_type = TypeManager.CoreLookupType (rc.Compiler,
317 "System.Runtime.CompilerServices", "CallSite`1", Kind.Class, true);
319 if (TypeManager.binder_flags == null) {
320 TypeManager.binder_flags = TypeManager.CoreLookupType (rc.Compiler,
321 "Microsoft.CSharp.RuntimeBinder", "CSharpBinderFlags", Kind.Enum, true);
324 eclass = ExprClass.Value;
326 if (type == null)
327 type = InternalType.Dynamic;
329 if (rc.Report.Errors == errors)
330 return true;
332 rc.Report.Error (1969, loc,
333 "Dynamic operation cannot be compiled without `Microsoft.CSharp.dll' assembly reference");
334 return false;
337 public override void Emit (EmitContext ec)
339 EmitCall (ec, binder_expr, arguments, false);
342 public override void EmitStatement (EmitContext ec)
344 EmitCall (ec, binder_expr, arguments, true);
347 protected void EmitCall (EmitContext ec, Expression binder, Arguments arguments, bool isStatement)
349 int dyn_args_count = arguments == null ? 0 : arguments.Count;
350 TypeExpr site_type = CreateSiteType (RootContext.ToplevelTypes.Compiler, arguments, dyn_args_count, isStatement);
351 FieldExpr site_field_expr = new FieldExpr (CreateSiteField (site_type).FieldBuilder, loc);
353 SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
355 Arguments args = new Arguments (1);
356 args.Add (new Argument (binder));
357 StatementExpression s = new StatementExpression (new SimpleAssign (site_field_expr, new Invocation (new MemberAccess (site_type, "Create"), args)));
359 BlockContext bc = new BlockContext (ec.MemberContext, null, TypeManager.void_type);
360 if (s.Resolve (bc)) {
361 Statement init = new If (new Binary (Binary.Operator.Equality, site_field_expr, new NullLiteral (loc)), s, loc);
362 init.Emit (ec);
365 args = new Arguments (1 + dyn_args_count);
366 args.Add (new Argument (site_field_expr));
367 if (arguments != null) {
368 foreach (Argument a in arguments) {
369 if (a is NamedArgument) {
370 // Name is not valid in this context
371 args.Add (new Argument (a.Expr, a.ArgType));
372 continue;
375 args.Add (a);
379 Expression target = new DelegateInvocation (new MemberAccess (site_field_expr, "Target", loc).Resolve (bc), args, loc).Resolve (bc);
380 if (target != null)
381 target.Emit (ec);
383 SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
386 public static MemberAccess GetBinderNamespace (Location loc)
388 return new MemberAccess (new MemberAccess (
389 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "Microsoft", loc), "CSharp", loc), "RuntimeBinder", loc);
392 public static MemberAccess GetBinder (string name, Location loc)
394 return new MemberAccess (TypeManager.binder_type, name, loc);
397 TypeExpr CreateSiteType (CompilerContext ctx, Arguments arguments, int dyn_args_count, bool is_statement)
399 int default_args = is_statement ? 1 : 2;
401 bool has_ref_out_argument = false;
402 FullNamedExpression[] targs = new FullNamedExpression[dyn_args_count + default_args];
403 targs [0] = new TypeExpression (TypeManager.call_site_type, loc);
404 for (int i = 0; i < dyn_args_count; ++i) {
405 Type arg_type;
406 Argument a = arguments [i];
407 if (a.Type == TypeManager.null_type)
408 arg_type = TypeManager.object_type;
409 else
410 arg_type = a.Type;
412 if (a.ArgType == Argument.AType.Out || a.ArgType == Argument.AType.Ref)
413 has_ref_out_argument = true;
415 targs [i + 1] = new TypeExpression (arg_type, loc);
418 TypeExpr del_type = null;
419 if (!has_ref_out_argument) {
420 string d_name = is_statement ? "Action`" : "Func`";
422 Type t = TypeManager.CoreLookupType (ctx, "System", d_name + (dyn_args_count + default_args), Kind.Delegate, false);
423 if (t != null) {
424 if (!is_statement)
425 targs [targs.Length - 1] = new TypeExpression (type, loc);
427 del_type = new GenericTypeExpr (t, new TypeArguments (targs), loc);
432 // Create custom delegate when no appropriate predefined one is found
434 if (del_type == null) {
435 Type rt = is_statement ? TypeManager.void_type : type;
436 Parameter[] p = new Parameter [dyn_args_count + 1];
437 p[0] = new Parameter (targs [0], "p0", Parameter.Modifier.NONE, null, loc);
439 for (int i = 1; i < dyn_args_count + 1; ++i)
440 p[i] = new Parameter (targs[i], "p" + i.ToString ("X"), arguments[i - 1].Modifier, null, loc);
442 TypeContainer parent = CreateSiteContainer ();
443 Delegate d = new Delegate (parent.NamespaceEntry, parent, new TypeExpression (rt, loc),
444 Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED,
445 new MemberName ("Container" + container_counter++.ToString ("X")),
446 new ParametersCompiled (ctx, p), null);
448 d.DefineType ();
449 d.Define ();
450 d.Emit ();
452 parent.AddDelegate (d);
453 del_type = new TypeExpression (d.TypeBuilder, loc);
456 TypeExpr site_type = new GenericTypeExpr (TypeManager.generic_call_site_type, new TypeArguments (del_type), loc);
457 return site_type;
460 public static void Reset ()
462 global_site_container = null;
463 field_counter = container_counter = 0;
468 // Dynamic member access compound assignment for events
470 class DynamicEventCompoundAssign : DynamicExpressionStatement, IDynamicBinder
472 string name;
473 Statement condition;
475 public DynamicEventCompoundAssign (string name, Arguments args, ExpressionStatement assignment, ExpressionStatement invoke, Location loc)
476 : base (null, args, loc)
478 this.name = name;
479 base.binder = this;
481 // Used by += or -= only
482 type = TypeManager.bool_type;
484 condition = new If (
485 new Binary (Binary.Operator.Equality, this, new BoolLiteral (true, loc)),
486 new StatementExpression (invoke), new StatementExpression (assignment),
487 loc);
490 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
492 Arguments binder_args = new Arguments (3);
494 binder_args.Add (new Argument (new BinderFlags (0, this)));
495 binder_args.Add (new Argument (new StringLiteral (name, loc)));
496 binder_args.Add (new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc)));
498 return new Invocation (GetBinder ("IsEvent", loc), binder_args);
501 public override void EmitStatement (EmitContext ec)
503 condition.Emit (ec);
507 class DynamicConversion : DynamicExpressionStatement, IDynamicBinder
509 public DynamicConversion (Type targetType, CSharpBinderFlags flags, Arguments args, Location loc)
510 : base (null, args, loc)
512 type = targetType;
513 base.flags = flags;
514 base.binder = this;
517 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
519 Arguments binder_args = new Arguments (2);
521 flags |= ec.HasSet (ResolveContext.Options.CheckedScope) ? CSharpBinderFlags.CheckedContext : 0;
523 binder_args.Add (new Argument (new BinderFlags (flags, this)));
524 binder_args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
525 return new Invocation (GetBinder ("Convert", loc), binder_args);
529 class DynamicConstructorBinder : DynamicExpressionStatement, IDynamicBinder
531 public DynamicConstructorBinder (Type type, Arguments args, Location loc)
532 : base (null, args, loc)
534 this.type = type;
535 base.binder = this;
538 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
540 Arguments binder_args = new Arguments (3);
542 binder_args.Add (new Argument (new BinderFlags (0, this)));
543 binder_args.Add (new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc)));
544 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation ("[]", args.CreateDynamicBinderArguments (ec), loc)));
546 return new Invocation (GetBinder ("InvokeConstructor", loc), binder_args);
550 class DynamicIndexBinder : DynamicMemberAssignable
552 public DynamicIndexBinder (Arguments args, Location loc)
553 : base (args, loc)
557 protected override Expression CreateCallSiteBinder (ResolveContext ec, Arguments args, bool isSet)
559 Arguments binder_args = new Arguments (3);
561 binder_args.Add (new Argument (new BinderFlags (0, this)));
562 binder_args.Add (new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc)));
563 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation ("[]", args.CreateDynamicBinderArguments (ec), loc)));
565 return new Invocation (GetBinder (isSet ? "SetIndex" : "GetIndex", loc), binder_args);
569 class DynamicInvocation : DynamicExpressionStatement, IDynamicBinder
571 ATypeNameExpression member;
573 public DynamicInvocation (ATypeNameExpression member, Arguments args, Location loc)
574 : base (null, args, loc)
576 base.binder = this;
577 this.member = member;
580 public DynamicInvocation (ATypeNameExpression member, Arguments args, Type type, Location loc)
581 : this (member, args, loc)
583 // When a return type is known not to be dynamic
584 this.type = type;
587 public static DynamicInvocation CreateSpecialNameInvoke (ATypeNameExpression member, Arguments args, Location loc)
589 return new DynamicInvocation (member, args, loc) {
590 flags = CSharpBinderFlags.InvokeSpecialName
594 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
596 Arguments binder_args = new Arguments (member != null ? 5 : 3);
597 bool is_member_access = member is MemberAccess;
599 CSharpBinderFlags call_flags;
600 if (!is_member_access && member is SimpleName) {
601 call_flags = CSharpBinderFlags.InvokeSimpleName;
602 is_member_access = true;
603 } else {
604 call_flags = 0;
607 binder_args.Add (new Argument (new BinderFlags (call_flags, this)));
609 if (is_member_access)
610 binder_args.Add (new Argument (new StringLiteral (member.Name, member.Location)));
612 if (member != null && member.HasTypeArguments) {
613 TypeArguments ta = member.TypeArguments;
614 if (ta.Resolve (ec)) {
615 var targs = new ArrayInitializer (ta.Count, loc);
616 foreach (Type t in ta.Arguments)
617 targs.Add (new TypeOf (new TypeExpression (t, loc), loc));
619 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation ("[]", targs, loc)));
621 } else if (is_member_access) {
622 binder_args.Add (new Argument (new NullLiteral (loc)));
625 binder_args.Add (new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc)));
627 Expression real_args;
628 if (args == null) {
629 // Cannot be null because .NET trips over
630 real_args = new ArrayCreation (
631 new MemberAccess (GetBinderNamespace (loc), "CSharpArgumentInfo", loc), "[]",
632 new ArrayInitializer (0, loc), loc);
633 } else {
634 real_args = new ImplicitlyTypedArrayCreation ("[]", args.CreateDynamicBinderArguments (ec), loc);
637 binder_args.Add (new Argument (real_args));
639 return new Invocation (GetBinder (is_member_access ? "InvokeMember" : "Invoke", loc), binder_args);
642 public override void EmitStatement (EmitContext ec)
644 flags |= CSharpBinderFlags.ResultDiscarded;
645 base.EmitStatement (ec);
649 class DynamicMemberBinder : DynamicMemberAssignable
651 readonly string name;
653 public DynamicMemberBinder (string name, Arguments args, Location loc)
654 : base (args, loc)
656 this.name = name;
659 protected override Expression CreateCallSiteBinder (ResolveContext ec, Arguments args, bool isSet)
661 Arguments binder_args = new Arguments (4);
663 binder_args.Add (new Argument (new BinderFlags (0, this)));
664 binder_args.Add (new Argument (new StringLiteral (name, loc)));
665 binder_args.Add (new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc)));
666 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation ("[]", args.CreateDynamicBinderArguments (ec), loc)));
668 return new Invocation (GetBinder (isSet ? "SetMember" : "GetMember", loc), binder_args);
673 // Any member binder which can be source and target of assignment
675 abstract class DynamicMemberAssignable : DynamicExpressionStatement, IDynamicBinder, IAssignMethod
677 Expression setter;
678 Arguments setter_args;
680 protected DynamicMemberAssignable (Arguments args, Location loc)
681 : base (null, args, loc)
683 base.binder = this;
686 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
689 // DoResolve always uses getter
691 return CreateCallSiteBinder (ec, args, false);
694 protected abstract Expression CreateCallSiteBinder (ResolveContext ec, Arguments args, bool isSet);
696 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
698 if (right_side == EmptyExpression.OutAccess.Instance) {
699 right_side.DoResolveLValue (rc, this);
700 return null;
703 if (DoResolveCore (rc)) {
704 setter_args = new Arguments (Arguments.Count + 1);
705 setter_args.AddRange (Arguments);
706 setter_args.Add (new Argument (right_side));
707 setter = CreateCallSiteBinder (rc, setter_args, true);
710 eclass = ExprClass.Variable;
711 return this;
714 public override void Emit (EmitContext ec)
716 // It's null for ResolveLValue used without assignment
717 if (binder_expr == null)
718 EmitCall (ec, setter, Arguments, false);
719 else
720 base.Emit (ec);
723 public override void EmitStatement (EmitContext ec)
725 // It's null for ResolveLValue used without assignment
726 if (binder_expr == null)
727 EmitCall (ec, setter, Arguments, true);
728 else
729 base.EmitStatement (ec);
732 #region IAssignMethod Members
734 public void Emit (EmitContext ec, bool leave_copy)
736 throw new NotImplementedException ();
739 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
741 EmitCall (ec, setter, setter_args, !leave_copy);
744 #endregion
747 class DynamicUnaryConversion : DynamicExpressionStatement, IDynamicBinder
749 string name;
751 public DynamicUnaryConversion (string name, Arguments args, Location loc)
752 : base (null, args, loc)
754 this.name = name;
755 base.binder = this;
756 if (name == "IsTrue" || name == "IsFalse")
757 type = TypeManager.bool_type;
760 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
762 Arguments binder_args = new Arguments (3);
764 MemberAccess sle = new MemberAccess (new MemberAccess (
765 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
767 var flags = ec.HasSet (ResolveContext.Options.CheckedScope) ? CSharpBinderFlags.CheckedContext : 0;
769 binder_args.Add (new Argument (new BinderFlags (flags, this)));
770 binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), name, loc)));
771 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation ("[]", args.CreateDynamicBinderArguments (ec), loc)));
773 return new Invocation (GetBinder ("UnaryOperation", loc), binder_args);