Пример #1
0
 internal bool AssignmentCompatible(IReflect lhir, bool reportError){
   if (lhir == Typeob.Object || lhir == Typeob.Array || lhir is ArrayObject) return true;
   IReflect target_element_ir;
   if (lhir == Typeob.Array)
     target_element_ir = Typeob.Object;
   else if (lhir is TypedArray){
     TypedArray tArr = ((TypedArray)lhir);
     if (tArr.rank != 1){
       this.context.HandleError(JSError.TypeMismatch, reportError);
       return false;
     }
     target_element_ir = tArr.elementType;
   }else if (lhir is Type && ((Type)lhir).IsArray){
     Type t = ((Type)lhir);
     if (t.GetArrayRank() != 1){
       this.context.HandleError(JSError.TypeMismatch, reportError);
       return false;
     }
     target_element_ir = t.GetElementType();
   }else
     return false;
   for (int i = 0, n = this.elements.count; i < n; i++)
     if (!Binding.AssignmentCompatible(target_element_ir, this.elements[i], this.elements[i].InferType(null), reportError))
       return false;
   return true;
 }
 public HtmlToClrEventProxy(object sender, string eventName, EventHandler eventHandler)
 {
     this.eventHandler = eventHandler;
     this.eventName = eventName;
     System.Type type = typeof(HtmlToClrEventProxy);
     this.typeIReflectImplementation = type;
 }
        public HtmlToClrEventProxy(object sender, string eventName, EventHandler eventHandler) {
            this.eventHandler = eventHandler;
            this.eventName = eventName;

            Type htmlToClrEventProxyType = typeof(HtmlToClrEventProxy);
            typeIReflectImplementation = htmlToClrEventProxyType as IReflect;
        }
        private static PropertyInfo GetPropertyCaseInsensitive(IReflect type, string propertyName)
        {
            // make the property reflection lookup case insensitive
            const BindingFlags bindingFlags = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance;

            return type.GetProperty(propertyName, bindingFlags);
        }
Пример #5
0
        private static IEnumerable<Action<IComponentContext, object>> BuildLoggerInjectors(IReflect componentType)
        {
            // look for settable properties of type "ILogger"
            var loggerProperties = componentType
                .GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance)
                .Select(p => new
                {
                    PropertyInfo = p,
                    p.PropertyType,
                    IndexParameters = p.GetIndexParameters(),
                    Accessors = p.GetAccessors(false)
                })
                // must be a logger
                .Where(x => x.PropertyType == typeof(ILogger))
                // must not be an indexer
                .Where(x => x.IndexParameters.Count() == 0)
                // must have get/set, or only set
                .Where(x => x.Accessors.Length != 1 || x.Accessors[0].ReturnType == typeof(void));

            // return an IEnumerable of actions that resolve a logger and assign the property
            return loggerProperties
                   .Select(entry => entry.PropertyInfo)
                   .Select(propertyInfo => (Action<IComponentContext, object>)((ctx, instance) =>
                   {
                       var propertyValue = ctx.Resolve<ILogger>(new TypedParameter(typeof(Type), componentType));
                       propertyInfo.SetValue(instance, propertyValue, null);
                   }));
        }
 internal InternalAccessibleObject(AccessibleObject accessibleImplemention)
 {
     this.publicIAccessible = accessibleImplemention;
     this.publicIEnumVariant = accessibleImplemention;
     this.publicIOleWindow = accessibleImplemention;
     this.publicIReflect = accessibleImplemention;
 }
 private static MemberInfo[] GetDefaultMembers(Type typ, IReflect objIReflect, ref string DefaultName)
 {
     MemberInfo[] nonGenericMembers;
     if (typ == objIReflect)
     {
         do
         {
             object[] customAttributes = typ.GetCustomAttributes(typeof(DefaultMemberAttribute), false);
             if ((customAttributes != null) && (customAttributes.Length != 0))
             {
                 DefaultName = ((DefaultMemberAttribute) customAttributes[0]).MemberName;
                 nonGenericMembers = GetNonGenericMembers(typ.GetMember(DefaultName, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase));
                 if ((nonGenericMembers != null) && (nonGenericMembers.Length != 0))
                 {
                     return nonGenericMembers;
                 }
                 DefaultName = "";
                 return null;
             }
             typ = typ.BaseType;
         }
         while (typ != null);
         DefaultName = "";
         return null;
     }
     nonGenericMembers = GetNonGenericMembers(objIReflect.GetMember("", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase));
     if ((nonGenericMembers == null) || (nonGenericMembers.Length == 0))
     {
         DefaultName = "";
         return null;
     }
     DefaultName = nonGenericMembers[0].Name;
     return nonGenericMembers;
 }
        private static IEnumerable<string> CompareTypes(IReflect type1, IReflect type2, BindingFlags bindingFlags)
        {
            MethodInfo[] typeTMethodInfo = type1.GetMethods(bindingFlags);
            MethodInfo[] typeXMethodInfo = type2.GetMethods(bindingFlags);

            return typeTMethodInfo.Select(x => x.Name)
                                  .Except(typeXMethodInfo.Select(x => x.Name));
        }
Пример #9
0
 public static string LookupResource(IReflect resourceManagerProvider, string resourceKey)
 {
     PropertyInfo property = resourceManagerProvider.GetProperty(resourceKey, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
     // Fallback with the key name
     if (property == null)
         return resourceKey;
     return (string) property.GetValue(null, null); // returns string directly from res file
 }
Пример #10
0
 internal VsaNamedItemScope(Object hostObject, ScriptObject parent, VsaEngine engine)
   : base(parent){
   this.namedItem = hostObject;
   if ((this.reflectObj = hostObject as IReflect) == null)
     this.reflectObj = hostObject.GetType();
   this.recursive = false;
   this.engine = engine;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultEnvironmentProvider"/> class.
 /// </summary>
 /// <param name="supportedType">A <see cref="IReflect"/> of a object with the supported Environment Aliases on.</param>
 protected DefaultEnvironmentProvider(IReflect supportedType)
 {
     this.SupportedAliases = supportedType
         .GetFields(BindingFlags.Static | BindingFlags.Public)
         .Where(f => f.IsLiteral)
         .Select(a => a.GetValue(supportedType) as string)
         .ToArray();
 }
Пример #12
0
		private static FieldInfo GetFieldByPropertyName(IReflect viewModelType, string propertyName)
		{
			var charList = new List<char> { char.ToLower(propertyName[0]) };
			charList.AddRange(propertyName.Substring(1));
			var fieldName = new string(charList.ToArray());

			var field = viewModelType.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
			return field;
		}
Пример #13
0
 // private CTOR
 private HtmlEventProxy(string eventName, IHTMLElement2 htmlElement, EventHandler eventHandler)
 {
     this.eventName = eventName;
     this.htmlElement = htmlElement;
     this.sender = this;
     this.eventHandler = eventHandler;
     Type type = typeof(HtmlEventProxy);
     this.typeIReflectImplementation = type;
 }
Пример #14
0
 private static PropertyInfo FindUserProperty(IReflect type)
 {
     //寻找类型为 "Localizer" 并且具有set方法的属性。
     return type
         .GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance)
         .Where(x => x.PropertyType == typeof(Localizer)) //必须是一个本地化委托
         .Where(x => !x.GetIndexParameters().Any()) //没有索引器
         .FirstOrDefault(x => x.GetAccessors(false).Length != 1 || x.GetAccessors(false)[0].ReturnType == typeof(void)); //必须具有set方法。
 }
Пример #15
0
 internal CallableExpression(AST expression)
   : base(expression.context, ""){
   this.expression = expression;
   JSLocalField field = new JSLocalField("", null, 0, Missing.Value);
   this.expressionInferredType = expression.InferType(field);
   field.inferred_type = this.expressionInferredType;
   this.member = field;
   this.members = new MemberInfo[]{field};
 }
 public FormatPropertiesResolver(IReflect type, IPropertyFormatInfoProvider formatInfoProvider)
 {
     this.formatInfoProvider = formatInfoProvider;
     PropertiesFormat =
         type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
             .Where(prop => prop.CanRead)
             .Select(ConvertToPropertyFormat)
             .Where(pform => pform != null);
 }
Пример #17
0
        void WriteObject(TextWriter writer, object value, IReflect type)
        {
            foreach (var property in type
                .GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                var propertyValue = property.GetValue(value, new object[] { });

                WriteTag(writer, propertyValue, property, null);
            }
        }
Пример #18
0
		/*
		 * Constructs the wrapper for a known method name
		 */
		public LuaMethodWrapper(ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType) 
		{
			this.translator=translator;
			this.methodName=methodName;
			this.targetType=targetType;
			if(targetType!=null)
				extractTarget=translator.typeChecker.getExtractor(targetType);
			this.bindingType=bindingType;
			members=targetType.UnderlyingSystemType.GetMember(methodName,MemberTypes.Method,bindingType|BindingFlags.Public|BindingFlags.NonPublic);
		}
 internal VsaNamedItemScope(object hostObject, ScriptObject parent, VsaEngine engine) : base(parent)
 {
     this.namedItem = hostObject;
     this.reflectObj = hostObject as IReflect;
     if (this.reflectObj == null)
     {
         this.reflectObj = Globals.TypeRefs.ToReferenceContext(hostObject.GetType());
     }
     this.recursive = false;
     base.engine = engine;
 }
Пример #20
0
 internal JSLocalField(String name, FunctionScope scope, int slotNumber, Object value)
   : base(name, scope, FieldAttributes.Static|FieldAttributes.Public) {
   this.slotNumber = slotNumber;
   this.inferred_type = null;
   this.dependents = null;
   this.value = value;
   this.debugOn = false;
   this.outerField = null;
   this.isDefined = false;
   this.isUsedBeforeDefinition = false;
 }
Пример #21
0
        static  Func<string, object> Bind(IReflect factory)
        {
            var method = factory.GetMethod("GetGrain", 
                BindingFlags.Public | BindingFlags.Static, null, 
                new[]{typeof(long), typeof(string)}, null);

            var argument = Expression.Parameter(typeof(string), "ext");
            var call = Expression.Call(method, new Expression[]{Expression.Constant(0L), argument});
            var lambda = Expression.Lambda<Func<string, object>>(call, argument);

            return lambda.Compile();
        }
Пример #22
0
 internal Member(Context context, AST rootObject, AST memberName)
   : base(context, memberName.context.GetCode()){
   this.fast = this.Engine.doFast;
   this.isImplicitWrapper = false;
   this.isNonVirtual = rootObject is ThisLiteral && ((ThisLiteral)rootObject).isSuper;
   this.lateBinding = null;
   this.memberNameContext = memberName.context;
   this.rootObject = rootObject;
   this.rootObjectInferredType = null;
   this.refLoc = null;
   this.temp = null;
 }
Пример #23
0
		/*
		 * Constructs the wrapper for a known MethodBase instance
		 */
		public LuaMethodWrapper(ObjectTranslator translator, object target, IReflect targetType, MethodBase method) 
		{
			this.translator=translator;
			this.target=target;
			this.targetType=targetType;
			if(targetType!=null)
				extractTarget=translator.typeChecker.getExtractor(targetType);
			this.method=method;
			this.methodName=method.Name;
			if(method.IsStatic) { bindingType=BindingFlags.Static; } 
			else { bindingType=BindingFlags.Instance; }
		}
Пример #24
0
 private IReflect[] ArgIRs(){
   int n = this.args.count;
   IReflect[] argIRs = new IReflect[n];
   for (int i = 0; i < n; i++){
     AST arg = this.args[i];
     IReflect ir = argIRs[i] = arg.InferType(null);
     if (arg is AddressOf){
       if (ir is ClassScope) ir = ((ClassScope)ir).GetBakedSuperType(); //this should change if ever JS can declare out params
       argIRs[i] = Convert.ToType("&", Convert.ToType(ir));
     }
   }
   return argIRs;
 }
Пример #25
0
 public LuaMethodWrapper(ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType)
 {
     this._LastCalledMethod = new MethodCache();
     this._Translator = translator;
     this._MethodName = methodName;
     this._TargetType = targetType;
     if (targetType != null)
     {
         this._ExtractTarget = translator.typeChecker.getExtractor(targetType);
     }
     this._BindingType = bindingType;
     this._Members = targetType.UnderlyingSystemType.GetMember(methodName, MemberTypes.Method, (bindingType | BindingFlags.Public) | BindingFlags.IgnoreCase);
 }
Пример #26
0
 protected MethodInfo GetOperator(IReflect ir1, IReflect ir2){
   if (ir1 is ClassScope) ir1 = ((ClassScope)ir1).GetUnderlyingTypeIfEnum();
   if (ir2 is ClassScope) ir2 = ((ClassScope)ir2).GetUnderlyingTypeIfEnum();
   Type t1 = ir1 is Type ? (Type)ir1 : Typeob.Object;
   Type t2 = ir2 is Type ? (Type)ir2 : Typeob.Object;
   if (this.type1 == t1 && this.type2 == t2)
     return this.operatorMeth; 
   this.type1 = t1;
   this.type2 = t2;
   this.operatorMeth = null;
   if (t1 == Typeob.String || Convert.IsPrimitiveNumericType(ir1) || Typeob.JSObject.IsAssignableFrom(t1))
     t1 = null; 
   if (t2 == Typeob.String || Convert.IsPrimitiveNumericType(ir2) || Typeob.JSObject.IsAssignableFrom(t2))
     t2 = null;
   if (t1 == null && t2 == null)
     return null;
   //One of the operands is an object of a type that might have a user defined operator.
   String name = "op_NoSuchOp";
   switch (this.operatorTok){
     case JSToken.BitwiseAnd: name = "op_BitwiseAnd"; break;
     case JSToken.BitwiseOr: name = "op_BitwiseOr"; break;
     case JSToken.BitwiseXor: name = "op_ExclusiveOr"; break;
     case JSToken.Divide: name = "op_Division"; break;
     case JSToken.Equal: name = "op_Equality"; break;
     case JSToken.GreaterThan: name = "op_GreaterThan"; break;
     case JSToken.GreaterThanEqual: name = "op_GreaterThanOrEqual"; break;
     case JSToken.LeftShift: name = "op_LeftShift"; break;
     case JSToken.LessThan: name = "op_LessThan"; break;
     case JSToken.LessThanEqual: name = "op_LessThanOrEqual"; break;
     case JSToken.Minus: name = "op_Subtraction"; break;
     case JSToken.Modulo: name = "op_Modulus"; break;
     case JSToken.Multiply: name = "op_Multiply"; break;
     case JSToken.NotEqual: name = "op_Inequality"; break;
     case JSToken.Plus: name = "op_Addition"; break;
     case JSToken.RightShift:name = "op_RightShift"; break;
   }
   Type[] types = new Type[]{this.type1, this.type2};
   if (t1 == t2){
     MethodInfo op = t1.GetMethod(name, BindingFlags.Public|BindingFlags.Static, JSBinder.ob, types, null);
     if (op != null && (op.Attributes & MethodAttributes.SpecialName) != 0 && op.GetParameters().Length == 2)
       this.operatorMeth = op;
   }else{
     //Search both operand types, but only if there is a possibility that they might have operators defined on them
     MethodInfo op1 = t1 == null ? null : t1.GetMethod(name, BindingFlags.Public|BindingFlags.Static, JSBinder.ob, types, null);
     MethodInfo op2 = t2 == null ? null : t2.GetMethod(name, BindingFlags.Public|BindingFlags.Static, JSBinder.ob, types, null);
     this.operatorMeth = JSBinder.SelectOperator(op1, op2, this.type1, this.type2); //Choose the better of the two
   }
   if (this.operatorMeth != null)
     this.operatorMeth = new JSMethodInfo(this.operatorMeth);
   return this.operatorMeth;  
 }
Пример #27
0
        /// <summary>
        /// Constructs the wrapper for a known method name
        /// </summary>
        /// <param name="translator"></param>
        /// <param name="targetType"></param>
        /// <param name="methodName"></param>
        /// <param name="bindingType"></param>
        public LuaMethodWrapper(ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType)
        {
            invokeFunction = new LuaNativeFunction(this.Call);

            _Translator = translator;
            _MethodName = methodName;

            if (targetType != null)
                _ExtractTarget = translator.typeChecker.GetExtractor(targetType);

            _BindingType = bindingType;
            //CP: Removed NonPublic binding search and added IgnoreCase
            _Members = targetType.UnderlyingSystemType.GetMember(methodName, MemberTypes.Method, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*|BindingFlags.NonPublic*/);
        }
Пример #28
0
 internal JSObject(ScriptObject parent, Type subType)
   : base(parent) {
   this.memberCache = null;
   this.isASubClass = false;
   this.subClassIR = null;
   Debug.Assert(subType == this.GetType() || this.GetType() == typeof(BuiltinFunction));
   if (subType != Typeob.JSObject){
     this.isASubClass = true;
     this.subClassIR = TypeReflector.GetTypeReflectorFor(subType);
   }
   this.noExpando = this.isASubClass;
   this.name_table = null;
   this.field_table = null;
 }
 internal TypeExpression(AST expression)
   : base(expression.context) {
   this.expression = expression;
   this.isArray = false;
   this.rank = 0;
   this.recursive = false;
   this.cachedIR = null;
   if (expression is Lookup){
     String name = expression.ToString();
     Object ptype = Globals.TypeRefs.GetPredefinedType(name);
     if (ptype != null)
       this.expression = new ConstantWrapper(ptype, expression.context);
   }
 }
Пример #30
0
		private void injectMembers(IReflect type, object instance)
		{
			var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
				.Where(x => x.CanWrite);
			foreach (var propertyInfo in properties)
			{
				propertyInfo.SetValue(instance, _container.Resolve(propertyInfo.PropertyType), null);
			}
			var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
			foreach (var fieldsInfo in fields)
			{
				fieldsInfo.SetValue(instance, _container.Resolve(fieldsInfo.FieldType));
			}
		}
Пример #31
0
        private static void CopyFields(
            object originalObject,
            IDictionary <object, object> visited,
            object cloneObject,
            IReflect typeToReflect,
            BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy, Func <FieldInfo, bool> filter = null)
        {
            var validFields = typeToReflect.GetFields(bindingFlags).Where(x => x.IsValidField()).ToList();

            foreach (FieldInfo fieldInfo in validFields)
            {
                if (filter != null && filter(fieldInfo) == false)
                {
                    continue;
                }
                if (IsPrimitive(fieldInfo.FieldType))
                {
                    continue;
                }
                var originalFieldValue = fieldInfo.GetValue(originalObject);
                var clonedFieldValue   = InternalCopy(originalFieldValue, visited);
                fieldInfo.SetValue(cloneObject, clonedFieldValue);
            }
        }
Пример #32
0
        internal void ResolveAssignmentToDefaultIndexedProperty(ASTList args, IReflect[] argIRs, AST rhvalue)
        {
            IReflect ir = this.InferType(null);
            Type     t  = ir is Type ? (Type)ir : null;

            if (ir is ClassScope)
            {
                t = ((ClassScope)ir).GetBakedSuperType();
            }
            MemberInfo[] defaultMembers = JSBinder.GetDefaultMembers(t);
            if (defaultMembers != null && defaultMembers.Length > 0)
            {
                try{
                    PropertyInfo prop = JSBinder.SelectProperty(defaultMembers, argIRs); //Returns property getters as well
                    if (prop != null)
                    {
                        this.method = JSProperty.GetSetMethod(prop, true);
                        if (this.method == null)
                        {
                            this.context.HandleError(JSError.AssignmentToReadOnly, true);
                        }
                        if (!Binding.CheckParameters(prop.GetIndexParameters(), argIRs, args, this.context, 0, false, true))
                        {
                            this.method = null;
                        }
                        return;
                    }
                }catch (AmbiguousMatchException) {
                    this.context.HandleError(JSError.AmbiguousMatch);
                    return;
                }
            }
            String tname = ir is ClassScope ? ((ClassScope)ir).GetName() : ((Type)ir).Name;

            this.context.HandleError(JSError.NotIndexable, tname);
        }
Пример #33
0
        private static bool TryInvokeMethod(IReflect target, string name, bool ignoreCase, object[] args, out object result)
        {
            // ReSharper disable SuspiciousTypeConversion.Global

            var dispatchEx = target as IDispatchEx;

            if (dispatchEx != null)
            {
                // Standard IExpando-over-IDispatchEx support appears to leak the variants it
                // creates for the invocation arguments. This issue has been reported. In the
                // meantime we'll bypass this facility and interface with IDispatchEx directly.

                result = dispatchEx.InvokeMethod(name, ignoreCase, args);
                return(true);
            }

            // ReSharper restore SuspiciousTypeConversion.Global

            var flags = BindingFlags.Public;

            if (ignoreCase)
            {
                flags |= BindingFlags.IgnoreCase;
            }

            var method = target.GetMethod(name, flags);

            if (method != null)
            {
                result = method.Invoke(target, BindingFlags.InvokeMethod | flags, null, args, CultureInfo.InvariantCulture);
                return(true);
            }

            result = null;
            return(false);
        }
Пример #34
0
        private static object GetMethodExtended(
            IReflect type,
            string name,
            bool staticMethod,
            int parameterCount)
        {
            var          haveMethodName = false;
            BindingFlags flags          = (staticMethod ? BindingFlags.Static :
                                           BindingFlags.Instance) | BindingFlags.Public |
                                          BindingFlags.NonPublic | BindingFlags.InvokeMethod;

            foreach (var method in type.GetMethods(flags))
            {
                if (method.Name.Equals(name))
                {
                    haveMethodName = true;
                    if (method.GetParameters().Length == parameterCount)
                    {
                        return(method);
                    }
                }
            }
            return(haveMethodName ? type.GetMethod(name, flags) : null);
        }
        private static MemberInfo[] GetAndWrapMember(IReflect reflect, object namedItem, string name, BindingFlags bindingAttr)
        {
            PropertyInfo property = reflect.GetProperty(name, bindingAttr);

            if (property != null)
            {
                MethodInfo getMethod = JSProperty.GetGetMethod(property, false);
                MethodInfo setMethod = JSProperty.GetSetMethod(property, false);
                if (((getMethod != null) && !getMethod.IsStatic) || ((setMethod != null) && !setMethod.IsStatic))
                {
                    MethodInfo method = reflect.GetMethod(name, bindingAttr);
                    if ((method != null) && !method.IsStatic)
                    {
                        return(new MemberInfo[] { new JSWrappedPropertyAndMethod(property, method, namedItem) });
                    }
                }
            }
            MemberInfo[] member = reflect.GetMember(name, bindingAttr);
            if ((member != null) && (member.Length > 0))
            {
                return(ScriptObject.WrapMembers(member, namedItem));
            }
            return(null);
        }
Пример #36
0
        private async Task <IEnumerable <MethodInfo> > GetMatchingMethodsAsync(IReflect matchingType)
        {
            var matchingMethods = new List <MethodInfo>();

            foreach (MethodInfo method in matchingType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(arg => !arg.IsSpecialName))
            {
                bool matches = true;

                foreach (IMethodFilter methodFilter in _methodFilters)
                {
                    if (!await methodFilter.MatchesAsync(method))
                    {
                        matches = false;
                        break;
                    }
                }
                if (matches)
                {
                    matchingMethods.Add(method);
                }
            }

            return(matchingMethods);
        }
Пример #37
0
 public TypedArray(IReflect elementType, int rank)
 {
     this.elementType = elementType;
     this.rank        = rank;
 }
Пример #38
0
 private static object GetFieldStatic(this IReflect t, string name) => t.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null);
Пример #39
0
 public static IEnumerable <PropertyInfo> SearchableProperties(this IReflect obj)
 {
     return(obj.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => Attribute.IsDefined(p, typeof(MakeSearchable))));
 }
Пример #40
0
 static void RequirePrivateMethods([KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute)), DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] IReflect m)
 {
 }
Пример #41
0
 public static extern void Unsupported(
     [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "System.Runtime.InteropServices.CustomMarshalers.ExpandoToDispatchExMarshaler")]
     IReflect expando
     );
Пример #42
0
        /*
         * Pushes the value of a member or a delegate to call it, depending on the type of
         * the member. Works with static or instance members.
         * Uses reflection to find members, and stores the reflected MemberInfo object in
         * a cache (indexed by the type of the object and the name of the member).
         */
        private int getMember(KopiLua.Lua.lua_State luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType)
        {
            bool       implicitStatic = false;
            MemberInfo member         = null;
            object     cachedMember   = checkMemberCache(memberCache, objType, methodName);

            //object cachedMember=null;
            if (cachedMember is KopiLua.Lua.lua_CFunction)
            {
                translator.pushFunction(luaState, (KopiLua.Lua.lua_CFunction)cachedMember);
                translator.push(luaState, true);
                return(2);
            }
            else if (cachedMember != null)
            {
                member = (MemberInfo)cachedMember;
            }
            else
            {
                MemberInfo[] members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.NonPublic);
                if (members.Length > 0)
                {
                    member = members[0];
                }
                else
                {
                    // If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static
                    // lookups for fields/properties/events -kevinh
                    members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

                    if (members.Length > 0)
                    {
                        member         = members[0];
                        implicitStatic = true;
                    }
                }
            }
            if (member != null)
            {
                if (member.MemberType == MemberTypes.Field)
                {
                    FieldInfo field = (FieldInfo)member;
                    if (cachedMember == null)
                    {
                        setMemberCache(memberCache, objType, methodName, member);
                    }
                    try
                    {
                        translator.push(luaState, field.GetValue(obj));
                    }
                    catch
                    {
                        LuaDLL.lua_pushnil(luaState);
                    }
                }
                else if (member.MemberType == MemberTypes.Property)
                {
                    PropertyInfo property = (PropertyInfo)member;
                    if (cachedMember == null)
                    {
                        setMemberCache(memberCache, objType, methodName, member);
                    }
                    try
                    {
                        object val = property.GetValue(obj, null);

                        translator.push(luaState, val);
                    }
                    catch (ArgumentException)
                    {
                        // If we can't find the getter in our class, recurse up to the base class and see
                        // if they can help.

                        if (objType is Type && !(((Type)objType) == typeof(object)))
                        {
                            return(getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType));
                        }
                        else
                        {
                            LuaDLL.lua_pushnil(luaState);
                        }
                    }
                    catch (TargetInvocationException e)  // Convert this exception into a Lua error
                    {
                        ThrowError(luaState, e);
                        LuaDLL.lua_pushnil(luaState);
                    }
                }
                else if (member.MemberType == MemberTypes.Event)
                {
                    EventInfo eventInfo = (EventInfo)member;
                    if (cachedMember == null)
                    {
                        setMemberCache(memberCache, objType, methodName, member);
                    }
                    translator.push(luaState, new RegisterEventHandler(translator.pendingEvents, obj, eventInfo));
                }
                else if (!implicitStatic)
                {
                    if (member.MemberType == MemberTypes.NestedType)
                    {
                        // kevinh - added support for finding nested types

                        // cache us
                        if (cachedMember == null)
                        {
                            setMemberCache(memberCache, objType, methodName, member);
                        }

                        // Find the name of our class
                        string name    = member.Name;
                        Type   dectype = member.DeclaringType;

                        // Build a new long name and try to find the type by name
                        string longname   = dectype.FullName + "+" + name;
                        Type   nestedType = translator.FindType(longname);

                        translator.pushType(luaState, nestedType);
                    }
                    else
                    {
                        // Member type must be 'method'
                        KopiLua.Lua.lua_CFunction wrapper = new KopiLua.Lua.lua_CFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call);
                        if (cachedMember == null)
                        {
                            setMemberCache(memberCache, objType, methodName, wrapper);
                        }
                        translator.pushFunction(luaState, wrapper);
                        translator.push(luaState, true);
                        return(2);
                    }
                }
                else
                {
                    // If we reach this point we found a static method, but can't use it in this context because the user passed in an instance
                    translator.throwError(luaState, "can't pass instance to static method " + methodName);

                    LuaDLL.lua_pushnil(luaState);
                }
            }
            else
            {
                // kevinh - we want to throw an exception because meerly returning 'nil' in this case
                // is not sufficient.  valid data members may return nil and therefore there must be some
                // way to know the member just doesn't exist.

                translator.throwError(luaState, "unknown member name " + methodName);

                LuaDLL.lua_pushnil(luaState);
            }

            // push false because we are NOT returning a function (see luaIndexFunction)
            translator.push(luaState, false);
            return(2);
        }
Пример #43
0
        /*
         * Checks if a MemberInfo object is cached, returning it or null.
         */
        private object checkMemberCache(Hashtable memberCache, IReflect objType, string memberName)
        {
            var members = (Hashtable)memberCache [objType];

            return(!members.IsNull() ? members [memberName] : null);
        }
Пример #44
0
        protected override void HandleNoSuchMemberError()
        {
            IReflect obType = this.rootObject.InferType(null);
            Object   obVal  = null;

            if (this.rootObject is ConstantWrapper)
            {
                obVal = this.rootObject.Evaluate();
            }

            if ((obType == Typeob.Object && !this.isNonVirtual) ||
                (obType is JSObject && !((JSObject)obType).noExpando) ||
                (obType is GlobalScope && !((GlobalScope)obType).isKnownAtCompileTime))
            {
                return;
            }
            if (obType is Type)
            {
                Type t = (Type)obType;
                if (Typeob.ScriptFunction.IsAssignableFrom(t) || t == Typeob.MathObject)
                {
                    //dealing with an assigment to a member of a builtin constructor function.
                    Debug.Assert(this.fast);
                    this.memberNameContext.HandleError(JSError.OLENoPropOrMethod);
                    return;
                }
                if (Typeob.IExpando.IsAssignableFrom(t))
                {
                    return;
                }
                if (!this.fast)
                {
                    if (t == Typeob.Boolean || t == Typeob.String || Convert.IsPrimitiveNumericType(t))
                    {
                        return;
                    }
                }

                // Check to see if we couldn't get the member because it is non-static.
                if (obVal is ClassScope)
                {
                    MemberInfo[] members = ((ClassScope)obVal).GetMember(this.name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                    if (members.Length > 0)
                    {
                        this.memberNameContext.HandleError(JSError.NonStaticWithTypeName);
                        return;
                    }
                }
            }

            if (obVal is FunctionObject)
            {
                this.rootObject = new ConstantWrapper(((FunctionObject)obVal).name, this.rootObject.context);
                this.memberNameContext.HandleError(JSError.OLENoPropOrMethod);
                return;
            }

            // Check to see if we couldn't get the member because it is static.
            if (obType is ClassScope)
            {
                MemberInfo[] members = ((ClassScope)obType).GetMember(this.name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
                if (members.Length > 0)
                {
                    this.memberNameContext.HandleError(JSError.StaticRequiresTypeName);
                    return;
                }
            }

            if (obVal is Type)
            {
                this.memberNameContext.HandleError(JSError.NoSuchStaticMember, Convert.ToTypeName((Type)obVal));
            }
            else if (obVal is ClassScope)
            {
                this.memberNameContext.HandleError(JSError.NoSuchStaticMember, Convert.ToTypeName((ClassScope)obVal));
            }
            else if (obVal is Namespace)
            {
                this.memberNameContext.HandleError(JSError.NoSuchType, ((Namespace)obVal).Name + "." + this.name);
            }
            else
            {
                if (obType == FunctionPrototype.ob && this.rootObject is Binding &&
                    ((Binding)this.rootObject).member is JSVariableField && ((JSVariableField)((Binding)this.rootObject).member).value is FunctionObject)
                {
                    return;
                }
                this.memberNameContext.HandleError(JSError.NoSuchMember, Convert.ToTypeName(obType));
            }
        }
Пример #45
0
 public static IEnumerable <PropertyInfo> SearchablePropertiesOfType <T>(this IReflect obj)
 {
     return(obj.SearchableProperties().Where(p => p.PropertyType == typeof(T)));
 }
Пример #46
0
 public void UpdateAvailableFormatingParts(IReflect type)
 {
     TextBox.UpdateAvailableFormatingParts(type);
 }
Пример #47
0
 /*
  * Checks if the value at Lua stack index stackPos matches paramType,
  * returning a conversion function if it does and null otherwise.
  */
 internal ExtractValue getExtractor(IReflect paramType)
 {
     return(getExtractor(paramType.UnderlyingSystemType));
 }
Пример #48
0
 private static IEnumerable <PropertyInfo> GetTestSourcePropertiesFrom(IReflect type)
 {
     return(type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(IsTestSource));
 }
Пример #49
0
        /// <summary>[-0, +2, e]
        /// Returns to Lua the value of a member or a delegate to call it, depending on the type of the member.
        /// Works with static or instance members. Uses reflection to find members,
        /// and stores the reflected MemberInfo object in a cache (indexed by <paramref name="objType"/> and <paramref name="methodName"/>).
        /// </summary>
        /// <exception cref="ArgumentNullException"><paramref name="objType"/> and <paramref name="methodName"/> are required</exception>
        int getMember(lua.State L, IReflect objType, object obj, string methodName, BindingFlags bindingType)
        {
            Debug.Assert(interpreter.IsSameLua(L));
            Debug.Assert(objType != null && methodName != null);

            Debug.Assert((obj == null) == (objType is ProxyType));
            Debug.Assert((obj == null) != (objType is Type));
            Debug.Assert((obj == null) == ((bindingType & BindingFlags.Static) == BindingFlags.Static));
            Debug.Assert((obj == null) != ((bindingType & BindingFlags.Instance) == BindingFlags.Instance));

            MemberInfo member       = null;
            object     cachedMember = checkMemberCache(objType, methodName);

            if (cachedMember != null)
            {
                var cachedMethod = cachedMember as lua.CFunction;
                if (cachedMethod != null)
                {
                    luaclr.pushcfunction(L, cachedMethod);
                    lua.pushboolean(L, true);
                    return(2);
                }
                Debug.Assert(cachedMember is MemberInfo);
                member = (MemberInfo)cachedMember;
            }
            else
            {
                MemberInfo[] members = objType.GetMember(methodName, bindingType | luanet.LuaBindingFlags);
                if (members.Length != 0)
                {
                    member = members[0];
                                        #if DEBUG
                    if (!(members.Length == 1 || member is MethodBase))                     // todo
                    {
                        return(luaL.error(L, "Overloads for members other than methods are not implemented."));
                    }
                                        #endif
                }
            }

            object value = null;

            switch (member == null ? MemberTypes.All : member.MemberType)
            {
            default:             // not found or found a constructor
                // kevinh - we want to throw an error because merely returning 'nil' in this case
                // is not sufficient.  valid data members may return nil and therefore there must be some
                // way to know the member just doesn't exist.
                return(luaL.error(L, string.Format("'{0}' does not contain a definition for '{1}'", objType.UnderlyingSystemType.FullName, methodName)));

            case MemberTypes.Method:
                var wrapper = new lua.CFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call);

                if (cachedMember == null)
                {
                    setMemberCache(objType, methodName, wrapper);
                }
                luaclr.pushcfunction(L, wrapper);
                lua.pushboolean(L, true);
                return(2);

            case MemberTypes.Field:
                if (!translator.memberIsAllowed(member))
                {
                    return(luaL.error(L, "field read failed (access denied)"));
                }
                try { value = ((FieldInfo)member).GetValue(obj); }
                catch { goto default; }
                translator.push(L, value);
                break;

            case MemberTypes.Property:
                // todo: support indexed properties
                if (!translator.memberIsAllowed(member))
                {
                    return(luaL.error(L, "property call failed (access denied)"));
                }
                try { value = ((PropertyInfo)member).GetValue(obj, null); }
                catch (TargetInvocationException ex) { return(translator.throwError(L, luaclr.verifyex(ex.InnerException))); }
                catch { goto default; }
                translator.push(L, value);
                break;

            case MemberTypes.Event:
                if (!translator.memberIsAllowed(member))
                {
                    return(luaL.error(L, "event read failed (access denied)"));
                }
                value = new RegisterEventHandler(translator.pendingEvents, obj, (EventInfo)member);
                translator.push(L, value);
                break;

            case MemberTypes.NestedType:
                var nestedType = (Type)member;
                if (translator.FindType(nestedType))                 // don't hand out class references unless loaded/whitelisted
                {
                    ObjectTranslator.pushType(L, nestedType);
                }
                else
                {
                    lua.pushnil(L);
                }
                break;
            }

            if (cachedMember == null)
            {
                setMemberCache(objType, methodName, member);
            }
            // push false because we are NOT returning a function (see luaIndexFunction)
            lua.pushboolean(L, false);
            return(2);
        }
Пример #50
0
        private void BindName(JSField inferenceTarget)
        {
            MemberInfo[] members = null;
            this.rootObject = this.rootObject.PartiallyEvaluate();
            IReflect obType = this.rootObjectInferredType = this.rootObject.InferType(inferenceTarget);

            if (this.rootObject is ConstantWrapper)
            {
                Object ob = Convert.ToObject2(this.rootObject.Evaluate(), this.Engine);
                if (ob == null)
                {
                    this.rootObject.context.HandleError(JSError.ObjectExpected);
                    return;
                }
                ClassScope csc = ob as ClassScope;
                Type       t   = ob as Type;
                if (csc != null || t != null)
                {
                    //object is a type. Look for static members on the type only. If none are found, look for instance members on type Type.
                    if (csc != null)
                    {
                        this.members = members = csc.GetMember(this.name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly);
                    }
                    else
                    {
                        this.members = members = t.GetMember(this.name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly);
                    }
                    if (members.Length > 0)
                    {
                        return;             //found a binding
                    }
                    //Look for instance members on type Type
                    this.members = members = Typeob.Type.GetMember(this.name, BindingFlags.Public | BindingFlags.Instance);
                    return;
                }
                Namespace ns = ob as Namespace;
                if (ns != null)
                {
                    String fullname = ns.Name + "." + this.name;
                    csc = this.Engine.GetClass(fullname);
                    if (csc != null)
                    {
                        FieldAttributes attrs = FieldAttributes.Literal;
                        if ((csc.owner.attributes & TypeAttributes.Public) == 0)
                        {
                            attrs |= FieldAttributes.Private;
                        }
                        this.members = new MemberInfo[] { new JSGlobalField(null, this.name, csc, attrs) };
                        return;
                    }
                    else
                    {
                        t = this.Engine.GetType(fullname);
                        if (t != null)
                        {
                            this.members = new MemberInfo[] { t };
                            return;
                        }
                    }
                }
                else if (ob is MathObject || ob is ScriptFunction && !(ob is FunctionObject)) //It is a built in constructor function
                {
                    obType = (IReflect)ob;
                }
            }
            obType = this.ProvideWrapperForPrototypeProperties(obType);

            //Give up and go late bound if not enough is known about the object at compile time.
            if (obType == Typeob.Object && !this.isNonVirtual) //The latter provides for super in classes that extend System.Object
            {
                this.members = new MemberInfo[0];
                return;
            }

            Type ty = obType as Type;

            //Interfaces are weird, call a helper
            if (ty != null && ty.IsInterface)
            {
                this.members = JSBinder.GetInterfaceMembers(this.name, ty);
                return;
            }
            ClassScope cs = obType as ClassScope;

            if (cs != null && cs.owner.isInterface)
            {
                this.members = cs.owner.GetInterfaceMember(this.name);
                return;
            }

            //Now run up the inheritance chain until a member is found
            while (obType != null)
            {
                cs = obType as ClassScope;
                if (cs != null)
                {
                    //The FlattenHierachy flag here tells ClassScope to add in any overloads found on base classes
                    members = this.members = obType.GetMember(this.name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.FlattenHierarchy);
                    if (members.Length > 0)
                    {
                        return;
                    }
                    obType = cs.GetSuperType();
                    continue;
                }
                ty = obType as Type;
                if (ty == null) //Dealing with the global scope via the this literal or with a built in object in fast mode
                {
                    this.members = obType.GetMember(this.name, BindingFlags.Public | BindingFlags.Instance);
                    return;
                }
                members = this.members = ty.GetMember(this.name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                if (members.Length > 0)
                {
                    MemberInfo mem = LateBinding.SelectMember(members);
                    if (mem == null)
                    {
                        //Found a method or methods. Need to add any overloads found in base classes.
                        //Do another lookup, this time with the DeclaredOnly flag cleared and asking only for methods
                        members = this.members = ty.GetMember(this.name, MemberTypes.Method, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                        if (members.Length == 0) //Dealing with an indexed property, ask again
                        {
                            this.members = ty.GetMember(this.name, MemberTypes.Property, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                        }
                    }
                    return;
                }
                obType = ty.BaseType;
            }
        }
Пример #51
0
        /// <summary>[-0, +0, e]
        /// Tries to set a named property or field.
        /// Returns false if unable to find the named member, true for success
        /// </summary>
        /// <exception cref="ArgumentNullException"><paramref name="targetType"/> is required</exception>
        bool trySetMember(lua.State L, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage)
        {
            Debug.Assert(interpreter.IsSameLua(L));
            Debug.Assert(targetType != null);
            Debug.Assert((target == null) == ((bindingType & BindingFlags.Static) == BindingFlags.Static));
            Debug.Assert((target == null) != ((bindingType & BindingFlags.Instance) == BindingFlags.Instance));
            detailMessage = null;               // No error yet

            // If not already a string just return - we don't want to call tostring - which has the side effect of
            // changing the lua typecode to string
            // Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
            // be true for isstring.
            if (lua.type(L, 2) != LUA.T.STRING)
            {
                detailMessage = "member names must be strings";
                return(false);
            }

            // We only look up property names by string
            string fieldName = lua.tostring(L, 2);

            if (fieldName.Length == 0 || !(Char.IsLetter(fieldName[0]) || fieldName[0] == '_'))
            {
                detailMessage = "invalid member name";
                return(false);
            }

            // Find our member via reflection or the cache
            MemberInfo member = checkMemberCache(targetType, fieldName) as MemberInfo;

            if (member == null)
            {
                MemberInfo[] members = targetType.GetMember(fieldName, bindingType | luanet.LuaBindingFlags);
                if (members.Length == 0)
                {
                    detailMessage = "member '" + fieldName + "' does not exist";
                    return(false);
                }
                member = members[0];
                if (!(member is MethodBase))
                {
                    Debug.Assert(members.Length == 1);                     // todo: support other overloads
                    setMemberCache(targetType, fieldName, member);
                }
            }

            object val;

            switch (member.MemberType)
            {
            case MemberTypes.Field:
                if (!translator.memberIsAllowed(member))
                {
                    luaL.error(L, "field write failed (access denied)");
                }
                var field = (FieldInfo)member;
                val = translator.getAsType(L, 3, field.FieldType);

                try
                {
                    field.SetValue(target, val);
                    return(true);
                }
                catch (Exception ex)
                {
                    detailMessage = "field write failed (" + ex.Message + ")";
                    return(false);
                }

            case MemberTypes.Property:
                if (!translator.memberIsAllowed(member))
                {
                    luaL.error(L, "property setter call failed (access denied)");
                }
                PropertyInfo property = (PropertyInfo)member;
                val = translator.getAsType(L, 3, property.PropertyType);

                try
                {
                    property.SetValue(target, val, null);
                    return(true);
                }
                catch (TargetInvocationException ex)
                {
                    translator.throwError(L, luaclr.verifyex(ex.InnerException));
                    return(false);                    // never returns
                }
                catch (Exception ex)
                {
                    detailMessage = "property setter call failed (" + ex.Message + ")";
                    return(false);
                }

            default:
                detailMessage = "'" + fieldName + "' is not a CLR field or property";
                return(false);
            }
        }
 private static IEnumerable <MemberInfo> GetInterfaceMembers(IReflect type)
 {
     return(type.GetMembers(BindingFlags.Public | BindingFlags.Instance)
            .Where(mi => mi.MemberType == MemberTypes.Field || mi.MemberType == MemberTypes.Property));
 }
Пример #53
0
 private static MethodInfo GetMethod(string funcName, IReflect type)
 {
     return(type.GetMethod(funcName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance));
 }
Пример #54
0
 private IEnumerable <string> GetConstantClassValues(IReflect constantClassType)
 {
     return(constantClassType.GetFields(BindingFlags.Public | BindingFlags.Static)
            .Select(field => ((ConstantClass)field.GetValue(null)).Value));
 }
Пример #55
0
        /// <summary>
        /// Tries to set a named property or field
        /// </summary>
        /// <param name="luaState"></param>
        /// <param name="targetType"></param>
        /// <param name="target"></param>
        /// <param name="bindingType"></param>
        /// <returns>false if unable to find the named member, true for success</returns>
        private bool trySetMember(KopiLua.Lua.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage)
        {
            detailMessage = null;   // No error yet

            // If not already a string just return - we don't want to call tostring - which has the side effect of
            // changing the lua typecode to string
            // Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
            // be true for isstring.
            if (LuaDLL.lua_type(luaState, 2) != LuaTypes.LUA_TSTRING)
            {
                detailMessage = "property names must be strings";
                return(false);
            }

            // We only look up property names by string
            string fieldName = LuaDLL.lua_tostring(luaState, 2);

            if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_'))
            {
                detailMessage = "invalid property name";
                return(false);
            }

            // Find our member via reflection or the cache
            MemberInfo member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName);

            if (member == null)
            {
                MemberInfo[] members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.NonPublic);
                if (members.Length > 0)
                {
                    member = members[0];
                    setMemberCache(memberCache, targetType, fieldName, member);
                }
                else
                {
                    detailMessage = "field or property '" + fieldName + "' does not exist";
                    return(false);
                }
            }

            if (member.MemberType == MemberTypes.Field)
            {
                FieldInfo field = (FieldInfo)member;
                object    val   = translator.getAsType(luaState, 3, field.FieldType);
                try
                {
                    field.SetValue(target, val);
                }
                catch (Exception e)
                {
                    ThrowError(luaState, e);
                }
                // We did a call
                return(true);
            }
            else if (member.MemberType == MemberTypes.Property)
            {
                PropertyInfo property = (PropertyInfo)member;
                object       val      = translator.getAsType(luaState, 3, property.PropertyType);
                try
                {
                    property.SetValue(target, val, null);
                }
                catch (Exception e)
                {
                    ThrowError(luaState, e);
                }
                // We did a call
                return(true);
            }

            detailMessage = "'" + fieldName + "' is not a .net field or property";
            return(false);
        }
Пример #56
0
        internal override AST PartiallyEvaluate()
        {
            if (this.alreadyPartiallyEvaluated)
            {
                return(this);
            }
            this.alreadyPartiallyEvaluated = true;
            if (this.inBrackets && this.AllParamsAreMissing())
            {
                if (this.isConstructor)
                {
                    this.args.context.HandleError(JSError.TypeMismatch);
                }
                return(new ConstantWrapper(new TypedArray(((TypeExpression) new TypeExpression(this.func).PartiallyEvaluate()).ToIReflect(), this.args.count + 1), base.context));
            }
            this.func = this.func.PartiallyEvaluateAsCallable();
            this.args = (ASTList)this.args.PartiallyEvaluate();
            IReflect[] argIRs = this.ArgIRs();
            this.func.ResolveCall(this.args, argIRs, this.isConstructor, this.inBrackets);
            if ((!this.isConstructor && !this.inBrackets) && ((this.func is Binding) && (this.args.count == 1)))
            {
                Binding func = (Binding)this.func;
                if (func.member is Type)
                {
                    Type            member  = (Type)func.member;
                    ConstantWrapper wrapper = this.args[0] as ConstantWrapper;
                    if (wrapper != null)
                    {
                        try
                        {
                            if ((wrapper.value == null) || (wrapper.value is DBNull))
                            {
                                return(this);
                            }
                            if (wrapper.isNumericLiteral && (((member == Typeob.Decimal) || (member == Typeob.Int64)) || ((member == Typeob.UInt64) || (member == Typeob.Single))))
                            {
                                return(new ConstantWrapper(Microsoft.JScript.Convert.CoerceT(wrapper.context.GetCode(), member, true), base.context));
                            }
                            return(new ConstantWrapper(Microsoft.JScript.Convert.CoerceT(wrapper.Evaluate(), member, true), base.context));
                        }
                        catch
                        {
                            wrapper.context.HandleError(JSError.TypeMismatch);
                            goto Label_0354;
                        }
                    }
                    if (!Binding.AssignmentCompatible(member, this.args[0], argIRs[0], false))
                    {
                        this.args[0].context.HandleError(JSError.ImpossibleConversion);
                    }
                }
                else if (func.member is JSVariableField)
                {
                    JSVariableField field = (JSVariableField)func.member;
                    if (field.IsLiteral)
                    {
                        if (field.value is ClassScope)
                        {
                            ClassScope scope = (ClassScope)field.value;
                            IReflect   underlyingTypeIfEnum = scope.GetUnderlyingTypeIfEnum();
                            if (underlyingTypeIfEnum != null)
                            {
                                if ((!Microsoft.JScript.Convert.IsPromotableTo(argIRs[0], underlyingTypeIfEnum) && !Microsoft.JScript.Convert.IsPromotableTo(underlyingTypeIfEnum, argIRs[0])) && ((argIRs[0] != Typeob.String) || (underlyingTypeIfEnum == scope)))
                                {
                                    this.args[0].context.HandleError(JSError.ImpossibleConversion);
                                }
                            }
                            else if (!Microsoft.JScript.Convert.IsPromotableTo(argIRs[0], scope) && !Microsoft.JScript.Convert.IsPromotableTo(scope, argIRs[0]))
                            {
                                this.args[0].context.HandleError(JSError.ImpossibleConversion);
                            }
                        }
                        else if (field.value is TypedArray)
                        {
                            TypedArray array = (TypedArray)field.value;
                            if (!Microsoft.JScript.Convert.IsPromotableTo(argIRs[0], array) && !Microsoft.JScript.Convert.IsPromotableTo(array, argIRs[0]))
                            {
                                this.args[0].context.HandleError(JSError.ImpossibleConversion);
                            }
                        }
                    }
                }
            }
Label_0354:
            return(this);
        }
Пример #57
0
 static Reflect()
 {
     Provider = new DefaultReflect();
     // 如果需要使用快速反射,启用下面这一行
     //Provider = new EmitReflect();
 }
Пример #58
0
        public HtmlToClrEventProxy()
        {
            Type htmlToClrEventProxyType = typeof(HtmlToClrEventProxy);

            typeIReflectImplementation = htmlToClrEventProxyType as IReflect;
        }
Пример #59
0
        protected MethodInfo GetOperator(IReflect ir1, IReflect ir2)
        {
            if (ir1 is ClassScope)
            {
                ir1 = ((ClassScope)ir1).GetUnderlyingTypeIfEnum();
            }
            if (ir2 is ClassScope)
            {
                ir2 = ((ClassScope)ir2).GetUnderlyingTypeIfEnum();
            }
            Type t1 = ir1 is Type ? (Type)ir1 : Typeob.Object;
            Type t2 = ir2 is Type ? (Type)ir2 : Typeob.Object;

            if (this.type1 == t1 && this.type2 == t2)
            {
                return(this.operatorMeth);
            }
            this.type1        = t1;
            this.type2        = t2;
            this.operatorMeth = null;
            if (t1 == Typeob.String || Convert.IsPrimitiveNumericType(ir1) || Typeob.JSObject.IsAssignableFrom(t1))
            {
                t1 = null;
            }
            if (t2 == Typeob.String || Convert.IsPrimitiveNumericType(ir2) || Typeob.JSObject.IsAssignableFrom(t2))
            {
                t2 = null;
            }
            if (t1 == null && t2 == null)
            {
                return(null);
            }
            //One of the operands is an object of a type that might have a user defined operator.
            String name = "op_NoSuchOp";

            switch (this.operatorTok)
            {
            case JSToken.BitwiseAnd: name = "op_BitwiseAnd"; break;

            case JSToken.BitwiseOr: name = "op_BitwiseOr"; break;

            case JSToken.BitwiseXor: name = "op_ExclusiveOr"; break;

            case JSToken.Divide: name = "op_Division"; break;

            case JSToken.Equal: name = "op_Equality"; break;

            case JSToken.GreaterThan: name = "op_GreaterThan"; break;

            case JSToken.GreaterThanEqual: name = "op_GreaterThanOrEqual"; break;

            case JSToken.LeftShift: name = "op_LeftShift"; break;

            case JSToken.LessThan: name = "op_LessThan"; break;

            case JSToken.LessThanEqual: name = "op_LessThanOrEqual"; break;

            case JSToken.Minus: name = "op_Subtraction"; break;

            case JSToken.Modulo: name = "op_Modulus"; break;

            case JSToken.Multiply: name = "op_Multiply"; break;

            case JSToken.NotEqual: name = "op_Inequality"; break;

            case JSToken.Plus: name = "op_Addition"; break;

            case JSToken.RightShift: name = "op_RightShift"; break;
            }
            Type[] types = new Type[] { this.type1, this.type2 };
            if (t1 == t2)
            {
                MethodInfo op = t1.GetMethod(name, BindingFlags.Public | BindingFlags.Static, JSBinder.ob, types, null);
                if (op != null && (op.Attributes & MethodAttributes.SpecialName) != 0 && op.GetParameters().Length == 2)
                {
                    this.operatorMeth = op;
                }
            }
            else
            {
                //Search both operand types, but only if there is a possibility that they might have operators defined on them
                MethodInfo op1 = t1 == null ? null : t1.GetMethod(name, BindingFlags.Public | BindingFlags.Static, JSBinder.ob, types, null);
                MethodInfo op2 = t2 == null ? null : t2.GetMethod(name, BindingFlags.Public | BindingFlags.Static, JSBinder.ob, types, null);
                this.operatorMeth = JSBinder.SelectOperator(op1, op2, this.type1, this.type2); //Choose the better of the two
            }
            if (this.operatorMeth != null)
            {
                this.operatorMeth = new JSMethodInfo(this.operatorMeth);
            }
            return(this.operatorMeth);
        }
Пример #60
0
        private int getMember(IntPtr luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType)
        {
            bool       flag       = false;
            MemberInfo memberInfo = null;
            object     obj2       = this.checkMemberCache(this.memberCache, objType, methodName);

            if (obj2 is LuaCSFunction)
            {
                this.translator.pushFunction(luaState, (LuaCSFunction)obj2);
                this.translator.push(luaState, true);
                return(2);
            }
            if (obj2 != null)
            {
                memberInfo = (MemberInfo)obj2;
            }
            else
            {
                MemberInfo[] member = objType.GetMember(methodName, bindingType | 16 | 1);
                if (member.Length > 0)
                {
                    memberInfo = member[0];
                }
                else
                {
                    member = objType.GetMember(methodName, bindingType | 8 | 16 | 1);
                    if (member.Length > 0)
                    {
                        memberInfo = member[0];
                        flag       = true;
                    }
                }
            }
            if (memberInfo != null)
            {
                if (memberInfo.get_MemberType() == 4)
                {
                    FieldInfo fieldInfo = (FieldInfo)memberInfo;
                    if (obj2 == null)
                    {
                        this.setMemberCache(this.memberCache, objType, methodName, memberInfo);
                    }
                    try
                    {
                        this.translator.push(luaState, fieldInfo.GetValue(obj));
                    }
                    catch
                    {
                        LuaDLL.lua_pushnil(luaState);
                    }
                }
                else if (memberInfo.get_MemberType() == 16)
                {
                    PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
                    if (obj2 == null)
                    {
                        this.setMemberCache(this.memberCache, objType, methodName, memberInfo);
                    }
                    try
                    {
                        object o = propertyInfo.GetGetMethod().Invoke(obj, null);
                        this.translator.push(luaState, o);
                    }
                    catch (ArgumentException)
                    {
                        if (objType is Type && (Type)objType != typeof(object))
                        {
                            return(this.getMember(luaState, ((Type)objType).get_BaseType(), obj, methodName, bindingType));
                        }
                        LuaDLL.lua_pushnil(luaState);
                    }
                    catch (TargetInvocationException e)
                    {
                        this.ThrowError(luaState, e);
                        LuaDLL.lua_pushnil(luaState);
                    }
                }
                else if (memberInfo.get_MemberType() == 2)
                {
                    EventInfo eventInfo = (EventInfo)memberInfo;
                    if (obj2 == null)
                    {
                        this.setMemberCache(this.memberCache, objType, methodName, memberInfo);
                    }
                    this.translator.push(luaState, new RegisterEventHandler(this.translator.pendingEvents, obj, eventInfo));
                }
                else if (!flag)
                {
                    if (memberInfo.get_MemberType() != 128)
                    {
                        LuaCSFunction luaCSFunction = new LuaCSFunction(new LuaMethodWrapper(this.translator, objType, methodName, bindingType).call);
                        if (obj2 == null)
                        {
                            this.setMemberCache(this.memberCache, objType, methodName, luaCSFunction);
                        }
                        this.translator.pushFunction(luaState, luaCSFunction);
                        this.translator.push(luaState, true);
                        return(2);
                    }
                    if (obj2 == null)
                    {
                        this.setMemberCache(this.memberCache, objType, methodName, memberInfo);
                    }
                    string name          = memberInfo.get_Name();
                    Type   declaringType = memberInfo.get_DeclaringType();
                    string className     = declaringType.get_FullName() + "+" + name;
                    Type   t             = this.translator.FindType(className);
                    this.translator.pushType(luaState, t);
                }
                else
                {
                    this.translator.throwError(luaState, "can't pass instance to static method " + methodName);
                    LuaDLL.lua_pushnil(luaState);
                }
            }
            else
            {
                this.translator.throwError(luaState, "unknown member name " + methodName);
                LuaDLL.lua_pushnil(luaState);
            }
            this.translator.push(luaState, false);
            return(2);
        }