コード例 #1
0
ファイル: DefaultBinder.cs プロジェクト: gaybro8777/ironruby
        private static ErrorInfo MakeIncorrectArgumentCountError(BindingTarget target)
        {
            int minArgs = Int32.MaxValue;
            int maxArgs = Int32.MinValue;

            foreach (int argCnt in target.ExpectedArgumentCount)
            {
                minArgs = System.Math.Min(minArgs, argCnt);
                maxArgs = System.Math.Max(maxArgs, argCnt);
            }

            return(ErrorInfo.FromException(
                       Ast.Call(
                           typeof(BinderOps).GetMethod("TypeErrorForIncorrectArgumentCount", new Type[] {
                typeof(string), typeof(int), typeof(int), typeof(int), typeof(int), typeof(bool), typeof(bool)
            }),
                           Ast.Constant(target.Name, typeof(string)), // name
                           Ast.Constant(minArgs),                     // min formal normal arg cnt
                           Ast.Constant(maxArgs),                     // max formal normal arg cnt
                           Ast.Constant(0),                           // default cnt
                           Ast.Constant(target.ActualArgumentCount),  // args provided
                           Ast.Constant(false),                       // hasArgList
                           Ast.Constant(false)                        // kwargs provided
                           )
                       ));
        }
コード例 #2
0
ファイル: RubyOverloadResolver.cs プロジェクト: ltwlf/IronSP
        internal void AddArgumentRestrictions(MetaObjectBuilder /*!*/ metaBuilder, BindingTarget /*!*/ bindingTarget)
        {
            var args           = GetActualArguments();
            var restrictedArgs = bindingTarget.Success ? bindingTarget.RestrictedArguments.GetObjects() : args.Arguments;

            for (int i = _firstRestrictedArg; i < restrictedArgs.Count; i++)
            {
                var arg = (bindingTarget.Success ? restrictedArgs[i] : restrictedArgs[i].Restrict(restrictedArgs[i].GetLimitType()));

                if (i >= args.FirstSplattedArg && i <= _lastSplattedArg)
                {
                    metaBuilder.AddCondition(arg.Restrictions.ToExpression());
                }
                else
                {
                    metaBuilder.AddRestriction(arg.Restrictions);
                }
            }

            // Adds condition for collapsed arguments - it is the same whether we succeed or not:
            var splatCondition = GetCollapsedArgsCondition();

            if (splatCondition != null)
            {
                metaBuilder.AddCondition(splatCondition);
            }
        }
コード例 #3
0
        private bool TryNumericComparison(OperatorInfo info)
        {
            MethodInfo[] targets = FilterNonMethods(_types[0], Binder.GetMember(Action, _types[0], "Compare"));
            if (targets.Length > 0)
            {
                MethodBinder  mb     = MethodBinder.MakeBinder(Binder, targets[0].Name, targets);
                BindingTarget target = mb.MakeBindingTarget(CallTypes.None, _types);
                if (target.Success)
                {
                    Expression call = Ast.Convert(target.MakeExpression(_rule, _rule.Parameters), typeof(int));
                    switch (info.Operator)
                    {
                    case Operators.GreaterThan: call = Ast.GreaterThan(call, Ast.Constant(0)); break;

                    case Operators.LessThan: call = Ast.LessThan(call, Ast.Constant(0)); break;

                    case Operators.GreaterThanOrEqual: call = Ast.GreaterThanOrEqual(call, Ast.Constant(0)); break;

                    case Operators.LessThanOrEqual: call = Ast.LessThanOrEqual(call, Ast.Constant(0)); break;

                    case Operators.Equals: call = Ast.Equal(call, Ast.Constant(0)); break;

                    case Operators.NotEquals: call = Ast.NotEqual(call, Ast.Constant(0)); break;

                    case Operators.Compare:
                        break;
                    }
                    _rule.Target = _rule.MakeReturn(Binder, call);
                    return(true);
                }
            }
            return(false);
        }
コード例 #4
0
        private Expression MakeAmbiguousCallError(BindingTarget target)
        {
            StringBuilder sb         = new StringBuilder(string.Format("Found multiple methods for '{0}': ", target.Name));
            string        outerComma = "";

            foreach (MethodCandidate candidate in target.AmbiguousMatches)
            {
                IList <ParameterWrapper> parameters = candidate.GetParameters();

                string innerComma = "";

                sb.Append(outerComma);
                sb.Append(target.Name);
                sb.Append('(');
                foreach (var param in parameters)
                {
                    if (!param.IsHidden)
                    {
                        sb.Append(innerComma);
                        sb.Append(Binder.GetTypeName(param.Type));
                        if (param.ProhibitNull)
                        {
                            sb.Append('!');
                        }
                        innerComma = ", ";
                    }
                }

                sb.Append(')');
                outerComma = ", ";
            }

            return(Methods.MakeAmbiguousMatchError.OpCall(AstUtils.Constant(sb.ToString())));
        }
コード例 #5
0
        private Expression MakeIncorrectArgumentCountError(BindingTarget target)
        {
            IList <int> available = target.ExpectedArgumentCount;
            int         expected;

            if (available.Count > 0)
            {
                int minGreater = Int32.MaxValue;
                int maxLesser  = Int32.MinValue;
                int max        = Int32.MinValue;
                foreach (int arity in available)
                {
                    if (arity > target.ActualArgumentCount)
                    {
                        minGreater = Math.Min(minGreater, arity);
                    }
                    else
                    {
                        maxLesser = Math.Max(maxLesser, arity);
                    }

                    max = Math.Max(max, arity);
                }

                expected = (target.ActualArgumentCount < maxLesser ? maxLesser : Math.Min(minGreater, max));
            }
            else
            {
                // no overload is callable:
                expected = 0;
            }

            return(Methods.MakeWrongNumberOfArgumentsError.OpCall(AstUtils.Constant(target.ActualArgumentCount), AstUtils.Constant(expected)));
        }
コード例 #6
0
        private MetaObject MakeMethodIndexRule(string oper, MetaObject[] args)
        {
            MethodInfo[] defaults = GetMethodsFromDefaults(args[0].LimitType.GetDefaultMembers(), oper);
            if (defaults.Length != 0)
            {
                MethodBinder binder = MethodBinder.MakeBinder(
                    this,
                    oper == StandardOperators.GetItem ? "get_Item" : "set_Item",
                    defaults);

                MetaObject[]        selfWithArgs = args;
                ParameterExpression arg2         = null;

                if (oper == StandardOperators.SetItem)
                {
                    Debug.Assert(args.Length >= 2);

                    // need to save arg2 in a temp because it's also our result
                    arg2 = Ast.Variable(args[2].Expression.Type, "arg2Temp");

                    args[2] = new MetaObject(
                        Ast.Assign(arg2, args[2].Expression),
                        args[2].Restrictions
                        );
                }

                BindingTarget target = binder.MakeBindingTarget(CallTypes.ImplicitInstance, selfWithArgs);

                Restrictions restrictions = Restrictions.Combine(args);

                if (target.Success)
                {
                    if (oper == StandardOperators.GetItem)
                    {
                        return(new MetaObject(
                                   target.MakeExpression(),
                                   restrictions.Merge(Restrictions.Combine(target.RestrictedArguments))
                                   ));
                    }
                    else
                    {
                        return(new MetaObject(
                                   Ast.Block(
                                       new ParameterExpression[] { arg2 },
                                       target.MakeExpression(),
                                       arg2
                                       ),
                                   restrictions.Merge(Restrictions.Combine(target.RestrictedArguments))
                                   ));
                    }
                }

                return(MakeError(
                           MakeInvalidParametersError(target),
                           restrictions
                           ));
            }

            return(null);
        }
コード例 #7
0
ファイル: DefaultBinder.cs プロジェクト: gaybro8777/ironruby
        private ErrorInfo MakeAmbiguousCallError(BindingTarget target)
        {
            StringBuilder sb         = new StringBuilder("Multiple targets could match: ");
            string        outerComma = "";

            foreach (MethodTarget mt in target.AmbiguousMatches)
            {
                Type[] types      = mt.GetParameterTypes();
                string innerComma = "";

                sb.Append(outerComma);
                sb.Append(target.Name);
                sb.Append('(');
                foreach (Type t in types)
                {
                    sb.Append(innerComma);
                    sb.Append(GetTypeName(t));
                    innerComma = ", ";
                }

                sb.Append(')');
                outerComma = ", ";
            }

            return(ErrorInfo.FromException(
                       Ast.Call(
                           typeof(BinderOps).GetMethod("SimpleTypeError"),
                           Ast.Constant(sb.ToString(), typeof(string))
                           )
                       ));
        }
コード例 #8
0
ファイル: ActionBinder.cs プロジェクト: stantoxt/dlr
        public DynamicMetaObject MakeCallExpression(OverloadResolverFactory resolverFactory, MethodInfo method, params DynamicMetaObject[] parameters)
        {
            OverloadResolver resolver;

            if (method.IsStatic)
            {
                resolver = resolverFactory.CreateOverloadResolver(parameters, new CallSignature(parameters.Length), CallTypes.None);
            }
            else
            {
                resolver = resolverFactory.CreateOverloadResolver(parameters, new CallSignature(parameters.Length - 1), CallTypes.ImplicitInstance);
            }
            BindingTarget target = resolver.ResolveOverload(method.Name, new MethodBase[] { method }, NarrowingLevel.None, NarrowingLevel.All);

            if (!target.Success)
            {
                BindingRestrictions restrictions = BindingRestrictions.Combine(parameters);
                foreach (DynamicMetaObject mo in parameters)
                {
                    restrictions = restrictions.Merge(BindingRestrictionsHelpers.GetRuntimeTypeRestriction(mo.Expression, mo.GetLimitType()));
                }
                return(DefaultBinder.MakeError(
                           resolver.MakeInvalidParametersError(target),
                           restrictions,
                           typeof(object)
                           ));
            }

            return(new DynamicMetaObject(target.MakeExpression(), target.RestrictedArguments.GetAllRestrictions()));
        }
コード例 #9
0
 private ErrorInfo MakeInvalidSplatteeError(BindingTarget target) {
     return ErrorInfo.FromException(
         Ast.Call(typeof(BinderOps).GetMethod("InvalidSplatteeError"), 
             AstUtils.Constant(target.Name),
             AstUtils.Constant(Binder.GetTypeName(_invalidSplattee.GetLimitType()))
         )
     );
 }
コード例 #10
0
 public override ErrorInfo MakeInvalidParametersError(BindingTarget target)
 {
     if (target.Result == BindingResult.InvalidArguments && _invalidSplattee != null)
     {
         return(MakeInvalidSplatteeError(target));
     }
     return(base.MakeInvalidParametersError(target));
 }
コード例 #11
0
ファイル: Reflector.cs プロジェクト: redchew-fork/clojure-clr
        /// <summary>
        /// Select matching method from list based on args.
        /// </summary>
        /// <param name="targetType"></param>
        /// <param name="args"></param>
        /// <param name="methods"></param>
        /// <param name="methodName"></param>
        /// <param name="isStatic"></param>
        /// <returns></returns>
        private static MethodBase GetMatchingMethodAux(Type targetType, IList <HostArg> args, IList <MethodBase> methods, string methodName, bool isStatic)
        {
            int argCount = args.Count;

            if (methods.Count == 0)
            {
                return(null);
            }

            if (methods.Count == 1)
            {
                return(methods[0]);
            }

            IList <DynamicMetaObject> argsPlus = new List <DynamicMetaObject>(argCount + (isStatic ? 0 : 1));

            if (!isStatic)
            {
                argsPlus.Add(new DynamicMetaObject(Expression.Default(targetType), BindingRestrictions.Empty));
            }

            foreach (HostArg ha in args)
            {
                Expr e       = ha.ArgExpr;
                Type argType = e.HasClrType ? (e.ClrType ?? typeof(object)) : typeof(Object);

                Type t;

                switch (ha.ParamType)
                {
                case HostArg.ParameterType.ByRef:
                    t = typeof(System.Runtime.CompilerServices.StrongBox <>).MakeGenericType(argType);
                    break;

                case HostArg.ParameterType.Standard:
                    t = argType;
                    break;

                default:
                    throw Util.UnreachableCode();
                }
                argsPlus.Add(new DynamicMetaObject(Expression.Default(t), BindingRestrictions.Empty));
            }

            // TODO: See if we can get rid of .Default
            OverloadResolverFactory factory = ClojureContext.Default.SharedOverloadResolverFactory;
            DefaultOverloadResolver res     = factory.CreateOverloadResolver(argsPlus, new CallSignature(argCount), isStatic ? CallTypes.None : CallTypes.ImplicitInstance);

            BindingTarget bt = res.ResolveOverload(methodName, methods, NarrowingLevel.None, NarrowingLevel.All);

            if (bt.Success)
            {
                return(bt.Overload.ReflectionInfo);
            }

            return(null);
        }
コード例 #12
0
        private DynamicMetaObject MakeMethodIndexRule(IndexType oper, OverloadResolverFactory resolverFactory, DynamicMetaObject[] args)
        {
            MethodInfo[] defaults = GetMethodsFromDefaults(args[0].GetLimitType().GetDefaultMembers(), oper);
            if (defaults.Length != 0)
            {
                DynamicMetaObject[] selfWithArgs = args;
                ParameterExpression arg2         = null;

                if (oper == IndexType.Set)
                {
                    Debug.Assert(args.Length >= 2);

                    // need to save arg2 in a temp because it's also our result
                    arg2 = Ast.Variable(args[2].Expression.Type, "arg2Temp");

                    args[2] = new DynamicMetaObject(
                        Ast.Assign(arg2, args[2].Expression),
                        args[2].Restrictions
                        );
                }

                BindingRestrictions restrictions = BindingRestrictions.Combine(args);

                var           resolver = resolverFactory.CreateOverloadResolver(selfWithArgs, new CallSignature(selfWithArgs.Length), CallTypes.ImplicitInstance);
                BindingTarget target   = resolver.ResolveOverload(oper == IndexType.Get ? "get_Item" : "set_Item", defaults, NarrowingLevel.None, NarrowingLevel.All);
                if (target.Success)
                {
                    if (oper == IndexType.Get)
                    {
                        return(new DynamicMetaObject(
                                   target.MakeExpression(),
                                   restrictions.Merge(target.RestrictedArguments.GetAllRestrictions())
                                   ));
                    }
                    else
                    {
                        return(new DynamicMetaObject(
                                   Ast.Block(
                                       new ParameterExpression[] { arg2 },
                                       target.MakeExpression(),
                                       arg2
                                       ),
                                   restrictions.Merge(target.RestrictedArguments.GetAllRestrictions())
                                   ));
                    }
                }

                return(MakeError(
                           resolver.MakeInvalidParametersError(target),
                           restrictions,
                           typeof(object)
                           ));
            }

            return(null);
        }
コード例 #13
0
        private Expression MakeCallFailureError(BindingTarget target)
        {
            foreach (CallFailure cf in target.CallFailures)
            {
                switch (cf.Reason)
                {
                case CallFailureReason.ConversionFailure:
                    foreach (ConversionResult cr in cf.ConversionResults)
                    {
                        if (cr.Failed)
                        {
                            if (typeof(Proc).IsAssignableFrom(cr.To))
                            {
                                return(Methods.CreateArgumentsErrorForProc.OpCall(AstUtils.Constant(cr.GetArgumentTypeName(Binder))));
                            }

                            Debug.Assert(typeof(BlockParam).IsSealed);
                            if (cr.To == typeof(BlockParam))
                            {
                                return(Methods.CreateArgumentsErrorForMissingBlock.OpCall());
                            }

                            string toType;
                            if (cr.To.IsGenericType && cr.To.GetGenericTypeDefinition() == typeof(Union <,>))
                            {
                                var g = cr.To.GetGenericArguments();
                                toType = Binder.GetTypeName(g[0]) + " or " + Binder.GetTypeName(g[1]);
                            }
                            else
                            {
                                toType = Binder.GetTypeName(cr.To);
                            }

                            return(Methods.CreateTypeConversionError.OpCall(
                                       AstUtils.Constant(cr.GetArgumentTypeName(Binder)),
                                       AstUtils.Constant(toType)
                                       ));
                        }
                    }
                    break;

                case CallFailureReason.TypeInference:
                    // TODO: Display generic parameters so it's clear what we couldn't infer.
                    return(Methods.CreateArgumentsError.OpCall(
                               AstUtils.Constant(String.Format("generic arguments could not be infered for method '{0}'", target.Name))
                               ));

                case CallFailureReason.DuplicateKeyword:
                case CallFailureReason.UnassignableKeyword:
                default:
                    throw new InvalidOperationException();
                }
            }
            throw new InvalidOperationException();
        }
コード例 #14
0
        private void MakeMethodBaseRule(MethodBase[] targets)
        {
            Type[]     argTypes; // will not include implicit instance argument (if any)
            SymbolId[] argNames; // will include ArgumentKind.Dictionary keyword names


            GetArgumentNamesAndTypes(out argNames, out argTypes);

            Type[]    bindingArgs = argTypes; // will include instance argument (if any)
            CallTypes callType    = CallTypes.None;

            if (_instance != null)
            {
                bindingArgs = ArrayUtils.Insert(InstanceType, argTypes);
                callType    = CallTypes.ImplicitInstance;
            }

            if (_reversedOperator && bindingArgs.Length >= 2)
            {
                // we swap the arguments before binding, and swap back before calling.
                ArrayUtils.SwapLastTwo(bindingArgs);
                if (argNames.Length >= 2)
                {
                    ArrayUtils.SwapLastTwo(argNames);
                }
            }

            // attempt to bind to an individual method
            MethodBinder  binder = MethodBinder.MakeBinder(Binder, GetTargetName(targets), targets, argNames, NarrowingLevel.None, _maxLevel);
            BindingTarget bt     = binder.MakeBindingTarget(callType, bindingArgs);

            if (bt.Success)
            {
                // if we succeed make the target for the rule
                MethodBase target       = bt.Method;
                MethodInfo targetMethod = target as MethodInfo;

                if (targetMethod != null)
                {
                    target = CompilerHelpers.GetCallableMethod(targetMethod, Binder.PrivateBinding);
                }

                Expression[] exprargs = FinishTestForCandidate(bt.ArgumentTests, argTypes);

                _rule.Target = _rule.MakeReturn(
                    Binder,
                    bt.MakeExpression(_rule, exprargs));
            }
            else
            {
                // make an error rule
                MakeInvalidParametersRule(bt);
            }
        }
コード例 #15
0
        public static Bindings For(Keys key, BindingTarget target = BindingTarget.Universal)
        {
            if (key == Keys.None)
            {
                return(Bindings.None);
            }

            Bindings b;

            return(KeyDictionaries[target].TryGetValue(key, out b) ? b : Bindings.None);
        }
コード例 #16
0
        public DataContextChangeSynchronizer(BindingSource bindingSource, BindingTarget bindingTarget, ITypeConverterProvider typeConverterProvider)
        {
            _bindingTarget = bindingTarget;
            Guard.ThrowIfNull(bindingTarget.Object, nameof(bindingTarget.Object));
            Guard.ThrowIfNull(bindingTarget.Property, nameof(bindingTarget.Property));
            Guard.ThrowIfNull(bindingSource.SourcePropertyPath, nameof(bindingSource.SourcePropertyPath));
            Guard.ThrowIfNull(bindingSource.Source, nameof(bindingSource.Source));
            Guard.ThrowIfNull(typeConverterProvider, nameof(typeConverterProvider));

            _bindingEndpoint             = new TargetBindingEndpoint(bindingTarget.Object, bindingTarget.Property);
            _sourceEndpoint              = new ObservablePropertyBranch(bindingSource.Source, bindingSource.SourcePropertyPath);
            _targetPropertyTypeConverter = typeConverterProvider.GetTypeConverter(bindingTarget.Property.PropertyType);
        }
コード例 #17
0
        private bool TryMakeInvertedBindingTarget(MethodInfo[] targets)
        {
            MethodBinder  mb     = MethodBinder.MakeBinder(Binder, targets[0].Name, targets);
            BindingTarget target = mb.MakeBindingTarget(CallTypes.None, _types);

            if (target.Success)
            {
                Expression call = target.MakeExpression(_rule, _rule.Parameters);
                _rule.Target = _rule.MakeReturn(Binder, Ast.Not(call));
                return(true);
            }
            return(false);
        }
コード例 #18
0
ファイル: DefaultBinder.cs プロジェクト: gaybro8777/ironruby
        public virtual ErrorInfo MakeInvalidParametersError(BindingTarget target)
        {
            switch (target.Result)
            {
            case BindingResult.CallFailure: return(MakeCallFailureError(target));

            case BindingResult.AmbiguousMatch: return(MakeAmbiguousCallError(target));

            case BindingResult.IncorrectArgumentCount: return(MakeIncorrectArgumentCountError(target));

            default: throw new InvalidOperationException();
            }
        }
コード例 #19
0
        public DataContextChangeSynchronizer(BindingSource bindingSource, BindingTarget bindingTarget, ITypeConverterProvider typeConverterProvider)
        {
            _bindingTarget = bindingTarget;
            Guard.ThrowIfNull(bindingTarget.Object, nameof(bindingTarget.Object));
            Guard.ThrowIfNull(bindingTarget.Property, nameof(bindingTarget.Property));
            Guard.ThrowIfNull(bindingSource.SourcePropertyPath, nameof(bindingSource.SourcePropertyPath));
            Guard.ThrowIfNull(bindingSource.Source, nameof(bindingSource.Source));
            Guard.ThrowIfNull(typeConverterProvider, nameof(typeConverterProvider));

            _bindingEndpoint = new TargetBindingEndpoint(bindingTarget.Object, bindingTarget.Property);
            _sourceEndpoint = new ObservablePropertyBranch(bindingSource.Source, bindingSource.SourcePropertyPath);
            _targetPropertyTypeConverter = typeConverterProvider.GetTypeConverter(bindingTarget.Property.PropertyType);
        }
コード例 #20
0
ファイル: DefaultBinder.Operations.cs プロジェクト: zuvys/dlr
        private DynamicMetaObject TryMakeInvertedBindingTarget(OverloadResolverFactory resolverFactory, MethodBase[] targets, DynamicMetaObject[] args)
        {
            var           resolver = resolverFactory.CreateOverloadResolver(args, new CallSignature(args.Length), CallTypes.None);
            BindingTarget target   = resolver.ResolveOverload(targets[0].Name, targets, NarrowingLevel.None, NarrowingLevel.All);

            if (target.Success)
            {
                return(new DynamicMetaObject(
                           Expression.Not(target.MakeExpression()),
                           target.RestrictedArguments.GetAllRestrictions()
                           ));
            }

            return(null);
        }
コード例 #21
0
        protected virtual IBindingSource GetBindingTarget([NotNull] IDataContext context, out object target, out IBindingPath targetPath)
        {
            target     = context.GetData(BindingBuilderConstants.Target, true);
            targetPath = context.GetData(BindingBuilderConstants.TargetPath, true);
            IBindingSource bindingSource = new BindingTarget(BindingServiceProvider.ObserverProvider.Observe(target, targetPath, false))
            {
                CommandParameterDelegate = context.GetData(BindingBuilderConstants.CommandParameter)
            };

            if (_decorators.Count != 0)
            {
                return(Decorate(bindingSource, true, context));
            }
            return(bindingSource);
        }
コード例 #22
0
        private MetaObject TryMakeBindingTarget(MethodInfo[] targets, MetaObject[] args, Expression codeContext, Restrictions restrictions)
        {
            MethodBinder mb = MethodBinder.MakeBinder(this, targets[0].Name, targets);

            BindingTarget target = mb.MakeBindingTarget(CallTypes.None, args);

            if (target.Success)
            {
                return(new MetaObject(
                           target.MakeExpression(new ParameterBinderWithCodeContext(this, codeContext)),
                           restrictions.Merge(Restrictions.Combine(target.RestrictedArguments))
                           ));
            }

            return(null);
        }
コード例 #23
0
        private MetaObject TryMakeInvertedBindingTarget(MethodBase[] targets, MetaObject[] args)
        {
            MethodBinder mb = MethodBinder.MakeBinder(this, targets[0].Name, targets);

            MetaObject[]  selfArgs = args;
            BindingTarget target   = mb.MakeBindingTarget(CallTypes.None, selfArgs);

            if (target.Success)
            {
                return(new MetaObject(
                           Ast.Not(target.MakeExpression()),
                           Restrictions.Combine(target.RestrictedArguments)
                           ));
            }

            return(null);
        }
コード例 #24
0
ファイル: DefaultBinder.cs プロジェクト: gaybro8777/ironruby
        private ErrorInfo MakeCallFailureError(BindingTarget target)
        {
            foreach (CallFailure cf in target.CallFailures)
            {
                switch (cf.Reason)
                {
                case CallFailureReason.ConversionFailure:
                    foreach (ConversionResult cr in cf.ConversionResults)
                    {
                        if (cr.Failed)
                        {
                            return(ErrorInfo.FromException(
                                       Ast.Call(
                                           typeof(BinderOps).GetMethod("SimpleTypeError"),
                                           Ast.Constant(String.Format("expected {0}, got {1}", GetTypeName(cr.To), GetTypeName(cr.From)))
                                           )
                                       ));
                        }
                    }
                    break;

                case CallFailureReason.DuplicateKeyword:
                    return(ErrorInfo.FromException(
                               Ast.Call(
                                   typeof(BinderOps).GetMethod("TypeErrorForDuplicateKeywordArgument"),
                                   Ast.Constant(target.Name, typeof(string)),
                                   Ast.Constant(SymbolTable.IdToString(cf.KeywordArguments[0]), typeof(string))     // TODO: Report all bad arguments?
                                   )
                               ));

                case CallFailureReason.UnassignableKeyword:
                    return(ErrorInfo.FromException(
                               Ast.Call(
                                   typeof(BinderOps).GetMethod("TypeErrorForExtraKeywordArgument"),
                                   Ast.Constant(target.Name, typeof(string)),
                                   Ast.Constant(SymbolTable.IdToString(cf.KeywordArguments[0]), typeof(string))     // TODO: Report all bad arguments?
                                   )
                               ));

                default: throw new InvalidOperationException();
                }
            }
            throw new InvalidOperationException();
        }
コード例 #25
0
        private MetaObject TryNumericComparison(OperatorInfo info, MetaObject[] args)
        {
            MethodInfo[] targets = FilterNonMethods(
                args[0].LimitType,
                GetMember(OldDoOperationAction.Make(this, info.Operator),
                          args[0].LimitType,
                          "Compare")
                );

            if (targets.Length > 0)
            {
                MethodBinder  mb     = MethodBinder.MakeBinder(this, targets[0].Name, targets);
                BindingTarget target = mb.MakeBindingTarget(CallTypes.None, args);
                if (target.Success)
                {
                    Expression call = AstUtils.Convert(target.MakeExpression(), typeof(int));
                    switch (info.Operator)
                    {
                    case Operators.GreaterThan: call = Ast.GreaterThan(call, Ast.Constant(0)); break;

                    case Operators.LessThan: call = Ast.LessThan(call, Ast.Constant(0)); break;

                    case Operators.GreaterThanOrEqual: call = Ast.GreaterThanOrEqual(call, Ast.Constant(0)); break;

                    case Operators.LessThanOrEqual: call = Ast.LessThanOrEqual(call, Ast.Constant(0)); break;

                    case Operators.Equals: call = Ast.Equal(call, Ast.Constant(0)); break;

                    case Operators.NotEquals: call = Ast.NotEqual(call, Ast.Constant(0)); break;

                    case Operators.Compare:
                        break;
                    }

                    return(new MetaObject(
                               call,
                               Restrictions.Combine(target.RestrictedArguments)
                               ));
                }
            }

            return(null);
        }
コード例 #26
0
ファイル: DefaultBinder.Operations.cs プロジェクト: zuvys/dlr
        private DynamicMetaObject TryNumericComparison(OperatorInfo info, OverloadResolverFactory resolverFactory, DynamicMetaObject[] args)
        {
            MethodInfo[] targets = FilterNonMethods(
                args[0].GetLimitType(),
                GetMember(
                    MemberRequestKind.Operation,
                    args[0].GetLimitType(),
                    "Compare"
                    )
                );

            if (targets.Length > 0)
            {
                var           resolver = resolverFactory.CreateOverloadResolver(args, new CallSignature(args.Length), CallTypes.None);
                BindingTarget target   = resolver.ResolveOverload(targets[0].Name, targets, NarrowingLevel.None, NarrowingLevel.All);
                if (target.Success)
                {
                    Expression call = AstUtils.Convert(target.MakeExpression(), typeof(int));
                    switch (info.Operator)
                    {
                    case ExpressionType.GreaterThan: call = Expression.GreaterThan(call, AstUtils.Constant(0)); break;

                    case ExpressionType.LessThan: call = Expression.LessThan(call, AstUtils.Constant(0)); break;

                    case ExpressionType.GreaterThanOrEqual: call = Expression.GreaterThanOrEqual(call, AstUtils.Constant(0)); break;

                    case ExpressionType.LessThanOrEqual: call = Expression.LessThanOrEqual(call, AstUtils.Constant(0)); break;

                    case ExpressionType.Equal: call = Expression.Equal(call, AstUtils.Constant(0)); break;

                    case ExpressionType.NotEqual: call = Expression.NotEqual(call, AstUtils.Constant(0)); break;
                    }

                    return(new DynamicMetaObject(
                               call,
                               target.RestrictedArguments.GetAllRestrictions()
                               ));
                }
            }

            return(null);
        }
コード例 #27
0
        private static void SetUnsafe(Bindings b, Keys k)
        {
            BindingTarget target = getBindingTarget(b);

            Dictionary <Keys, Bindings> KeyDictionary = getKeyDictionary(target);

            Keys kOld;

            if (BindingDictionary.TryGetValue(b, out kOld))
            {
                if (k == kOld)
                {
                    return;            //no change
                }
            }
            if (BindingDictionary.TryGetValue(b, out kOld) && kOld != Keys.None)
            {
                bool foundRebind = false;
                foreach (var v in BindingDictionary)
                {
                    if (v.Key != b && v.Value == kOld)
                    {
                        KeyDictionary[kOld] = v.Key;
                        foundRebind         = true;
                        break;
                    }
                }

                if (!foundRebind)
                {
                    KeyDictionary.Remove(kOld);
                }
            }

            BindingDictionary[b] = k;
            KeyDictionary[k]     = b;

            //Reset binding statics.
            ChatEngine.keySpamCheckArray = null;
        }
コード例 #28
0
        private void MakeInvalidParametersRule(BindingTarget bt)
        {
            MakeSplatTests();

            if (_args.Length > 1)
            {
                // we do an exact type check on all of the arguments types for a failed call.
                Expression[] argExpr = MakeArgumentExpressions();
                SymbolId[]   names;
                Type[]       vals;
                GetArgumentNamesAndTypes(out names, out vals);
                if (_instance != null)
                {
                    // target type was added to test already
                    argExpr = ArrayUtils.RemoveFirst(argExpr);
                }

                _test = Ast.AndAlso(_test, MakeNecessaryTests(_rule, vals, argExpr));
            }

            _rule.Target = Binder.MakeInvalidParametersError(bt).MakeErrorForRule(_rule, Binder);
        }
コード例 #29
0
ファイル: Reflector.cs プロジェクト: terkhorn/clojure-clr
        private static MethodBase GetMatchingMethodAux(Type targetType, object[] actualArgs, IList <MethodBase> methods, string methodName, bool isStatic)
        {
            int argCount = actualArgs.Length;

            if (methods.Count == 0)
            {
                return(null);
            }

            if (methods.Count == 1)
            {
                return(methods[0]);
            }

            IList <DynamicMetaObject> argsPlus = new List <DynamicMetaObject>(argCount + (isStatic ? 0 : 1));

            if (!isStatic)
            {
                argsPlus.Add(new DynamicMetaObject(Expression.Default(targetType), BindingRestrictions.Empty));
            }

            foreach (object arg in actualArgs)
            {
                argsPlus.Add(new DynamicMetaObject(Expression.Default(arg.GetType()), BindingRestrictions.Empty, arg));
            }

            OverloadResolverFactory factory = ClojureContext.Default.SharedOverloadResolverFactory;
            DefaultOverloadResolver res     = factory.CreateOverloadResolver(argsPlus, new CallSignature(argCount), isStatic ? CallTypes.None : CallTypes.ImplicitInstance);

            BindingTarget bt = res.ResolveOverload(methodName, methods, NarrowingLevel.None, NarrowingLevel.All);

            if (bt.Success)
            {
                return(bt.Overload.ReflectionInfo);
            }

            return(null);
        }
コード例 #30
0
ファイル: Class795.cs プロジェクト: newchild/Project-DayZero
 // Token: 0x06002F0D RID: 12045
 // RVA: 0x00131560 File Offset: 0x0012F760
 public static Bindings smethod_4(Keys keys_3, BindingTarget bindingTarget_0)
 {
     if (keys_3 == null)
     {
         return Bindings.None;
     }
     Bindings result;
     if (!Class795.dictionary_1[bindingTarget_0].TryGetValue(keys_3, out result))
     {
         return Bindings.None;
     }
     return result;
 }
コード例 #31
0
ファイル: SlotOrFunction.cs プロジェクト: gavz/IronKit
 public SlotOrFunction(BindingTarget /*!*/ function, DynamicMetaObject /*!*/ target)
 {
     _target   = target;
     _function = function;
 }
コード例 #32
0
        /// <summary>
        /// Helper for generating the call to a builtin function.  This is used for calls from built-in method
        /// descriptors and built-in functions w/ and w/o a bound instance.
        ///
        /// This provides all sorts of common checks on top of the call while the caller provides a delegate
        /// to do the actual call.  The common checks include:
        ///     check for generic-only methods
        ///     reversed operator support
        ///     transforming arguments so the default binder can understand them (currently user defined mapping types to PythonDictionary)
        ///     returning NotImplemented from binary operators
        ///     Warning when calling certain built-in functions
        ///
        /// </summary>
        /// <param name="call">The call binder we're doing the call for</param>
        /// <param name="codeContext">An expression which points to the code context</param>
        /// <param name="function">the meta object for the built in function</param>
        /// <param name="hasSelf">true if we're calling with an instance</param>
        /// <param name="args">The arguments being passed to the function</param>
        /// <param name="functionRestriction">A restriction for the built-in function, method desc, etc...</param>
        /// <param name="bind">A delegate to perform the actual call to the method.</param>
        internal DynamicMetaObject /*!*/ MakeBuiltinFunctionCall(DynamicMetaObjectBinder /*!*/ call, Expression /*!*/ codeContext, DynamicMetaObject /*!*/ function, DynamicMetaObject /*!*/[] args, bool hasSelf, BindingRestrictions /*!*/ functionRestriction, Func <DynamicMetaObject /*!*/[] /*!*/, BindingResult /*!*/> bind)
        {
            DynamicMetaObject res = null;

            // if we have a user defined operator for **args then transform it into a PythonDictionary
            DynamicMetaObject translated = TranslateArguments(call, codeContext, new DynamicMetaObject(function.Expression, functionRestriction, function.Value), args, hasSelf, Name);

            if (translated != null)
            {
                return(translated);
            }

            // swap the arguments if we have a reversed operator
            if (IsReversedOperator)
            {
                ArrayUtils.SwapLastTwo(args);
            }

            // do the appropriate calling logic
            BindingResult result = bind(args);

            // validate the result
            BindingTarget target = result.Target;

            res = result.MetaObject;

            if (target.Overload != null && target.Overload.IsProtected)
            {
                // report an error when calling a protected member
                res = new DynamicMetaObject(
                    BindingHelpers.TypeErrorForProtectedMember(
                        target.Overload.DeclaringType,
                        target.Overload.Name
                        ),
                    res.Restrictions
                    );
            }
            else if (IsBinaryOperator && args.Length == 2 && IsThrowException(res.Expression))
            {
                // Binary Operators return NotImplemented on failure.
                res = new DynamicMetaObject(
                    Ast.Property(null, typeof(PythonOps), "NotImplemented"),
                    res.Restrictions
                    );
            }
            else if (target.Overload != null)
            {
                // Add profiling information for this builtin function, if applicable
                IPythonSite pythonSite = (call as IPythonSite);
                if (pythonSite != null)
                {
                    var pc = pythonSite.Context;
                    var po = pc.Options as PythonOptions;
                    if (po != null && po.EnableProfiler)
                    {
                        Profiler profiler = Profiler.GetProfiler(pc);
                        res = new DynamicMetaObject(
                            profiler.AddProfiling(res.Expression, target.Overload.ReflectionInfo),
                            res.Restrictions
                            );
                    }
                }
            }

            // add any warnings that are applicable for calling this function
            WarningInfo info;

            if (target.Overload != null && BindingWarnings.ShouldWarn(PythonContext.GetPythonContext(call), target.Overload, out info))
            {
                res = info.AddWarning(codeContext, res);
            }

            // finally add the restrictions for the built-in function and return the result.
            res = new DynamicMetaObject(
                res.Expression,
                functionRestriction.Merge(res.Restrictions)
                );

            // The function can return something typed to boolean or int.
            // If that happens, we need to apply Python's boxing rules.
            if (res.Expression.Type.IsValueType())
            {
                res = BindingHelpers.AddPythonBoxing(res);
            }
            else if (res.Expression.Type == typeof(void))
            {
                res = new DynamicMetaObject(
                    Expression.Block(
                        res.Expression,
                        Expression.Constant(null)
                        ),
                    res.Restrictions
                    );
            }

            return(res);
        }
コード例 #33
0
ファイル: Class795.cs プロジェクト: newchild/Project-DayZero
 // Token: 0x06002F0A RID: 12042
 // RVA: 0x000233B1 File Offset: 0x000215B1
 private static Dictionary<Keys, Bindings> smethod_1(BindingTarget bindingTarget_0)
 {
     return Class795.dictionary_1[bindingTarget_0];
 }
コード例 #34
0
 public void SetBindingType(BindingTarget target)
 {
     this.BindingTarget = target;
 }