Null constant cannot be used for ref/out variables
[mono.git] / mcs / class / Microsoft.CSharp / Microsoft.CSharp.RuntimeBinder / CSharpBinder.cs
1 //
2 // CSharpBinder.cs
3 //
4 // Authors:
5 //      Marek Safar  <marek.safar@gmail.com>
6 //
7 // Copyright (C) 2009 Novell, Inc (http://www.novell.com)
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 //
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 //
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28
29 using System;
30 using System.Dynamic;
31 using System.Linq.Expressions;
32 using Compiler = Mono.CSharp;
33 using System.Reflection;
34 using System.Collections.Generic;
35
36 namespace Microsoft.CSharp.RuntimeBinder
37 {
38         class CSharpBinder
39         {
40                 static ConstructorInfo binder_exception_ctor;
41                 static object resolver = new object ();
42
43                 DynamicMetaObjectBinder binder;
44                 Compiler.Expression expr;
45                 BindingRestrictions restrictions;
46                 DynamicMetaObject errorSuggestion;
47
48                 public CSharpBinder (DynamicMetaObjectBinder binder, Compiler.Expression expr, DynamicMetaObject errorSuggestion)
49                 {
50                         this.binder = binder;
51                         this.expr = expr;
52                         this.restrictions = BindingRestrictions.Empty;
53                         this.errorSuggestion = errorSuggestion;
54                 }
55
56                 public Compiler.ResolveContext.Options ResolveOptions { get; set; }
57
58                 public void AddRestrictions (DynamicMetaObject arg)
59                 {
60                         restrictions = restrictions.Merge (CreateRestrictionsOnTarget (arg));
61                 }
62
63                 public void AddRestrictions (DynamicMetaObject[] args)
64                 {
65                         restrictions = restrictions.Merge (CreateRestrictionsOnTarget (args));
66                 }
67
68                 public DynamicMetaObject Bind (DynamicContext ctx, Type callingType)
69                 {
70                         Expression res;
71                         try {
72                                 var rc = new Compiler.ResolveContext (new RuntimeBinderContext (ctx, ctx.ImportType (callingType)), ResolveOptions);
73
74                                 // Static typemanager and internal caches are not thread-safe
75                                 lock (resolver) {
76                                         expr = expr.Resolve (rc, Compiler.ResolveFlags.VariableOrValue);
77                                 }
78
79                                 if (expr == null)
80                                         throw new RuntimeBinderInternalCompilerException ("Expression resolved to null");
81
82                                 res = expr.MakeExpression (new Compiler.BuilderContext ());
83                         } catch (RuntimeBinderException e) {
84                                 if (errorSuggestion != null)
85                                         return errorSuggestion;
86
87                                 res = CreateBinderException (e.Message);
88                         } catch (Exception) {
89                                 if (errorSuggestion != null)
90                                         return errorSuggestion;
91
92                                 throw;
93                         }
94
95                         return new DynamicMetaObject (res, restrictions);
96                 }
97
98                 Expression CreateBinderException (string message)
99                 {
100                         if (binder_exception_ctor == null)
101                                 binder_exception_ctor = typeof (RuntimeBinderException).GetConstructor (new[] { typeof (string) });
102
103                         //
104                         // Uses target type to keep expressions composition working
105                         //
106                         return Expression.Throw (Expression.New (binder_exception_ctor, Expression.Constant (message)), binder.ReturnType);
107                 }
108
109                 static BindingRestrictions CreateRestrictionsOnTarget (DynamicMetaObject arg)
110                 {
111                         return arg.HasValue && arg.Value == null ?
112                                 BindingRestrictions.GetInstanceRestriction (arg.Expression, null) :
113                                 BindingRestrictions.GetTypeRestriction (arg.Expression, arg.LimitType);
114                 }
115
116                 public static BindingRestrictions CreateRestrictionsOnTarget (DynamicMetaObject[] args)
117                 {
118                         if (args.Length == 0)
119                                 return BindingRestrictions.Empty;
120
121                         var res = CreateRestrictionsOnTarget (args[0]);
122                         for (int i = 1; i < args.Length; ++i)
123                                 res = res.Merge (CreateRestrictionsOnTarget (args[i]));
124
125                         return res;
126                 }
127         }
128
129         class DynamicContext
130         {
131                 static DynamicContext dc;
132                 static object compiler_initializer = new object ();
133                 static object lock_object = new object ();
134
135                 readonly Compiler.CompilerContext cc;
136
137                 private DynamicContext (Compiler.CompilerContext cc)
138                 {
139                         this.cc = cc;
140                 }
141
142                 public Compiler.CompilerContext CompilerContext {
143                         get {
144                                 return cc;
145                         }
146                 }
147
148                 public static DynamicContext Create ()
149                 {
150                         if (dc != null)
151                                 return dc;
152
153                         lock (compiler_initializer) {
154                                 if (dc != null)
155                                         return dc;
156
157                                 var importer = new Compiler.ReflectionMetaImporter () {
158                                         IgnorePrivateMembers = false
159                                 };
160
161                                 var reporter = new Compiler.Report (ErrorPrinter.Instance) {
162                                         WarningLevel = 0
163                                 };
164
165                                 var cc = new Compiler.CompilerContext (importer, reporter) {
166                                         IsRuntimeBinder = true
167                                 };
168
169                                 IList<Compiler.PredefinedTypeSpec> core_types = null;
170                                 // HACK: To avoid re-initializing static TypeManager types, like string_type
171                                 if (!Compiler.RootContext.EvalMode) {
172                                         core_types = Compiler.TypeManager.InitCoreTypes ();
173                                 }
174
175                                 importer.Initialize ();
176
177                                 // I don't think dynamically loaded assemblies can be used as dynamic
178                                 // expression without static type to be loaded first
179                                 // AppDomain.CurrentDomain.AssemblyLoad += (sender, e) => { throw new NotImplementedException (); };
180
181                                 // Import all currently loaded assemblies
182                                 var ns = cc.GlobalRootNamespace;
183                                 foreach (System.Reflection.Assembly a in AppDomain.CurrentDomain.GetAssemblies ()) {
184                                         ns.AddAssemblyReference (a);
185                                         importer.ImportAssembly (a, ns);
186                                 }
187
188                                 if (!Compiler.RootContext.EvalMode) {
189                                         Compiler.TypeManager.InitCoreTypes (cc, core_types);
190                                         Compiler.TypeManager.InitOptionalCoreTypes (cc);
191                                 }
192
193                                 dc = new DynamicContext (cc);
194                         }
195
196                         return dc;
197                 }
198
199                 //
200                 // Creates mcs expression from dynamic object
201                 //
202                 public Compiler.Expression CreateCompilerExpression (CSharpArgumentInfo info, DynamicMetaObject value)
203                 {
204                         if (value.Value == null && (info == null || (info.Flags & (CSharpArgumentInfoFlags.IsOut | CSharpArgumentInfoFlags.IsRef)) == 0)) {
205                                 if (value.LimitType == typeof (object))
206                                         return new Compiler.NullLiteral (Compiler.Location.Null);
207
208                                 return Compiler.Constant.CreateConstantFromValue (ImportType (value.LimitType), null, Compiler.Location.Null);
209                         }
210
211                         //
212                         // No type details provider, go with runtime type
213                         //
214                         if (info == null)
215                                 return new Compiler.RuntimeValueExpression (value, ImportType (value.RuntimeType));
216
217                         //
218                         // Value is known to be a type
219                         //
220                         if ((info.Flags & CSharpArgumentInfoFlags.IsStaticType) != 0)
221                                 return new Compiler.TypeExpression (ImportType ((Type) value.Value), Compiler.Location.Null);
222
223                         //
224                         // Use compilation time type when type was known not to be dynamic during compilation
225                         //
226                         Type value_type = (info.Flags & CSharpArgumentInfoFlags.UseCompileTimeType) != 0 ? value.Expression.Type : value.LimitType;
227                         var type = ImportType (value_type);
228
229                         if ((info.Flags & CSharpArgumentInfoFlags.Constant) != 0)
230                                 return Compiler.Constant.CreateConstantFromValue (type, value.Value, Compiler.Location.Null);
231
232                         return new Compiler.RuntimeValueExpression (value, type);
233                 }
234
235                 //
236                 // Creates mcs arguments from dynamic argument info
237                 //
238                 public Compiler.Arguments CreateCompilerArguments (IEnumerable<CSharpArgumentInfo> info, DynamicMetaObject[] args)
239                 {
240                         var res = new Compiler.Arguments (args.Length);
241                         int pos = 0;
242
243                         // enumerates over args
244                         foreach (var item in info) {
245                                 var expr = CreateCompilerExpression (item, args[pos++]);
246                                 if (item.IsNamed) {
247                                         res.Add (new Compiler.NamedArgument (item.Name, Compiler.Location.Null, expr));
248                                 } else {
249                                         res.Add (new Compiler.Argument (expr, item.ArgumentModifier));
250                                 }
251
252                                 if (pos == args.Length)
253                                         break;
254                         }
255
256                         return res;
257                 }
258
259                 public Compiler.TypeSpec ImportType (Type type)
260                 {
261                         lock (lock_object) {
262                                 return cc.MetaImporter.ImportType (type);
263                         }
264                 }
265         }
266 }