Exemple #1
0
        private static BuiltinFunction GetConstructorFunction(Type t, bool privateBinding)
        {
            BuiltinFunction ctorFunc = InstanceOps.NonDefaultNewInst;

            MethodBase[] ctors = PythonTypeOps.GetConstructors(t, privateBinding, true);

            return(GetConstructor(t, ctorFunc, ctors));
        }
Exemple #2
0
        public BuiltinFunctionInfo(BuiltinFunction function, ProjectState projectState)
            : base(ClrModule.GetPythonType(typeof(BuiltinFunction)), projectState)
        {
            // TODO: get return information, parameters, members
            _function = function;

            _returnTypes = Utils.GetReturnTypes(function, projectState);
            _doc         = null;
        }
Exemple #3
0
 private static BuiltinFunction CreateFunction(string name, params string[] methodNames)
 {
     MethodBase[] methods = new MethodBase[methodNames.Length];
     for (int i = 0; i < methods.Length; i++)
     {
         methods[i] = typeof(InstanceOps).GetMethod(methodNames[i]);
     }
     return(BuiltinFunction.MakeFunction(name, methods, typeof(object)));
 }
Exemple #4
0
        public static object OverloadedNewKW(CodeContext context, BuiltinFunction overloads\u00F8, PythonType type\u00F8, [ParamDictionary] IDictionary <object, object> kwargs\u00F8)
        {
            if (type\u00F8 == null)
            {
                throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8)));
            }

            return(overloads\u00F8.Call(context, null, null, ArrayUtils.EmptyObjects, kwargs\u00F8));
        }
        internal BuiltinFunctionOverloadResult(ProjectState state, BuiltinFunction overload, int removedParams, string name, params ParameterResult[] extraParams)
            : base(null, name)
        {
            _overload        = overload;
            _extraParameters = extraParams;
            _removedParams   = removedParams;
            _projectState    = state;

            CalculateDocumentation();
        }
Exemple #6
0
 override protected void ProcessBuiltinInvocation(BuiltinFunction function, MethodInvocationExpression node)
 {
     if (TypeSystemServices.IsQuackBuiltin(function))
     {
         BindDuck(node);
     }
     else
     {
         base.ProcessBuiltinInvocation(function, node);
     }
 }
Exemple #7
0
        public DynamicMetaObject /*!*/ Invoke(PythonInvokeBinder /*!*/ pythonInvoke, Expression /*!*/ codeContext, DynamicMetaObject /*!*/ target, DynamicMetaObject /*!*/[] /*!*/ args)
        {
            DynamicMetaObject translated = BuiltinFunction.TranslateArguments(pythonInvoke, codeContext, target, args, false, Value.Name);

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

            return(InvokeWorker(pythonInvoke, args, codeContext));
        }
Exemple #8
0
        public static Symbol AddExtern(this Intermediate.Module mod, string name, BuiltinFunction value)
        {
            var sym = new Symbol(value.Type, name)
            {
                IsConst     = true,
                IsExported  = false,
                Kind        = SymbolKind.Extern,
                Initializer = new Intermediate.FunctionLiteral(value),
            };

            mod.Symbols.Add(sym);
            return(sym);
        }
Exemple #9
0
        internal void Initialize(Window window, FrameworkElement element = null)
        {
            if (window == null)
            {
                throw new ArgumentNullException(nameof(window));
            }

            if (!window.IsInitialized)
            {
                throw new InvalidOperationException("Target Window has not been initialized.");
            }

            _targetWindow  = window;
            _targetElement = element;

            ForbearScaling = WillForbearScalingIfUnnecessary && BuiltinFunction.IsScalingSupported(_targetWindow);

            if (IsPerMonitorDpiAware)
            {
                MonitorDpi = DpiChecker.GetDpiFromVisual(_targetWindow);

                if (MonitorDpi.Equals(SystemDpi) || ForbearScaling)
                {
                    WindowDpi = MonitorDpi;
                }
                else
                {
                    var newInfo = new WindowInfo
                    {
                        Dpi    = MonitorDpi,
                        Width  = _targetWindow.Width * (double)MonitorDpi.X / SystemDpi.X,
                        Height = _targetWindow.Height * (double)MonitorDpi.Y / SystemDpi.Y,
                    };

                    Interlocked.Exchange(ref _dueInfo, newInfo);

                    ChangeDpi();
                }
            }
            else
            {
                MonitorDpi = SystemDpi;
                WindowDpi  = MonitorDpi;
            }

            ColorProfilePath = ColorProfileChecker.GetColorProfilePath(_targetWindow);

            _targetSource = PresentationSource.FromVisual(_targetWindow) as HwndSource;
            _targetSource?.AddHook(WndProc);
        }
Exemple #10
0
        /// <summary>
        /// Determines if a type member can be imported.  This is used to treat static types like modules.
        /// </summary>
        private static bool IsStaticTypeMemberInAll(CodeContext /*!*/ context, PythonType /*!*/ pt, string name, out object res)
        {
            PythonTypeSlot pts;

            res = null;
            if (pt.TryResolveSlot(context, name, out pts))
            {
                if (name == "__doc__" || name == "__class__")
                {
                    // these exist but we don't want to clobber __doc__ on import * or bring in __class__
                    return(false);
                }
                else if (pts is ReflectedGetterSetter)
                {
                    // property or indexer, these fetch the value at runtime, the user needs to explicitly
                    // import them using from type import property
                    return(false);
                }

                ReflectedField rf = pts as ReflectedField;
                if (rf != null && !rf._info.IsInitOnly && !rf._info.IsLiteral)
                {
                    // only bring in read-only fields, if the value can change the user needs to explicitly
                    // import by name
                    return(false);
                }

                BuiltinMethodDescriptor method = pts as BuiltinMethodDescriptor;
                if (method != null && (!method.DeclaringType.IsSealed() || !method.DeclaringType.IsAbstract()))
                {
                    // inherited object member on a static class (GetHashCode, Equals, etc...)
                    return(false);
                }

                BuiltinFunction bf = pts as BuiltinFunction;
                if (bf != null && (!bf.DeclaringType.IsSealed() || !bf.DeclaringType.IsAbstract()))
                {
                    // __new__/ReferenceEquals inherited from object
                    return(false);
                }

                if (pts.TryGetValue(context, null, pt, out res))
                {
                    return(true);
                }
            }

            res = null;
            return(false);
        }
 public static object Call(string path, CodeTree codeTree, string staticMethodName, string methodName, string functionName, BuiltinFunction builtinFunction, Type type, ExpressionCollection typeArguments, IEnumerable<object> args, Engine engine)
 {
     if (path != null)
         return engine.CallPath(path, codeTree, args);
     if (functionName != null)
         return engine.CallFunction(functionName, args);
     if (builtinFunction != 0)
         return engine.CallBuiltinFunction(builtinFunction, args);
     var typeArgs = typeArguments.Count != 0 ? typeArguments.Get(engine).Cast<Type>().ToArray() : null;
     if (staticMethodName != null)
         return CallHelper.CallMethod(staticMethodName, true, type, null, args, typeArgs, engine);
     if (methodName != null)
         return CallHelper.CallMethod(methodName, false, type ?? engine.Context.GetType(), engine.Context, args, typeArgs, engine);
     return engine.Throw("nothing to call");
 }
        internal static ConstructorFunction GetConstructor(Type type, BuiltinFunction realTarget, params MethodBase[] mems)
        {
            ConstructorFunction res = null;

            if (mems.Length != 0)
            {
                ReflectionCache.MethodBaseCache cache = new ReflectionCache.MethodBaseCache("__new__", mems);
                lock (_ctors) {
                    if (!_ctors.TryGetValue(cache, out res))
                    {
                        _ctors[cache] = res = new ConstructorFunction(realTarget, mems);
                    }
                }
            }

            return(res);
        }
Exemple #13
0
        internal static ISet <Namespace> GetReturnTypes(BuiltinFunction func, ProjectState projectState)
        {
            var result = new HashSet <Namespace>();
            var found  = new HashSet <Type>();

            foreach (var target in func.Overloads.Targets)
            {
                var targetInfo = (target as System.Reflection.MethodInfo);
                if (targetInfo != null && !found.Contains(targetInfo.ReturnType))
                {
                    var pyType = ClrModule.GetPythonType(targetInfo.ReturnType);
                    result.Add(((BuiltinClassInfo)projectState.GetNamespaceFromObjects(pyType)).Instance);
                    found.Add(targetInfo.ReturnType);
                }
            }
            return(result);
        }
        public object Call(Interpreter interpreter, List <object> args)
        {
            var instance = new BuiltinClass(
                name,
                superclass.Call(interpreter, args) as BuiltinClass,
                methods,
                staticMethods,
                true
                );

            BuiltinFunction constructor = GetMethod("constructor");

            if (constructor != null)
            {
                constructor.Bind(instance, superclass).Call(interpreter, args);
            }

            return(instance);
        }
        private static BuiltinFunction CheckAlwaysNotImplemented(BuiltinFunction xBf)
        {
            if (xBf != null)
            {
                bool returnsValue = false;
                foreach (MethodBase mb in xBf.Targets)
                {
                    if (mb.GetReturnType() != typeof(NotImplementedType))
                    {
                        returnsValue = true;
                        break;
                    }
                }

                if (!returnsValue)
                {
                    xBf = null;
                }
            }
            return(xBf);
        }
 public override object Get(int index, IScriptable start)
 {
     if (0 <= index && index < args.Length)
     {
         object value = args [index];
         if (value != UniqueTag.NotFound)
         {
             if (sharedWithActivation(index))
             {
                 BuiltinFunction f       = activation.function;
                 string          argName = f.getParamOrVarName(index);
                 value = activation.Get(argName, activation);
                 if (value == UniqueTag.NotFound)
                 {
                     Context.CodeBug();
                 }
             }
             return(value);
         }
     }
     return(base.Get(index, start));
 }
        static PythonCopyReg()
        {
            pythonReduceComplex = BuiltinFunction.MakeMethod(
                "pickle_complex",
                typeof(PythonCopyReg).GetMethod("ReduceComplex"),
                FunctionType.Function | FunctionType.PythonVisible
            );

            pythonReconstructor = BuiltinFunction.MakeMethod(
                "_reconstructor",
                typeof(PythonCopyReg).GetMethod("Reconstructor"),
                FunctionType.Function | FunctionType.PythonVisible
            );

            pythonCreateNewObject = BuiltinFunction.MakeMethod(
                "__newobj__",
                typeof(PythonCopyReg).GetMethod("NewObject"),
                FunctionType.Function | FunctionType.PythonVisible
            );

            dispatchTable[TypeCache.Complex64] = pythonReduceComplex;
        }
        /// <summary>
        /// Gets a builtin function for the given declaring type and member infos.
        ///
        /// Given the same inputs this always returns the same object ensuring there's only 1 builtinfunction
        /// for each .NET method.
        ///
        /// This method takes both a cacheName and a pythonName.  The cache name is the real method name.  The pythonName
        /// is the name of the method as exposed to Python.
        /// </summary>
        internal static BuiltinFunction /*!*/ GetBuiltinFunction(Type /*!*/ type, string /*!*/ cacheName, string /*!*/ pythonName, FunctionType?funcType, params MemberInfo /*!*/[] /*!*/ mems)
        {
            BuiltinFunction res = null;

            if (mems.Length != 0)
            {
                FunctionType ft = funcType ?? GetMethodFunctionType(type, mems);
                type = GetBaseDeclaringType(type, mems);

                BuiltinFunctionKey cache = new BuiltinFunctionKey(type, new ReflectionCache.MethodBaseCache(cacheName, GetNonBaseHelperMethodInfos(mems)), ft);

                lock (_functions) {
                    if (!_functions.TryGetValue(cache, out res))
                    {
                        if (PythonTypeOps.GetFinalSystemType(type) == type)
                        {
                            IList <MethodInfo> overriddenMethods = NewTypeMaker.GetOverriddenMethods(type, cacheName);

                            if (overriddenMethods.Count > 0)
                            {
                                List <MemberInfo> newMems = new List <MemberInfo>(mems);

                                foreach (MethodInfo mi in overriddenMethods)
                                {
                                    newMems.Add(mi);
                                }

                                mems = newMems.ToArray();
                            }
                        }

                        _functions[cache] = res = BuiltinFunction.MakeMethod(pythonName, ReflectionUtils.GetMethodInfos(mems), type, ft);
                    }
                }
            }

            return(res);
        }
        private bool sharedWithActivation(int index)
        {
            BuiltinFunction f            = activation.function;
            int             definedCount = f.ParamCount;

            if (index < definedCount)
            {
                // Check if argument is not hidden by later argument with the same
                // name as hidden arguments are not shared with activation
                if (index < definedCount - 1)
                {
                    string argName = f.getParamOrVarName(index);
                    for (int i = index + 1; i < definedCount; i++)
                    {
                        if (argName.Equals(f.getParamOrVarName(i)))
                        {
                            return(false);
                        }
                    }
                }
                return(true);
            }
            return(false);
        }
        public bool DeleteAttribute(object instance)
        {
            if (isSuperTypeMethod) {
                throw new NotImplementedException();
            }

            func = null;
            funcAsFunc = null;
            isSuperTypeMethod = true;
            UpdateFromBases(pythonType.MethodResolutionOrder);
            pythonType.UpdateSubclasses();
            return true;
        }
 internal ClassMethodDescriptor(BuiltinFunction func)
 {
     this.func = func;
 }
        internal static void CheckSelfWorker(object self, BuiltinFunction template)
        {
            // to a fast check on the CLR types, if they match we can avoid the slower
            // check that involves looking up dynamic types. (self can be null on
            // calls like set.add(None)
            if (self != null && self.GetType() == template.ClrDeclaringType) return;

            DynamicType selfType = self == null ? NoneTypeOps.TypeInstance : Ops.GetDynamicTypeFromType(self.GetType());
            Debug.Assert(selfType != null);

            ReflectedType declType = template.DeclaringType;
            if (!selfType.IsSubclassOf(declType)) {
                // if a conversion exists to the type allow the call.
                object converted;
                if (!Converter.TryConvert(self, declType.type, out converted) || converted == null) {
                    throw Ops.TypeError("descriptor {0} requires a {1} object but received a {2}",
                        Ops.Repr(template.Name),
                        Ops.Repr(template.DeclaringType.Name),
                        Ops.Repr(Ops.GetPythonTypeName(self)));
                }
            }
            return;
        }
 public ConstructorFunction(BuiltinFunction realTarget, MethodBase[] constructors)
     : base()
 {
     base.Name = "__new__";
     base.Targets = realTarget.Targets;
     base.FunctionType = realTarget.FunctionType;
     this.ctors = constructors;
 }
Exemple #24
0
 public static object OverloadedNewBasic(CodeContext context, SiteLocalStorage <CallSite <Func <CallSite, CodeContext, object, object[], object> > > storage, BuiltinFunction overloads\u00F8, PythonType type\u00F8, params object[] args\u00F8)
 {
     if (type\u00F8 == null)
     {
         throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8)));
     }
     if (args\u00F8 == null)
     {
         args\u00F8 = new object[1];
     }
     return(overloads\u00F8.Call(context, storage, null, args\u00F8));
 }
 public BoundBuiltinFunction(BuiltinFunction target, object instance)
 {
     this.target = target;
     this.instance = instance;
 }
 protected virtual object GetTargetFunction(BuiltinFunction bf)
 {
     return bf;
 }
Exemple #27
0
 public SpecializedBuiltinFunction(ProjectState state, BuiltinFunction function, Func <CallExpression, AnalysisUnit, ISet <Namespace>[], ISet <Namespace> > call)
     : base(function, state)
 {
     _call = call;
 }
 public BuiltinMethodDescriptor(BuiltinFunction function)
 {
     template = function;
 }
        // Use indexing on generic methods to provide a new reflected method with targets bound with
        // the supplied type arguments.
        public object this[object key]
        {
            get {
                // Retrieve the list of type arguments from the index.
                Type[] types;
                Tuple typesTuple = key as Tuple;

                if (typesTuple != null) {
                    types = new Type[typesTuple.Count];
                    for (int i = 0; i < types.Length; i++) {
                        types[i] = Converter.ConvertToType(typesTuple[i]);
                    }
                } else {
                    types = new Type[] { Converter.ConvertToType(key) };
                }

                // Start building a new ReflectedMethod that will contain targets with bound type
                // arguments.
                BuiltinFunction rm = new BuiltinFunction();

                // Search for generic targets with the correct arity (number of type parameters).
                // Compatible targets must be MethodInfos by definition (constructors never take
                // type arguments).
                int arity = types.Length;
                foreach (MethodBase mb in targets) {
                    MethodInfo mi = mb as MethodInfo;
                    if (mi == null)
                        continue;
                    if (mi.ContainsGenericParameters && mi.GetGenericArguments().Length == arity)
                        rm.AddMethod(mi.MakeGenericMethod(types));
                }
                if (rm.Targets == null)
                    throw Ops.TypeError(string.Format("bad type args to this generic method {0}", this));

                rm.Name = Name;
                rm.FunctionType = FunctionType | FunctionType.OptimizeChecked;    // don't want to optimize & whack our dictionary.

                return rm;
            }
        }
        internal IMember MakeObject(object obj)
        {
            if (obj == null)
            {
                return(null);
            }
            lock (this) {
                IMember res;
                if (!_members.TryGetValue(obj, out res))
                {
                    PythonModule mod = obj as PythonModule;
                    if (mod != null)
                    {
                        // FIXME: name
                        object name;
                        if (!mod.Get__dict__().TryGetValue("__name__", out name) || !(name is string))
                        {
                            name = "";
                        }
                        _members[obj] = res = new IronPythonModule(this, mod, (string)name);
                    }

                    PythonType type = obj as PythonType;
                    if (type != null)
                    {
                        _members[obj] = res = GetTypeFromType(type.__clrtype__());
                    }

                    BuiltinFunction func = obj as BuiltinFunction;
                    if (func != null)
                    {
                        _members[obj] = res = new IronPythonBuiltinFunction(this, func);
                    }

                    BuiltinMethodDescriptor methodDesc = obj as BuiltinMethodDescriptor;
                    if (methodDesc != null)
                    {
                        _members[obj] = res = new IronPythonBuiltinMethodDescriptor(this, methodDesc);
                    }

                    ReflectedField field = obj as ReflectedField;
                    if (field != null)
                    {
                        return(new IronPythonField(this, field));
                    }

                    ReflectedProperty prop = obj as ReflectedProperty;
                    if (prop != null)
                    {
                        _members[obj] = res = new IronPythonProperty(this, prop);
                    }

                    ReflectedExtensionProperty extProp = obj as ReflectedExtensionProperty;
                    if (extProp != null)
                    {
                        _members[obj] = res = new IronPythonExtensionProperty(this, extProp);
                    }

                    NamespaceTracker ns = obj as NamespaceTracker;
                    if (ns != null)
                    {
                        _members[obj] = res = new IronPythonNamespace(this, ns);
                    }

                    Method method = obj as Method;
                    if (method != null)
                    {
                        _members[obj] = res = new IronPythonGenericMember(this, method, PythonMemberType.Method);
                    }

                    var classMethod = obj as ClassMethodDescriptor;
                    if (classMethod != null)
                    {
                        _members[obj] = res = new IronPythonGenericMember(this, classMethod, PythonMemberType.Method);
                    }

                    var typeSlot = obj as PythonTypeTypeSlot;
                    if (typeSlot != null)
                    {
                        _members[obj] = res = new IronPythonGenericMember(this, typeSlot, PythonMemberType.Property);
                    }

                    ReflectedEvent eventObj = obj as ReflectedEvent;
                    if (eventObj != null)
                    {
                        return(new IronPythonEvent(this, eventObj));
                    }

                    if (res == null)
                    {
                        var genericTypeSlot = obj as PythonTypeSlot;
                        if (genericTypeSlot != null)
                        {
                            _members[obj] = res = new IronPythonGenericMember(this, genericTypeSlot, PythonMemberType.Property);
                        }
                    }

                    TypeGroup tg = obj as TypeGroup;
                    if (tg != null)
                    {
                        _members[obj] = res = new PythonObject <TypeGroup>(this, tg);
                    }

                    var attrType = (obj != null) ? obj.GetType() : typeof(DynamicNull);
                    if (attrType == typeof(bool) || attrType == typeof(int) || attrType == typeof(Complex) ||
                        attrType == typeof(string) || attrType == typeof(long) || attrType == typeof(double) ||
                        attrType.IsEnum || obj == null)
                    {
                        _members[obj] = res = new IronPythonConstant(this, obj);
                    }

                    if (res == null)
                    {
                        Debug.Assert(!(obj is bool));
                        _members[obj] = res = new PythonObject <object>(this, obj);
                    }
                }

                return(res);
            }
        }
 public static BuiltinFunction MakeOrAdd(BuiltinFunction existing, string name, MethodBase mi, FunctionType funcType)
 {
     if (existing != null) {
         existing.AddMethod(mi);
         return existing;
     } else {
         return MakeMethod(name, mi, funcType);
     }
 }
 public static object OverloadedNewBasic(ICallerContext context, BuiltinFunction overloads\u03bf, DynamicType type\u03c4, params object[] args\u03b1)
 {
     if (type\u03c4 == null) throw Ops.TypeError("__new__ expected type object, got {0}", Ops.StringRepr(Ops.GetDynamicType(type\u03c4)));
     if (args\u03b1 == null) args\u03b1 = new object[1];
     return overloads\u03bf.Call(context, args\u03b1);
 }
        private void FindMatchingTargets(Type[] sig, MethodBase[] targets, BuiltinFunction rm)
        {
            int args = sig.Length;

            foreach (MethodBase mb in targets) {
                ParameterInfo[] pis = mb.GetParameters();
                if (pis.Length != args)
                    continue;

                // Check each parameter type for an exact match.
                bool match = true;
                for (int i = 0; i < args; i++)
                    if (pis[i].ParameterType != sig[i]) {
                        match = false;
                        break;
                    }
                if (!match)
                    continue;

                // Okay, we have a match, add it to the list.
                rm.AddMethod(mb);
            }
        }
        public void SetDeclaredMethod(object m)
        {
            this.func = m;
            this.funcAsFunc = m as BuiltinFunction;
            this.isObjectMethod = pythonType.type == typeof(object);
            this.isBuiltinMethod = pythonType is ReflectedType;
            this.isSuperTypeMethod = false;

            pythonType.dict[this.name] = m;
        }
 public BuiltinFunctionOverloadMapper(BuiltinFunction builtinFunction, object instance)
 {
     this.function = builtinFunction;
     this.instance = instance;
 }
 private void UpdateFromBase(MethodWrapper mw)
 {
     func = mw.func;
     funcAsFunc = mw.func as BuiltinFunction;
     isObjectMethod = mw.isObjectMethod;
     isBuiltinMethod = mw.isBuiltinMethod;
     isSuperTypeMethod = true;
 }
Exemple #37
0
        // The "typeInstantiation" argument is passed in to help construct the result type of the function.
        Bpl.NAryExpr FunctionCall(Bpl.IToken tok, BuiltinFunction f, Bpl.Type typeInstantiation, params Bpl.Expr[] args)
        {
            Contract.Requires(tok != null);
            Contract.Requires(args != null);
            Contract.Requires(predef != null);
            Contract.Ensures(Contract.Result <Bpl.NAryExpr>() != null);

            switch (f)
            {
            case BuiltinFunction.LitInt:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "LitInt", Bpl.Type.Int, args));

            case BuiltinFunction.LitReal:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "LitReal", Bpl.Type.Real, args));

            case BuiltinFunction.Lit:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "Lit", typeInstantiation, args));

            case BuiltinFunction.LayerSucc:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "$LS", predef.LayerType, args));

            case BuiltinFunction.AsFuelBottom:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "AsFuelBottom", predef.LayerType, args));

            case BuiltinFunction.CharFromInt:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "char#FromInt", predef.CharType, args));

            case BuiltinFunction.CharToInt:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "char#ToInt", predef.CharType, args));

            case BuiltinFunction.Is:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "$Is", Bpl.Type.Bool, args));

            case BuiltinFunction.IsBox:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "$IsBox", Bpl.Type.Bool, args));

            case BuiltinFunction.IsAlloc:
                Contract.Assert(args.Length == 3);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "$IsAlloc", Bpl.Type.Bool, args));

            case BuiltinFunction.IsAllocBox:
                Contract.Assert(args.Length == 3);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "$IsAllocBox", Bpl.Type.Bool, args));

            case BuiltinFunction.IsTraitParent:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "IsTraitParent", Bpl.Type.Bool, args));

            case BuiltinFunction.SetCard:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Set#Card", Bpl.Type.Int, args));

            case BuiltinFunction.SetEmpty: {
                Contract.Assert(args.Length == 0);
                Contract.Assert(typeInstantiation != null);
                Bpl.Type resultType = predef.SetType(tok, true, typeInstantiation);
                return(Bpl.Expr.CoerceType(tok, FunctionCall(tok, "Set#Empty", resultType, args), resultType));
            }

            case BuiltinFunction.SetUnionOne:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "Set#UnionOne", predef.SetType(tok, true, typeInstantiation), args));

            case BuiltinFunction.SetUnion:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "Set#Union", predef.SetType(tok, true, typeInstantiation), args));

            case BuiltinFunction.SetIntersection:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "Set#Intersection", predef.SetType(tok, true, typeInstantiation), args));

            case BuiltinFunction.SetDifference:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "Set#Difference", predef.SetType(tok, true, typeInstantiation), args));

            case BuiltinFunction.SetEqual:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Set#Equal", Bpl.Type.Bool, args));

            case BuiltinFunction.SetSubset:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Set#Subset", Bpl.Type.Bool, args));

            case BuiltinFunction.SetDisjoint:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Set#Disjoint", Bpl.Type.Bool, args));

            case BuiltinFunction.ISetEmpty: {
                Contract.Assert(args.Length == 0);
                Contract.Assert(typeInstantiation != null);
                Bpl.Type resultType = predef.SetType(tok, false, typeInstantiation);
                return(Bpl.Expr.CoerceType(tok, FunctionCall(tok, "ISet#Empty", resultType, args), resultType));
            }

            case BuiltinFunction.ISetUnionOne:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "ISet#UnionOne", predef.SetType(tok, false, typeInstantiation), args));

            case BuiltinFunction.ISetUnion:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "ISet#Union", predef.SetType(tok, false, typeInstantiation), args));

            case BuiltinFunction.ISetIntersection:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "ISet#Intersection", predef.SetType(tok, false, typeInstantiation), args));

            case BuiltinFunction.ISetDifference:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "ISet#Difference", predef.SetType(tok, false, typeInstantiation), args));

            case BuiltinFunction.ISetEqual:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "ISet#Equal", Bpl.Type.Bool, args));

            case BuiltinFunction.ISetSubset:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "ISet#Subset", Bpl.Type.Bool, args));

            case BuiltinFunction.ISetDisjoint:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "ISet#Disjoint", Bpl.Type.Bool, args));

            case BuiltinFunction.MultiSetCard:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "MultiSet#Card", Bpl.Type.Int, args));

            case BuiltinFunction.MultiSetEmpty: {
                Contract.Assert(args.Length == 0);
                Contract.Assert(typeInstantiation != null);
                Bpl.Type resultType = predef.MultiSetType(tok, typeInstantiation);
                return(Bpl.Expr.CoerceType(tok, FunctionCall(tok, "MultiSet#Empty", resultType, args), resultType));
            }

            case BuiltinFunction.MultiSetUnionOne:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "MultiSet#UnionOne", predef.MultiSetType(tok, typeInstantiation), args));

            case BuiltinFunction.MultiSetUnion:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "MultiSet#Union", predef.MultiSetType(tok, typeInstantiation), args));

            case BuiltinFunction.MultiSetIntersection:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "MultiSet#Intersection", predef.MultiSetType(tok, typeInstantiation), args));

            case BuiltinFunction.MultiSetDifference:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "MultiSet#Difference", predef.MultiSetType(tok, typeInstantiation), args));

            case BuiltinFunction.MultiSetEqual:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "MultiSet#Equal", Bpl.Type.Bool, args));

            case BuiltinFunction.MultiSetSubset:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "MultiSet#Subset", Bpl.Type.Bool, args));

            case BuiltinFunction.MultiSetDisjoint:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "MultiSet#Disjoint", Bpl.Type.Bool, args));

            case BuiltinFunction.MultiSetFromSet:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "MultiSet#FromSet", predef.MultiSetType(tok, typeInstantiation), args));

            case BuiltinFunction.MultiSetFromSeq:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "MultiSet#FromSeq", predef.MultiSetType(tok, typeInstantiation), args));

            case BuiltinFunction.IsGoodMultiSet:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "$IsGoodMultiSet", Bpl.Type.Bool, args));

            case BuiltinFunction.SeqLength:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Seq#Length", Bpl.Type.Int, args));

            case BuiltinFunction.SeqEmpty: {
                Contract.Assert(args.Length == 0);
                Contract.Assert(typeInstantiation != null);
                Bpl.Type resultType = predef.SeqType(tok, typeInstantiation);
                return(Bpl.Expr.CoerceType(tok, FunctionCall(tok, "Seq#Empty", resultType, args), resultType));
            }

            case BuiltinFunction.SeqBuild:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "Seq#Build", predef.SeqType(tok, typeInstantiation), args));

            case BuiltinFunction.SeqAppend:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "Seq#Append", predef.SeqType(tok, typeInstantiation), args));

            case BuiltinFunction.SeqIndex:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "Seq#Index", typeInstantiation, args));

            case BuiltinFunction.SeqUpdate:
                Contract.Assert(args.Length == 3);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "Seq#Update", predef.SeqType(tok, typeInstantiation), args));

            case BuiltinFunction.SeqContains:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Seq#Contains", Bpl.Type.Bool, args));

            case BuiltinFunction.SeqDrop:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "Seq#Drop", predef.SeqType(tok, typeInstantiation), args));

            case BuiltinFunction.SeqTake:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "Seq#Take", predef.SeqType(tok, typeInstantiation), args));

            case BuiltinFunction.SeqEqual:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Seq#Equal", Bpl.Type.Bool, args));

            case BuiltinFunction.SeqSameUntil:
                Contract.Assert(args.Length == 3);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Seq#SameUntil", Bpl.Type.Bool, args));

            case BuiltinFunction.SeqFromArray:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "Seq#FromArray", typeInstantiation, args));

            case BuiltinFunction.SeqRank:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Seq#Rank", Bpl.Type.Int, args));

            case BuiltinFunction.MapEmpty: {
                Contract.Assert(args.Length == 0);
                Contract.Assert(typeInstantiation != null);
                Bpl.Type resultType = predef.MapType(tok, true, typeInstantiation, typeInstantiation); // use 'typeInstantiation' (which is really always just BoxType anyway) as both type arguments
                return(Bpl.Expr.CoerceType(tok, FunctionCall(tok, "Map#Empty", resultType, args), resultType));
            }

            case BuiltinFunction.MapCard:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Map#Card", Bpl.Type.Int, args));

            case BuiltinFunction.MapDomain:
                Contract.Assert(args.Length == 1);
                return(FunctionCall(tok, "Map#Domain", typeInstantiation, args));

            case BuiltinFunction.MapElements:
                Contract.Assert(args.Length == 1);
                return(FunctionCall(tok, "Map#Elements", typeInstantiation, args));

            case BuiltinFunction.MapGlue:
                Contract.Assert(args.Length == 3);
                return(FunctionCall(tok, "Map#Glue", predef.MapType(tok, true, predef.BoxType, predef.BoxType), args));

            case BuiltinFunction.MapEqual:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Map#Equal", Bpl.Type.Bool, args));

            case BuiltinFunction.MapDisjoint:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Map#Disjoint", Bpl.Type.Bool, args));

            case BuiltinFunction.MapUnion:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "Map#Disjoint", typeInstantiation, args));

            case BuiltinFunction.IMapEmpty: {
                Contract.Assert(args.Length == 0);
                Contract.Assert(typeInstantiation != null);
                Bpl.Type resultType = predef.MapType(tok, false, typeInstantiation, typeInstantiation); // use 'typeInstantiation' (which is really always just BoxType anyway) as both type arguments
                return(Bpl.Expr.CoerceType(tok, FunctionCall(tok, "IMap#Empty", resultType, args), resultType));
            }

            case BuiltinFunction.IMapDomain:
                Contract.Assert(args.Length == 1);
                return(FunctionCall(tok, "IMap#Domain", typeInstantiation, args));

            case BuiltinFunction.IMapElements:
                Contract.Assert(args.Length == 1);
                return(FunctionCall(tok, "IMap#Elements", typeInstantiation, args));

            case BuiltinFunction.IMapGlue:
                Contract.Assert(args.Length == 3);
                return(FunctionCall(tok, "IMap#Glue", predef.MapType(tok, false, predef.BoxType, predef.BoxType), args));

            case BuiltinFunction.IMapEqual:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "IMap#Equal", Bpl.Type.Bool, args));

            case BuiltinFunction.IndexField:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "IndexField", predef.FieldName(tok, predef.BoxType), args));

            case BuiltinFunction.MultiIndexField:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "MultiIndexField", predef.FieldName(tok, predef.BoxType), args));

            case BuiltinFunction.Box:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "$Box", predef.BoxType, args));

            case BuiltinFunction.Unbox:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation != null);
                return(Bpl.Expr.CoerceType(tok, FunctionCall(tok, "$Unbox", typeInstantiation, args), typeInstantiation));

            case BuiltinFunction.RealToInt:
                Contract.Assume(args.Length == 1);
                Contract.Assume(typeInstantiation == null);
                return(FunctionCall(tok, "Int", Bpl.Type.Int, args));

            case BuiltinFunction.IntToReal:
                Contract.Assume(args.Length == 1);
                Contract.Assume(typeInstantiation == null);
                return(FunctionCall(tok, "Real", Bpl.Type.Real, args));

            case BuiltinFunction.IsGoodHeap:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "$IsGoodHeap", Bpl.Type.Bool, args));

            case BuiltinFunction.IsHeapAnchor:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "$IsHeapAnchor", Bpl.Type.Bool, args));

            case BuiltinFunction.HeapSucc:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "$HeapSucc", Bpl.Type.Bool, args));

            case BuiltinFunction.HeapSuccGhost:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "$HeapSuccGhost", Bpl.Type.Bool, args));

            case BuiltinFunction.DynamicType:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "dtype", predef.ClassNameType, args));

            case BuiltinFunction.TypeTuple:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "TypeTuple", predef.ClassNameType, args));

            case BuiltinFunction.DeclType:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "DeclType", predef.ClassNameType, args));

            case BuiltinFunction.FieldOfDecl:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "FieldOfDecl", predef.FieldName(tok, typeInstantiation), args));

            case BuiltinFunction.FDim:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "FDim", Bpl.Type.Int, args));

            case BuiltinFunction.IsGhostField:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "$IsGhostField", Bpl.Type.Bool, args));

            case BuiltinFunction.DatatypeCtorId:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "DatatypeCtorId", predef.DtCtorId, args));

            case BuiltinFunction.DtRank:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "DtRank", Bpl.Type.Int, args));

            case BuiltinFunction.BoxRank:
                Contract.Assert(args.Length == 1);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "BoxRank", Bpl.Type.Int, args));

            case BuiltinFunction.GenericAlloc:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation == null);
                return(FunctionCall(tok, "GenericAlloc", Bpl.Type.Bool, args));

            case BuiltinFunction.AtLayer:
                Contract.Assert(args.Length == 2);
                Contract.Assert(typeInstantiation != null);
                return(FunctionCall(tok, "AtLayer", typeInstantiation, args));

            default:
                Contract.Assert(false); throw new cce.UnreachableException(); // unexpected built-in function
            }
        }
Exemple #38
0
 public BuiltinInitAdapter(ArgumentValues /*!*/ ai, BuiltinFunction /*!*/ method, PythonContext /*!*/ state, Expression /*!*/ codeContext)
     : base(ai, state, codeContext)
 {
     _method = method;
 }
        public double Arity()
        {
            BuiltinFunction constructor = GetMethod("constructor");

            return(constructor != null?constructor.Arity() : 0);
        }
Exemple #40
0
        /// <summary>
        /// Creating a Python type involves calling __new__ and __init__.  We resolve them
        /// and generate calls to either the builtin funcions directly or embed sites which
        /// call the slots at runtime.
        /// </summary>
        private DynamicMetaObject /*!*/ MakePythonTypeCall(DynamicMetaObjectBinder /*!*/ call, Expression /*!*/ codeContext, DynamicMetaObject /*!*/[] /*!*/ args)
        {
            ValidationInfo valInfo = MakeVersionCheck();

            DynamicMetaObject self = new RestrictedMetaObject(
                AstUtils.Convert(Expression, LimitType),
                BindingRestrictionsHelpers.GetRuntimeTypeRestriction(Expression, LimitType),
                Value
                );
            CallSignature  sig = BindingHelpers.GetCallSignature(call);
            ArgumentValues ai  = new ArgumentValues(sig, self, args);
            NewAdapter     newAdapter;
            InitAdapter    initAdapter;

            if (TooManyArgsForDefaultNew(call, args))
            {
                return(MakeIncorrectArgumentsForCallError(call, ai, valInfo));
            }
            else if (Value.UnderlyingSystemType.IsGenericTypeDefinition)
            {
                return(MakeGenericTypeDefinitionError(call, ai, valInfo));
            }
            else if (Value.HasAbstractMethods(PythonContext.GetPythonContext(call).SharedContext))
            {
                return(MakeAbstractInstantiationError(call, ai, valInfo));
            }

            DynamicMetaObject translated = BuiltinFunction.TranslateArguments(call, codeContext, self, args, false, Value.Name);

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

            GetAdapters(ai, call, codeContext, out newAdapter, out initAdapter);
            PythonContext state = PythonContext.GetPythonContext(call);

            // get the expression for calling __new__
            DynamicMetaObject createExpr = newAdapter.GetExpression(state.Binder);

            if (createExpr.Expression.Type == typeof(void))
            {
                return(BindingHelpers.AddDynamicTestAndDefer(
                           call,
                           createExpr,
                           args,
                           valInfo
                           ));
            }

            Expression          res;
            BindingRestrictions additionalRestrictions = BindingRestrictions.Empty;

            if (!Value.IsSystemType && (!(newAdapter is DefaultNewAdapter) || HasFinalizer(call)))
            {
                // we need to dynamically check the return value to see if it's a subtype of
                // the type that we are calling.  If it is then we need to call __init__/__del__
                // for the actual returned type.
                res = Expression.Dynamic(
                    Value.GetLateBoundInitBinder(sig),
                    typeof(object),
                    ArrayUtils.Insert(
                        codeContext,
                        Expression.Convert(createExpr.Expression, typeof(object)),
                        DynamicUtils.GetExpressions(args)
                        )
                    );
                additionalRestrictions = createExpr.Restrictions;
            }
            else
            {
                // just call the __init__ method, built-in types currently have
                // no wacky return values which don't return the derived type.

                // then get the statement for calling __init__
                ParameterExpression allocatedInst = Ast.Variable(createExpr.GetLimitType(), "newInst");
                Expression          tmpRead       = allocatedInst;
                DynamicMetaObject   initCall      = initAdapter.MakeInitCall(
                    state.Binder,
                    new RestrictedMetaObject(
                        AstUtils.Convert(allocatedInst, Value.UnderlyingSystemType),
                        createExpr.Restrictions
                        )
                    );

                List <Expression> body = new List <Expression>();
                Debug.Assert(!HasFinalizer(call));

                // add the call to init if we need to
                if (initCall.Expression != tmpRead)
                {
                    // init can fail but if __new__ returns a different type
                    // no exception is raised.
                    DynamicMetaObject initStmt = initCall;

                    if (body.Count == 0)
                    {
                        body.Add(
                            Ast.Assign(allocatedInst, createExpr.Expression)
                            );
                    }

                    if (!Value.UnderlyingSystemType.IsAssignableFrom(createExpr.Expression.Type))
                    {
                        // return type of object, we need to check the return type before calling __init__.
                        body.Add(
                            AstUtils.IfThen(
                                Ast.TypeIs(allocatedInst, Value.UnderlyingSystemType),
                                initStmt.Expression
                                )
                            );
                    }
                    else
                    {
                        // just call the __init__ method, no type check necessary (TODO: need null check?)
                        body.Add(initStmt.Expression);
                    }
                }

                // and build the target from everything we have
                if (body.Count == 0)
                {
                    res = createExpr.Expression;
                }
                else
                {
                    body.Add(allocatedInst);
                    res = Ast.Block(body);
                }
                res = Ast.Block(new ParameterExpression[] { allocatedInst }, res);

                additionalRestrictions = initCall.Restrictions;
            }

            return(BindingHelpers.AddDynamicTestAndDefer(
                       call,
                       new DynamicMetaObject(
                           res,
                           self.Restrictions.Merge(additionalRestrictions)
                           ),
                       ArrayUtils.Insert(this, args),
                       valInfo
                       ));
        }
 protected override object GetTargetFunction(BuiltinFunction bf)
 {
     // return a function that's bound to the overloads, we'll
     // the user then calls this w/ the dynamic type, and the bound
     // function drops the class & calls the overload.
     if (bf.Targets[0].DeclaringType != typeof(InstanceOps))
         return new BoundBuiltinFunction(new ConstructorFunction(InstanceOps.OverloadedNew, bf.Targets), bf);
     return base.GetTargetFunction(bf);
 }
Exemple #42
0
 public BuiltinNewAdapter(ArgumentValues /*!*/ ai, PythonType /*!*/ creating, BuiltinFunction /*!*/ ctor, PythonContext /*!*/ state, Expression /*!*/ codeContext)
     : base(ai, state, codeContext)
 {
     _creating = creating;
     _ctor     = ctor;
 }
Exemple #43
0
        void Run()
        {
            var @void   = VoidType.Instance;
            var @int    = IntegerType.Instance;
            var @bool   = BooleanType.Instance;
            var @char   = CharacterType.Instance;
            var @string = new ArrayType(@char);

            var setType         = new FunctionType(new Parameter("dst", @int, ParameterFlags.Out), new Parameter("src", @int));
            var mainType        = new FunctionType();
            var printIntType    = new FunctionType(new Parameter("value", @int));
            var printStringType = new FunctionType(new Parameter("value", @string));
            var intBinOpType    = new FunctionType(@int, new Parameter("lhs", @int), new Parameter("rhs", @int));
            var intRelOpType    = new FunctionType(@bool, new Parameter("lhs", @int), new Parameter("rhs", @int));
            var intAssOpType    = new FunctionType(@int, new Parameter("dst", @int, ParameterFlags.Out), new Parameter("val", @int));
            var limitType       = new FunctionType(@int);

            var stringLiteral0 = new Array(@string, "i = ".Select(c => new Character(c)));
            var stringLiteral1 = new Array(@string, "\n".Select(c => new Character(c)));

            var @set = new UserFunction(setType, new Statement[]
            {
                new Statement.Call(new GlobalReference(6, false), new NullReference(), new StackFrameReference(0, false), new StackFrameReference(1, true))
                {
                    Location = "set:0"
                },
                new Statement.Exit()
                {
                    Location = "set:1"
                },
            });

            var @print = new UserFunction(mainType, new Statement[]
            {
                new Statement.Call(new GlobalReference(3, false), new GlobalReference(8, true))
                {
                    Location = "print:0"
                },
                new Statement.Call(new GlobalReference(2, false), new CreationFrameReference(0, true))
                {
                    Location = "print:1"
                },
                new Statement.Call(new GlobalReference(3, false), new GlobalReference(9, true))
                {
                    Location = "print:2"
                },
                new Statement.Exit()
                {
                    Location = "print:3"
                },
            });

            var @limit = new UserFunction(limitType, new Statement[]
            {
                new Statement.Call(new GlobalReference(6, false), new NullReference(), new StackFrameReference(0, false), new GlobalReference(10, true))
                {
                    Location = "limit:0"
                },
                new Statement.Exit()
                {
                    Location = "limit:1"
                },
            });

            var @main = new UserFunction(mainType, new Statement[]
            {
                // 0: call   g[0] SF[0] *g[7]        /* set(i,42) */
                new Statement.Call(new GlobalReference(0, false), new StackFrameReference(0, false), new GlobalReference(7, true))
                {
                    Location = "main:0"
                },

                // 1: call   g[12] SF[3]            /* tmp1 = limit() */
                new Statement.Call(new GlobalReference(12, false), new StackFrameReference(3, false))
                {
                    Location = "main:1"
                },

                // 2: call   g[5] SF[2] *SF[0] *SF[3] /* tmp0 = (i > tmp1) */
                new Statement.Call(new GlobalReference(5, false), new StackFrameReference(2, false), new StackFrameReference(0, true), new StackFrameReference(3, true))
                {
                    Location = "main:2"
                },

                // 3: jmpifn 7 SF[2]                 /* while(tmp0) { */
                new Statement.ConditionalJump(new StackFrameReference(2, false), 7, JumpBehaviour.WhenFalse)
                {
                    Location = "main:3"
                },

                // 4: call   g[4] SF[3] *SF[0] *g[11] /* tmp1 = i - 1 */
                new Statement.Call(new GlobalReference(4, false), new StackFrameReference(3, false), new StackFrameReference(0, true), new GlobalReference(11, true))
                {
                    Location = "main:4"
                },

                // 5: call   g[6] SF[0] *SF[3]       /* i = tmp1 */
                new Statement.Call(new GlobalReference(6, false), new NullReference(), new StackFrameReference(0, false), new StackFrameReference(3, true))
                {
                    Location = "main:5"
                },

                // 6: jmp    1                       /* } */
                new Statement.Jump(1)
                {
                    Location = "main:6"
                },

                // 7: newfun SF[1] f[1]              /* print = f[1](SF) */
                new Statement.CreateClosure(new StackFrameReference(1, false), @print)
                {
                    Location = "main:7"
                },

                // 8: call   SF[1]                   /* print() */
                new Statement.Call(new StackFrameReference(1, false))
                {
                    Location = "main:8"
                },

                // 9: exit                           /* return */
                new Statement.Exit()
                {
                    Location = "main:9"
                }
            }, @int, mainType, @bool, @int);

            var @printInt = new BuiltinFunction(@printIntType, (args) =>
            {
                Console.Write("{0}", args[0].Value as Integer);
                return(null);
            });

            var @printString = new BuiltinFunction(@printIntType, (args) =>
            {
                var value = args[0].Value as Array;
                var text  = string.Join <string>("", value.Select(v => char.ConvertFromUtf32((v as Character).Value)));
                Console.Write("{0}", text);
                return(null);
            });

            var @intAss = new BuiltinFunction(intAssOpType, (args) =>
            {
                args[0].Value = args[1].Value;
                return(null);
            });

            var @intSub = new BuiltinFunction(intBinOpType, (args) =>
            {
                return(new Integer((args[0].Value as Integer) - (args[1].Value as Integer)));
            });

            var @intMoreThan = new BuiltinFunction(intBinOpType, (args) =>
            {
                return(new Boolean((args[0].Value as Integer) > (args[1].Value as Integer)));
            });

            var literalMain = new Function(@main);

            var globals = new StorageContext(13);

            {
                globals[0]  = new ValueStore(new Function(@set));         //  set    : t[1] = f[0](nil)
                globals[1]  = new ValueStore(literalMain);                //  main   : t[2] = f[2](nil)
                globals[2]  = new ValueStore(new Function(@printInt));    //  print  : t[3] = f[5](nil)
                globals[3]  = new ValueStore(new Function(@printString)); //  print  : t[5] = f[4](nil)
                globals[4]  = new ValueStore(new Function(@intSub));      //  '-'    : t[6] = f[6](nil)
                globals[5]  = new ValueStore(new Function(@intMoreThan)); //  '>'    : t[7] = f[7](nil)
                globals[6]  = new ValueStore(new Function(@intAss));      //  '='    : t[8] = f[3](nil)
                globals[7]  = new ValueStore(new Integer(42));            //  42     : int
                globals[8]  = new ValueStore(stringLiteral0);             //  "i = " : array<char>
                globals[9]  = new ValueStore(stringLiteral1);             //  "\n"   : array<char>
                globals[10] = new ValueStore(new Integer(38));            //  38    : int
                globals[11] = new ValueStore(new Integer(1));             //  1     : int
                globals[12] = new ValueStore(new Function(@limit));       // limit : t[10] = f[8](nil)
            }

            literalMain.Call(globals);
        }
Exemple #44
0
        /// <summary>
        /// Tries to get the BuiltinFunction for the given name on the type of the provided MetaObject.
        ///
        /// Succeeds if the MetaObject is a BuiltinFunction or BuiltinMethodDescriptor.
        /// </summary>
        internal static bool TryGetStaticFunction(PythonContext /*!*/ state, string op, DynamicMetaObject /*!*/ mo, out BuiltinFunction function)
        {
            PythonType type = MetaPythonObject.GetPythonType(mo);

            function = null;
            if (!String.IsNullOrEmpty(op))
            {
                PythonTypeSlot xSlot;
                object         val;
                if (type.TryResolveSlot(state.SharedContext, op, out xSlot) &&
                    xSlot.TryGetValue(state.SharedContext, null, type, out val))
                {
                    function = TryConvertToBuiltinFunction(val);
                    if (function == null)
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Exemple #45
0
 public MetaBuiltinFunction(Expression /*!*/ expression, BindingRestrictions /*!*/ restrictions, BuiltinFunction /*!*/ value)
     : base(expression, BindingRestrictions.Empty, value)
 {
     Assert.NotNull(value);
 }
        public static object OverloadedNewKW(ICallerContext context, BuiltinFunction overloads\u03bf, DynamicType type\u03c4, [ParamDict] Dict kwargs\u03ba)
        {
            if (type\u03c4 == null) throw Ops.TypeError("__new__ expected type object, got {0}", Ops.StringRepr(Ops.GetDynamicType(type\u03c4)));

            object[] finalArgs;
            string[] names;
            DynamicType.GetKeywordArgs(kwargs\u03ba, Ops.EMPTY, out finalArgs, out names);

            return overloads\u03bf.CallHelper(context, finalArgs, names, null);
        }
        protected object GetOverload(object key, MethodBase[] targets)
        {
            // Retrieve the signature from the index.
            Type[] sig = GetSignatureFromKey(key);

            // We can still end up with more than one target since generic and non-generic
            // methods can share the same name and signature. So we'll build up a new
            // reflected method with all the candidate targets. A caller can then index this
            // reflected method if necessary in order to provide generic type arguments and
            // fully disambiguate the target.
            BuiltinFunction rm = new BuiltinFunction();
            rm.Name = function.Name;
            rm.FunctionType = function.FunctionType | FunctionType.OptimizeChecked; // don't allow optimization that would whack the real entry

            // Search for targets with the right number of arguments.
            FindMatchingTargets(sig, targets, rm);

            if (rm.Targets == null)
                throw Ops.TypeError("No match found for the method signature {0}", key);

            if (instance != null) {
                return new BoundBuiltinFunction(rm, instance);
            } else {
                return GetTargetFunction(rm);
            }
        }
Exemple #48
0
        /// <summary>
        /// Tries to get a MethodBinder associated with the slot for the specified type.
        ///
        /// If a method is found the binder is set and true is returned.
        /// If nothing is found binder is null and true is returned.
        /// If something other than a method is found false is returned.
        ///
        /// TODO: Remove rop
        /// </summary>
        internal static bool TryGetBinder(PythonContext /*!*/ state, DynamicMetaObject /*!*/[] /*!*/ types, string op, string rop, out SlotOrFunction /*!*/ res, out PythonType declaringType)
        {
            declaringType = null;

            DynamicMetaObject xType = types[0];
            BuiltinFunction   xBf;

            if (!BindingHelpers.TryGetStaticFunction(state, op, xType, out xBf))
            {
                res = SlotOrFunction.Empty;
                return(false);
            }

            xBf = CheckAlwaysNotImplemented(xBf);

            BindingTarget     bt;
            DynamicMetaObject binder;
            DynamicMetaObject yType = null;
            BuiltinFunction   yBf   = null;

            if (types.Length > 1)
            {
                yType = types[1];
                if (!BindingHelpers.IsSubclassOf(xType, yType) && !BindingHelpers.TryGetStaticFunction(state, rop, yType, out yBf))
                {
                    res = SlotOrFunction.Empty;
                    return(false);
                }

                yBf = CheckAlwaysNotImplemented(yBf);
            }

            if (yBf == xBf)
            {
                yBf = null;
            }
            else if (yBf != null && BindingHelpers.IsSubclassOf(yType, xType))
            {
                xBf = null;
            }

            var mc = new PythonOverloadResolver(
                state.Binder,
                types,
                new CallSignature(types.Length),
                AstUtils.Constant(state.SharedContext)
                );

            if (xBf == null)
            {
                if (yBf == null)
                {
                    binder = null;
                    bt     = null;
                }
                else
                {
                    declaringType = DynamicHelpers.GetPythonTypeFromType(yBf.DeclaringType);
                    binder        = state.Binder.CallMethod(mc, yBf.Targets, BindingRestrictions.Empty, null, PythonNarrowing.None, PythonNarrowing.BinaryOperator, out bt);
                }
            }
            else
            {
                if (yBf == null)
                {
                    declaringType = DynamicHelpers.GetPythonTypeFromType(xBf.DeclaringType);
                    binder        = state.Binder.CallMethod(mc, xBf.Targets, BindingRestrictions.Empty, null, PythonNarrowing.None, PythonNarrowing.BinaryOperator, out bt);
                }
                else
                {
                    List <MethodBase> targets = new List <MethodBase>();
                    targets.AddRange(xBf.Targets);
                    foreach (MethodBase mb in yBf.Targets)
                    {
                        if (!ContainsMethodSignature(targets, mb))
                        {
                            targets.Add(mb);
                        }
                    }

                    binder = state.Binder.CallMethod(mc, targets.ToArray(), BindingRestrictions.Empty, null, PythonNarrowing.None, PythonNarrowing.BinaryOperator, out bt);

                    foreach (MethodBase mb in yBf.Targets)
                    {
                        if (bt.Overload.ReflectionInfo == mb)
                        {
                            declaringType = DynamicHelpers.GetPythonTypeFromType(yBf.DeclaringType);
                            break;
                        }
                    }

                    if (declaringType == null)
                    {
                        declaringType = DynamicHelpers.GetPythonTypeFromType(xBf.DeclaringType);
                    }
                }
            }

            if (binder != null)
            {
                res = new SlotOrFunction(bt, binder);
            }
            else
            {
                res = SlotOrFunction.Empty;
            }

            Debug.Assert(res != null);
            return(true);
        }
 protected override void ProcessBuiltinInvocation(MethodInvocationExpression node, BuiltinFunction function)
 {
     if (function == UnityScript.TypeSystem.UnityScriptTypeSystem.UnityScriptEval)
     {
         EvalAnnotation.Mark(this.CurrentMethod);
         this.BindExpressionType(node, this.TypeSystemServices.ObjectType);
     }
     else if (function == UnityScript.TypeSystem.UnityScriptTypeSystem.UnityScriptTypeof)
     {
         this.ProcessTypeofBuiltin(node);
     }
     else
     {
         base.ProcessBuiltinInvocation(node, function);
     }
 }