5 // Marek Safar <marek.safar@gmail.com>
7 // Copyright (C) 2009 Novell, Inc (http://www.novell.com)
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:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
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.
31 using System.Linq.Expressions;
32 using Compiler = Mono.CSharp;
33 using System.Reflection;
34 using System.Collections.Generic;
36 namespace Microsoft.CSharp.RuntimeBinder
40 static ConstructorInfo binder_exception_ctor;
41 static object resolver = new object ();
43 DynamicMetaObjectBinder binder;
44 Compiler.Expression expr;
45 BindingRestrictions restrictions;
46 DynamicMetaObject errorSuggestion;
48 public CSharpBinder (DynamicMetaObjectBinder binder, Compiler.Expression expr, DynamicMetaObject errorSuggestion)
52 this.restrictions = BindingRestrictions.Empty;
53 this.errorSuggestion = errorSuggestion;
56 public Compiler.ResolveContext.Options ResolveOptions { get; set; }
58 public void AddRestrictions (DynamicMetaObject arg)
60 restrictions = restrictions.Merge (CreateRestrictionsOnTarget (arg));
63 public void AddRestrictions (DynamicMetaObject[] args)
65 restrictions = restrictions.Merge (CreateRestrictionsOnTarget (args));
68 public DynamicMetaObject Bind (DynamicContext ctx, Type callingType)
72 var rc = new Compiler.ResolveContext (new RuntimeBinderContext (ctx, ctx.ImportType (callingType)), ResolveOptions);
74 // Static typemanager and internal caches are not thread-safe
76 expr = expr.Resolve (rc, Compiler.ResolveFlags.VariableOrValue);
80 throw new RuntimeBinderInternalCompilerException ("Expression resolved to null");
82 res = expr.MakeExpression (new Compiler.BuilderContext ());
83 } catch (RuntimeBinderException e) {
84 if (errorSuggestion != null)
85 return errorSuggestion;
87 res = CreateBinderException (e.Message);
89 if (errorSuggestion != null)
90 return errorSuggestion;
95 return new DynamicMetaObject (res, restrictions);
98 Expression CreateBinderException (string message)
100 if (binder_exception_ctor == null)
101 binder_exception_ctor = typeof (RuntimeBinderException).GetConstructor (new[] { typeof (string) });
104 // Uses target type to keep expressions composition working
106 return Expression.Throw (Expression.New (binder_exception_ctor, Expression.Constant (message)), binder.ReturnType);
109 static BindingRestrictions CreateRestrictionsOnTarget (DynamicMetaObject arg)
111 return arg.HasValue && arg.Value == null ?
112 BindingRestrictions.GetInstanceRestriction (arg.Expression, null) :
113 BindingRestrictions.GetTypeRestriction (arg.Expression, arg.LimitType);
116 public static BindingRestrictions CreateRestrictionsOnTarget (DynamicMetaObject[] args)
118 if (args.Length == 0)
119 return BindingRestrictions.Empty;
121 var res = CreateRestrictionsOnTarget (args[0]);
122 for (int i = 1; i < args.Length; ++i)
123 res = res.Merge (CreateRestrictionsOnTarget (args[i]));
131 static DynamicContext dc;
132 static object compiler_initializer = new object ();
133 static object lock_object = new object ();
135 readonly Compiler.CompilerContext cc;
137 private DynamicContext (Compiler.CompilerContext cc)
142 public Compiler.CompilerContext CompilerContext {
148 public static DynamicContext Create ()
153 lock (compiler_initializer) {
157 var importer = new Compiler.ReflectionMetaImporter () {
158 IgnorePrivateMembers = false
161 var reporter = new Compiler.Report (ErrorPrinter.Instance) {
165 var cc = new Compiler.CompilerContext (importer, reporter) {
166 IsRuntimeBinder = true
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 ();
175 importer.Initialize ();
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 (); };
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);
188 if (!Compiler.RootContext.EvalMode) {
189 Compiler.TypeManager.InitCoreTypes (cc, core_types);
190 Compiler.TypeManager.InitOptionalCoreTypes (cc);
193 dc = new DynamicContext (cc);
200 // Creates mcs expression from dynamic object
202 public Compiler.Expression CreateCompilerExpression (CSharpArgumentInfo info, DynamicMetaObject value)
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);
208 return Compiler.Constant.CreateConstantFromValue (ImportType (value.LimitType), null, Compiler.Location.Null);
212 // No type details provider, go with runtime type
215 return new Compiler.RuntimeValueExpression (value, ImportType (value.RuntimeType));
218 // Value is known to be a type
220 if ((info.Flags & CSharpArgumentInfoFlags.IsStaticType) != 0)
221 return new Compiler.TypeExpression (ImportType ((Type) value.Value), Compiler.Location.Null);
224 // Use compilation time type when type was known not to be dynamic during compilation
226 Type value_type = (info.Flags & CSharpArgumentInfoFlags.UseCompileTimeType) != 0 ? value.Expression.Type : value.LimitType;
227 var type = ImportType (value_type);
229 if ((info.Flags & CSharpArgumentInfoFlags.Constant) != 0)
230 return Compiler.Constant.CreateConstantFromValue (type, value.Value, Compiler.Location.Null);
232 return new Compiler.RuntimeValueExpression (value, type);
236 // Creates mcs arguments from dynamic argument info
238 public Compiler.Arguments CreateCompilerArguments (IEnumerable<CSharpArgumentInfo> info, DynamicMetaObject[] args)
240 var res = new Compiler.Arguments (args.Length);
243 // enumerates over args
244 foreach (var item in info) {
245 var expr = CreateCompilerExpression (item, args[pos++]);
247 res.Add (new Compiler.NamedArgument (item.Name, Compiler.Location.Null, expr));
249 res.Add (new Compiler.Argument (expr, item.ArgumentModifier));
252 if (pos == args.Length)
259 public Compiler.TypeSpec ImportType (Type type)
262 return cc.MetaImporter.ImportType (type);