Beispiel #1
0
        public void Load(string script, string className = "Plugin")
        {
            if (string.IsNullOrEmpty(script))
            {
                throw new ArgumentException("script");
            }

            if (string.IsNullOrEmpty(className))
            {
                throw new ArgumentException("className");
            }

            if (!this.mFileSystem.File.Exists(script))
            {
                throw new FileNotFoundException("Script not found.", script);
            }

            try
            {
                this.mScriptPath = script;

                string scriptContent = this.mFileSystem.File.ReadAllText(this.mScriptPath);

                this.mScriptSource = this.mScriptEngine.CreateScriptSourceFromString(scriptContent);

                this.mScriptScope = this.mScriptEngine.CreateScope();

                this.mScriptScope.SetVariable("SSRSUtil", DynamicHelpers.GetPythonTypeFromType(typeof(SSRSUtil)));
                this.mScriptScope.SetVariable("FileSystem", this.mFileSystem);

                this.mScriptScope.SetVariable("ReportServerReader", this.mReportServerReader);
                this.mScriptScope.SetVariable("ReportServerWriter", this.mReportServerWriter);
                this.mScriptScope.SetVariable("ReportServerRepository", this.mReportServerRepository);

                this.mScriptScope.SetVariable("SQLUtil", DynamicHelpers.GetPythonTypeFromType(typeof(SQLUtil)));
                this.mScriptScope.SetVariable("Logger", this.mScriptLogger);

                CompiledCode compiled = this.mScriptSource.Compile();
                compiled.Execute(this.mScriptScope);

                this.mScriptClass = this.mScriptEngine.Operations.Invoke(this.mScriptScope.GetVariable(className));

                this.mScriptSource.Execute(this.mScriptScope);

                this.mLoaded = true;

                this.mScriptLogger.Info("Loading script '{0}'...", this.mScriptPath);

                this.CallMethod("OnLoad");
            }
            catch (SyntaxErrorException er)
            {
                var    eo    = this.mScriptEngine.GetService <ExceptionOperations>();
                string error = eo.FormatException(er);

                string msg = String.Format("Syntax error in \"{0}\":\n\r{1}",
                                           this.mFileSystem.Path.GetFileName(script),
                                           error);

                this.mLogger.Error(er, "Script syntax error");
                this.mScriptLogger.Error(er, "Script syntax error");

                throw new Exception(msg, er);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Implements the default __reduce_ex__ method as specified by PEP 307 case 3 (new-style instance, protocol 2)
        /// </summary>
        private static PythonTuple ReduceProtocol2(CodeContext /*!*/ context, object self)
        {
            PythonType myType = DynamicHelpers.GetPythonType(self);

            object state;

            object[] funcArgs;

            object func = context.LanguageContext.NewObject;

            object getNewArgsCallable;

            if (PythonOps.TryGetBoundAttr(context, myType, "__getnewargs__", out getNewArgsCallable))
            {
                // TypeError will bubble up if __getnewargs__ isn't callable
                if (!(PythonOps.CallWithContext(context, getNewArgsCallable, self) is PythonTuple newArgs))
                {
                    throw PythonOps.TypeError("__getnewargs__ should return a tuple");
                }
                funcArgs    = new object[1 + newArgs.Count];
                funcArgs[0] = myType;
                for (int i = 0; i < newArgs.Count; i++)
                {
                    funcArgs[i + 1] = newArgs[i];
                }
            }
            else
            {
                funcArgs = new object[] { myType };
            }

            if (!PythonTypeOps.TryInvokeUnaryOperator(context,
                                                      self,
                                                      "__getstate__",
                                                      out state))
            {
                object dict;
                if (self is IPythonObject ipo)
                {
                    dict = ipo.Dict;
                }
                else if (!PythonOps.TryGetBoundAttr(context, self, "__dict__", out dict))
                {
                    dict = null;
                }

                PythonDictionary initializedSlotValues = GetInitializedSlotValues(self);
                if (initializedSlotValues != null && initializedSlotValues.Count == 0)
                {
                    initializedSlotValues = null;
                }

                if (dict == null && initializedSlotValues == null)
                {
                    state = null;
                }
                else if (dict != null && initializedSlotValues == null)
                {
                    state = dict;
                }
                else if (dict != null && initializedSlotValues != null)
                {
                    state = PythonTuple.MakeTuple(dict, initializedSlotValues);
                }
                else /*dict == null && initializedSlotValues != null*/ state {
Beispiel #3
0
 /// <summary>
 /// Gets the required alignment of an object.
 /// </summary>
 public static int alignment(object o)
 {
     return(alignment(DynamicHelpers.GetPythonType(o)));
 }
        /// <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);
        }
Beispiel #5
0
        public static object __new__(CodeContext /*!*/ context, PythonType cls, [ParamDictionary] IDictionary <object, object> kwargs\u00F8, [NotNull] params object[] args\u00F8)
        {
            if (cls == null)
            {
                throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(cls)));
            }

            InstanceOps.CheckNewArgs(context, kwargs\u00F8, args\u00F8, cls);

            return(cls.CreateInstance(context));
        }
        private Func <CallSite, TSelfType, CodeContext, object> MakeGetMemberTarget <TSelfType>(string name, object target)
        {
            Type type = CompilerHelpers.GetType(target);

            // needed for GetMember call until DynamicAction goes away
            if (typeof(TypeTracker).IsAssignableFrom(type))
            {
                // no fast path for TypeTrackers
                PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast TypeTracker");
                return(null);
            }

            MemberGroup members = Context.Binder.GetMember(MemberRequestKind.Get, type, name);

            if (members.Count == 0 && type.IsInterface)
            {
                // all interfaces have object members
                type    = typeof(object);
                members = Context.Binder.GetMember(MemberRequestKind.Get, type, name);
            }

            if (members.Count == 0 && typeof(IStrongBox).IsAssignableFrom(type))
            {
                // no fast path for strong box access
                PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast StrongBox");
                return(null);
            }

            MethodInfo getMem = Context.Binder.GetMethod(type, "GetCustomMember");

            if (getMem != null && getMem.IsSpecialName)
            {
                // no fast path for custom member access
                PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast GetCustomMember " + type);
                return(null);
            }

            Expression   error;
            TrackerTypes memberType = Context.Binder.GetMemberType(members, out error);

            if (error == null)
            {
                PythonType argType  = DynamicHelpers.GetPythonTypeFromType(type);
                bool       isHidden = argType.IsHiddenMember(name);
                if (isHidden)
                {
                    PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast FilteredMember " + memberType);
                    return(null);
                }

                switch (memberType)
                {
                case TrackerTypes.TypeGroup:
                case TrackerTypes.Type:
                    object typeObj;
                    if (members.Count == 1)
                    {
                        typeObj = DynamicHelpers.GetPythonTypeFromType(((TypeTracker)members[0]).Type);
                    }
                    else
                    {
                        TypeTracker typeTracker = (TypeTracker)members[0];
                        for (int i = 1; i < members.Count; i++)
                        {
                            typeTracker = TypeGroup.UpdateTypeEntity(typeTracker, (TypeTracker)members[i]);
                        }
                        typeObj = typeTracker;
                    }

                    return(new FastTypeGet <TSelfType>(type, typeObj).GetTypeObject);

                case TrackerTypes.Method:
                    PythonTypeSlot slot = PythonTypeOps.GetSlot(members, name, _context.DomainManager.Configuration.PrivateBinding);
                    if (slot is BuiltinMethodDescriptor)
                    {
                        return(new FastMethodGet <TSelfType>(type, (BuiltinMethodDescriptor)slot).GetMethod);
                    }
                    else if (slot is BuiltinFunction)
                    {
                        return(new FastSlotGet <TSelfType>(type, slot, DynamicHelpers.GetPythonTypeFromType(type)).GetRetSlot);
                    }
                    return(new FastSlotGet <TSelfType>(type, slot, DynamicHelpers.GetPythonTypeFromType(type)).GetBindSlot);

                case TrackerTypes.Event:
                    if (members.Count == 1 && !((EventTracker)members[0]).IsStatic)
                    {
                        slot = PythonTypeOps.GetSlot(members, name, _context.DomainManager.Configuration.PrivateBinding);
                        return(new FastSlotGet <TSelfType>(type, slot, DynamicHelpers.GetPythonTypeFromType(((EventTracker)members[0]).DeclaringType)).GetBindSlot);
                    }
                    PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast Event " + members.Count + " " + ((EventTracker)members[0]).IsStatic);
                    return(null);

                case TrackerTypes.Property:
                    if (members.Count == 1)
                    {
                        PropertyTracker pt = (PropertyTracker)members[0];
                        if (!pt.IsStatic && pt.GetIndexParameters().Length == 0)
                        {
                            MethodInfo      prop = pt.GetGetMethod();
                            ParameterInfo[] parameters;

                            if (prop != null && (parameters = prop.GetParameters()).Length == 0)
                            {
                                if (prop.ReturnType == typeof(bool))
                                {
                                    return(new FastPropertyGet <TSelfType>(type, CallInstruction.Create(prop, parameters).Invoke).GetPropertyBool);
                                }
                                else if (prop.ReturnType == typeof(int))
                                {
                                    return(new FastPropertyGet <TSelfType>(type, CallInstruction.Create(prop, parameters).Invoke).GetPropertyInt);
                                }
                                else
                                {
                                    return(new FastPropertyGet <TSelfType>(type, CallInstruction.Create(prop, parameters).Invoke).GetProperty);
                                }
                            }
                        }
                    }
                    PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast Property " + members.Count + " " + ((PropertyTracker)members[0]).IsStatic);
                    return(null);

                case TrackerTypes.All:
                    getMem = Context.Binder.GetMethod(type, "GetBoundMember");
                    if (getMem != null && getMem.IsSpecialName)
                    {
                        PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast GetBoundMember " + type);
                        return(null);
                    }

                    if (IsNoThrow)
                    {
                        return(new FastErrorGet <TSelfType>(type, name).GetErrorNoThrow);
                    }
                    else
                    {
                        return(new FastErrorGet <TSelfType>(type, name).GetError);
                    }

                default:
                    PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast " + memberType);
                    return(null);
                }
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                foreach (MemberTracker mi in members)
                {
                    if (sb.Length != 0)
                    {
                        sb.Append(", ");
                    }
                    sb.Append(mi.MemberType);
                    sb.Append(" : ");
                    sb.Append(mi.ToString());
                }

                return(new FastErrorGet <TSelfType>(type, sb.ToString()).GetAmbiguous);
            }
        }
Beispiel #7
0
        internal static PythonTypeSlot /*!*/ GetSlot(MemberGroup group, string name, bool privateBinding)
        {
            if (group.Count == 0)
            {
                return(null);
            }

            group = FilterNewSlots(group);
            TrackerTypes tt = GetMemberType(group);

            switch (tt)
            {
            case TrackerTypes.Method:
                bool checkStatic       = false;
                List <MemberInfo> mems = new List <MemberInfo>();
                foreach (MemberTracker mt in group)
                {
                    MethodTracker metht = (MethodTracker)mt;
                    mems.Add(metht.Method);
                    checkStatic |= metht.IsStatic;
                }

                Type         declType = group[0].DeclaringType;
                MemberInfo[] memArray = mems.ToArray();
                FunctionType ft       = GetMethodFunctionType(declType, memArray, checkStatic);
                return(GetFinalSlotForFunction(GetBuiltinFunction(declType, group[0].Name, name, ft, memArray)));

            case TrackerTypes.Field:
                return(GetReflectedField(((FieldTracker)group[0]).Field));

            case TrackerTypes.Property:
                return(GetReflectedProperty((PropertyTracker)group[0], group, privateBinding));

            case TrackerTypes.Event:
                return(GetReflectedEvent(((EventTracker)group[0])));

            case TrackerTypes.Type:
                TypeTracker type = (TypeTracker)group[0];
                for (int i = 1; i < group.Count; i++)
                {
                    type = TypeGroup.UpdateTypeEntity(type, (TypeTracker)group[i]);
                }

                if (type is TypeGroup)
                {
                    return(new PythonTypeUserDescriptorSlot(type, true));
                }

                return(new PythonTypeUserDescriptorSlot(DynamicHelpers.GetPythonTypeFromType(type.Type), true));

            case TrackerTypes.Constructor:
                return(GetConstructorFunction(group[0].DeclaringType, privateBinding));

            case TrackerTypes.Custom:
                return(((PythonCustomTracker)group[0]).GetSlot());

            default:
                // if we have a new slot in the derived class filter out the
                // members from the base class.
                throw new InvalidOperationException(String.Format("Bad member type {0} on {1}.{2}", tt.ToString(), group[0].DeclaringType, name));
            }
        }
Beispiel #8
0
 public static string __repr__(object self)
 {
     return($"<{DynamicHelpers.GetPythonType(self).Name} object at {PythonOps.HexId(self)}>");
 }
Beispiel #9
0
        private static PythonTuple ReduceProtocol2(CodeContext /*!*/ context, object self)
        {
            // builtin types which can't be pickled (due to tp_itemsize != 0)
            if (self is MemoryView)
            {
                throw PythonOps.TypeError("can't pickle memoryview objects");
            }

            PythonType myType = DynamicHelpers.GetPythonType(self);

            object?state;

            object?[] funcArgs;

            var copyreg = context.LanguageContext.GetCopyRegModule();
            var func    = PythonOps.GetBoundAttr(context, copyreg, "__newobj__");

            if (PythonOps.TryGetBoundAttr(context, myType, "__getnewargs__", out object?getNewArgsCallable))
            {
                // TypeError will bubble up if __getnewargs__ isn't callable
                if (!(PythonOps.CallWithContext(context, getNewArgsCallable, self) is PythonTuple newArgs))
                {
                    throw PythonOps.TypeError("__getnewargs__ should return a tuple");
                }
                funcArgs    = new object[1 + newArgs.Count];
                funcArgs[0] = myType;
                for (int i = 0; i < newArgs.Count; i++)
                {
                    funcArgs[i + 1] = newArgs[i];
                }
            }
            else
            {
                funcArgs = new object[] { myType };
            }

            if (!PythonTypeOps.TryInvokeUnaryOperator(context,
                                                      self,
                                                      "__getstate__",
                                                      out state))
            {
                object?dict;
                if (self is IPythonObject ipo)
                {
                    dict = ipo.Dict;
                }
                else if (!PythonOps.TryGetBoundAttr(context, self, "__dict__", out dict))
                {
                    dict = null;
                }

                PythonDictionary?initializedSlotValues = GetInitializedSlotValues(self);
                if (initializedSlotValues != null && initializedSlotValues.Count == 0)
                {
                    initializedSlotValues = null;
                }

                if (dict == null && initializedSlotValues == null)
                {
                    state = null;
                }
                else if (dict != null && initializedSlotValues == null)
                {
                    state = dict;
                }
                else if (dict != null && initializedSlotValues != null)
                {
                    state = PythonTuple.MakeTuple(dict, initializedSlotValues);
                }
                else /*dict == null && initializedSlotValues != null*/ state {
        public ProjectState(ScriptEngine pythonEngine)
        {
            _pythonEngine      = pythonEngine;
            _projectEntries    = new List <ProjectEntry>();
            _modules           = new Dictionary <string, ModuleReference>();
            _modulesByFilename = new Dictionary <string, ModuleInfo>(StringComparer.OrdinalIgnoreCase);
            _itemCache         = new Dictionary <object, object>();

            var pythonContext = HostingHelpers.GetLanguageContext(_pythonEngine) as PythonContext;

            _codeContextCls = new ModuleContext(new PythonDictionary(), pythonContext).GlobalContext;
            _codeContextCls.ModuleContext.ShowCls = true;

            _codeContext = new ModuleContext(
                new PythonDictionary(),
                HostingHelpers.GetLanguageContext(_pythonEngine) as PythonContext
                ).GlobalContext;

            InitializeBuiltinModules();

            // TODO: Use reflection-only!
            _references = new List <KeyValuePair <Assembly, TopNamespaceTracker> >();
            AddAssembly(LoadAssemblyInfo(typeof(string).Assembly));
            AddAssembly(LoadAssemblyInfo(typeof(Debug).Assembly));


            // cached for quick checks to see if we're a call to clr.AddReference
            SpecializeFunction("clr", "AddReference", (n, unit, args) => AddReference(n, null));
            SpecializeFunction("clr", "AddReferenceByPartialName", (n, unit, args) => AddReference(n, ClrModule.LoadAssemblyByPartialName));
            SpecializeFunction("clr", "AddReferenceByName", (n, unit, args) => AddReference(n, null));
            SpecializeFunction("clr", "AddReferenceToFile", (n, unit, args) => AddReference(n, (s) => ClrModule.LoadAssemblyFromFile(_codeContext, s)));
            SpecializeFunction("clr", "AddReferenceToFileAndPath", (n, unit, args) => AddReference(n, (s) => ClrModule.LoadAssemblyFromFileWithPath(_codeContext, s)));

            try {
                SpecializeFunction("wpf", "LoadComponent", LoadComponent);
            } catch (KeyNotFoundException) {
                // IronPython.Wpf.dll isn't available...
            }

            SpecializeFunction("__builtin__", "range", (n, unit, args) => unit.DeclaringModule.GetOrMakeNodeVariable(n, (nn) => new RangeInfo(ClrModule.GetPythonType(typeof(List)), unit.ProjectState).SelfSet));
            SpecializeFunction("__builtin__", "min", ReturnUnionOfInputs);
            SpecializeFunction("__builtin__", "max", ReturnUnionOfInputs);

            _builtinModule   = (BuiltinModule)Modules["__builtin__"].Module;
            _propertyObj     = GetBuiltin("property");
            _classmethodObj  = GetBuiltin("classmethod");
            _staticmethodObj = GetBuiltin("staticmethod");
            _typeObj         = GetBuiltin("type");
            _intType         = GetBuiltin("int");
            _stringType      = (BuiltinClassInfo)GetBuiltin("str");

            _objectSet = new HashSet <Namespace>(new[] { GetBuiltin("object") });

            _setType       = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.Set);
            _rangeFunc     = GetBuiltin("range");
            _frozensetType = GetBuiltin("frozenset");
            _functionType  = GetNamespaceFromObjects(TypeCache.Function);
            _generatorType = (BuiltinClassInfo)GetNamespaceFromObjects(DynamicHelpers.GetPythonTypeFromType(typeof(PythonGenerator)));
            _dictType      = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.Dict);
            _boolType      = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.Boolean);
            _noneInst      = (ConstantInfo)GetNamespaceFromObjects(new object[] { null });
            _listType      = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.List);
            _tupleType     = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.PythonTuple);

            _queue = new Queue <AnalysisUnit>();

            _docProvider = CodeContext.LanguageContext.GetService <DocumentationProvider>();
        }
        internal Namespace GetNamespaceFromObjects(IEnumerable <object> attrs)
        {
            List <Namespace> values = new List <Namespace>();

            foreach (var attr in attrs)
            {
                var attrType = (attr != null) ? attr.GetType() : typeof(DynamicNull);
                if (attr is PythonType)
                {
                    values.Add(GetBuiltinType((PythonType)attr));
                }
                else if (attr is BuiltinFunction)
                {
                    var bf = (BuiltinFunction)attr;
                    if (bf.__self__ == null)
                    {
                        values.Add(GetCached(attr, () => new BuiltinFunctionInfo(bf, this)));
                    }
                    else
                    {
                        values.Add(new BuiltinFunctionInfo(bf, this));
                    }
                }
                else if (attrType == typeof(BuiltinMethodDescriptor))
                {
                    values.Add(GetCached(attr, () => new BuiltinMethodInfo((BuiltinMethodDescriptor)attr, this)));
                }
                else if (attrType.IsEnum)
                {
                    values.Add(GetCached(attr, () => new EnumInstanceInfo(attr, this)));
                }
                else if (attrType == typeof(ReflectedProperty) || attrType == typeof(ReflectedExtensionProperty))
                {
                    values.Add(GetCached(attr, () => new BuiltinPropertyInfo((ReflectedGetterSetter)attr, this)));
                }
                else if (attrType == typeof(ReflectedField))
                {
                    values.Add(GetCached(attr, () => new BuiltinFieldInfo((ReflectedField)attr, this)));
                }
                else if (attrType == typeof(ReflectedEvent))
                {
                    values.Add(GetCached(attr, () => new BuiltinEventInfo((ReflectedEvent)attr, this)));
                }
                else if (attrType == typeof(bool) || attrType == typeof(int) || attrType == typeof(Complex64) ||
                         attrType == typeof(string) || attrType == typeof(long) || attrType == typeof(double) ||
                         attr == null)
                {
                    var varRef = GetConstant(attr);
                    foreach (var constant in varRef)
                    {
                        values.Add(constant);
                    }
                }
                else if (attr is NamespaceTracker || attr is TypeGroup)     // TODO: Need to do better for TypeGroup's.
                {
                    values.Add(GetCached(attr, () => new ReflectedNamespace(new[] { attr }, this)));
                }
                else
                {
                    var pyAattrType = DynamicHelpers.GetPythonType(attr);
                    values.Add(GetCached(pyAattrType, () => new BuiltinClassInfo(pyAattrType, this)).Instance);
                }
            }

            if (values.Count == 1)
            {
                return(values[0]);
            }
            else if (values.Count > 1)
            {
                return(GetCached(new NamespaceKey(values.ToArray()), () => new ReflectedNamespace(attrs, this)));
            }
            else
            {
                return(null);
            }
        }
        private ISet <Namespace> LoadComponent(CallExpression node, AnalysisUnit unit, ISet <Namespace>[] args)
        {
            if (args.Length == 2)
            {
                var xaml = args[1];
                var self = args[0];

                foreach (var arg in xaml)
                {
                    string strConst = arg.GetConstantValue() as string;
                    if (strConst != null)
                    {
                        // process xaml file, add attributes to self
                        string           xamlPath = Path.Combine(Path.GetDirectoryName(unit.DeclaringModule.ProjectEntry.FilePath), strConst);
                        XamlProjectEntry xamlProject;
                        if (_xamlByFilename.TryGetValue(xamlPath, out xamlProject))
                        {
                            // TODO: Get existing analysis if it hasn't changed.
                            var analysis = xamlProject.Analysis;

                            if (analysis == null)
                            {
                                xamlProject.Analyze();
                                analysis = xamlProject.Analysis;
                            }

                            xamlProject.AddDependency(unit);

                            var evalUnit = unit.CopyForEval();

                            // add named objects to instance
                            foreach (var keyValue in analysis.NamedObjects)
                            {
                                var type = keyValue.Value;
                                if (type.Type.UnderlyingType != null)
                                {
                                    var ns = GetNamespaceFromObjects(DynamicHelpers.GetPythonTypeFromType(type.Type.UnderlyingType));
                                    if (ns is BuiltinClassInfo)
                                    {
                                        ns = ((BuiltinClassInfo)ns).Instance;
                                    }
                                    self.SetMember(node, evalUnit, keyValue.Key, ns.SelfSet);
                                }

                                // TODO: Better would be if SetMember took something other than a node, then we'd
                                // track references w/o this extra effort.
                                foreach (var inst in self)
                                {
                                    InstanceInfo instInfo = inst as InstanceInfo;
                                    if (instInfo != null)
                                    {
                                        VariableDef def;
                                        if (instInfo.InstanceAttributes.TryGetValue(keyValue.Key, out def))
                                        {
                                            def.AddAssignment(
                                                new SimpleSrcLocation(type.LineNumber, type.LineOffset, keyValue.Key.Length),
                                                xamlProject
                                                );
                                        }
                                    }
                                }
                            }

                            // add references to event handlers
                            foreach (var keyValue in analysis.EventHandlers)
                            {
                                // add reference to methods...
                                var member = keyValue.Value;

                                // TODO: Better would be if SetMember took something other than a node, then we'd
                                // track references w/o this extra effort.
                                foreach (var inst in self)
                                {
                                    InstanceInfo instInfo = inst as InstanceInfo;
                                    if (instInfo != null)
                                    {
                                        ClassInfo ci = instInfo.ClassInfo;

                                        VariableDef def;
                                        if (ci.Scope.Variables.TryGetValue(keyValue.Key, out def))
                                        {
                                            def.AddReference(
                                                new SimpleSrcLocation(member.LineNumber, member.LineOffset, keyValue.Key.Length),
                                                xamlProject
                                                );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // load component returns self
                return(self);
            }

            return(EmptySet <Namespace> .Instance);
        }
Beispiel #13
0
                public bool MoveNext()
                {
                    bool result = false;

                    Reset();

                    do
                    {
                        object lineobj = null;
                        if (!_iterator.MoveNext())
                        {
                            // End of input OR exception
                            if (_field.Length > 0 || _state == State.InQuotedField)
                            {
                                if (_reader._dialect.strict)
                                {
                                    throw MakeError("unexpected end of data");
                                }
                                else
                                {
                                    ParseSaveField();
                                    return(true);
                                }
                            }
                            return(false);
                        }
                        else
                        {
                            lineobj = _iterator.Current;
                        }

                        _reader._line_num++;

                        if (lineobj is char)
                        {
                            lineobj = lineobj.ToString();
                        }

                        if (!(lineobj is string))
                        {
                            throw PythonOps.TypeError("expected string or " +
                                                      "Unicode object, {0} found",
                                                      DynamicHelpers.GetPythonType(lineobj.GetType()));
                        }

                        string line = lineobj as string;
                        if (!string.IsNullOrEmpty(line))
                        {
                            for (int i = 0; i < line.Length; i++)
                            {
                                char c = line[i];
                                if (c == '\0')
                                {
                                    throw MakeError("line contains NULL byte");
                                }

                                ProcessChar(c);
                            }
                        }

                        ProcessChar('\0');
                        result = true;
                    } while (_state != State.StartRecord);

                    return(result);
                }
Beispiel #14
0
 private static Exception MakeTypeError(Type expectedType, object o)
 {
     return(MakeTypeError(DynamicHelpers.GetPythonTypeFromType(expectedType).Name.ToString(), o));
 }
Beispiel #15
0
        public static string FancyRepr(object self)
        {
            PythonType pt = (PythonType)DynamicHelpers.GetPythonType(self);

            // we can't call ToString on a UserType because we'll stack overflow, so
            // only do FancyRepr for reflected types.
            if (pt.IsSystemType)
            {
                string toStr = self.ToString();
                if (toStr == null)
                {
                    toStr = String.Empty;
                }

                // get the type name to display (CLI name or Python name)
                Type   type     = pt.UnderlyingSystemType;
                string typeName = type.FullName;

                // Get the underlying .ToString() representation.  Truncate multiple
                // lines, and don't display it if it's object's default representation (type name)

                // skip initial empty lines:
                int i = 0;
                while (i < toStr.Length && (toStr[i] == '\r' || toStr[i] == '\n'))
                {
                    i++;
                }

                // read the first non-empty line:
                int j = i;
                while (j < toStr.Length && toStr[j] != '\r' && toStr[j] != '\n')
                {
                    j++;
                }

                // skip following empty lines:
                int k = j;
                while (k < toStr.Length && (toStr[k] == '\r' || toStr[k] == '\n'))
                {
                    k++;
                }

                if (j > i)
                {
                    string first_non_empty_line         = toStr.Substring(i, j - i);
                    bool   has_multiple_non_empty_lines = k < toStr.Length;

                    return(String.Format("<{0} object at {1} [{2}{3}]>",
                                         typeName,
                                         PythonOps.HexId(self),
                                         first_non_empty_line,
                                         has_multiple_non_empty_lines ? "..." : String.Empty));
                }
                else
                {
                    return(String.Format("<{0} object at {1}>",
                                         typeName,
                                         PythonOps.HexId(self)));
                }
            }
            return(SimpleRepr(self));
        }
Beispiel #16
0
            public string __repr__(CodeContext context)
            {
                if (_comInterfaceIndex != -1)
                {
                    return(string.Format("<COM method offset {0}: {1} at {2}>", _comInterfaceIndex, DynamicHelpers.GetPythonType(this).Name, _id));
                }

                return(ObjectOps.__repr__(this));
            }
        public override ICollection <MemberDoc> GetMembers(object value)
        {
            List <MemberDoc> res = new List <MemberDoc>();

            PythonModule mod = value as PythonModule;

            if (mod != null)
            {
                foreach (var kvp in mod.__dict__)
                {
                    AddMember(res, kvp, false);
                }
                return(res);
            }

            NamespaceTracker ns = value as NamespaceTracker;

            if (ns != null)
            {
                foreach (var v in ns.SymbolAttributes)
                {
                    AddMember(
                        res,
                        new KeyValuePair <object, object>(
                            SymbolTable.IdToString(v.Key),
                            Importer.MemberTrackerToPython(_context.SharedClsContext, v.Value)
                            ),
                        false
                        );
                }
            }
            else
            {
                OldInstance oi = value as OldInstance;
                if (oi != null)
                {
                    foreach (var member in oi.Dictionary)
                    {
                        AddMember(res, member, false);
                    }

                    AddOldClassMembers(res, oi._class);
                }
                else
                {
                    PythonType pt = value as PythonType;
                    if (pt != null)
                    {
                        foreach (PythonType type in pt.ResolutionOrder)
                        {
                            foreach (var member in type.GetMemberDictionary(_context.SharedContext))
                            {
                                AddMember(res, member, true);
                            }
                        }
                    }
                    else
                    {
                        OldClass oc = value as OldClass;
                        if (oc != null)
                        {
                            AddOldClassMembers(res, oc);
                        }
                        else
                        {
                            pt = DynamicHelpers.GetPythonType(value);
                            foreach (var member in pt.GetMemberDictionary(_context.SharedContext))
                            {
                                AddMember(res, member, true);
                            }
                        }
                    }

                    IPythonObject ipo = value as IPythonObject;
                    if (ipo != null && ipo.Dict != null)
                    {
                        foreach (var member in ipo.Dict)
                        {
                            AddMember(res, member, false);
                        }
                    }
                }
            }

            return(res.ToArray());
        }
        private bool TryGetLazyValue(string name, bool publish, out object value)
        {
            if (!_cleared)
            {
                MemberInfo[] members = NonHiddenMembers(GetMember(name));
                if (members.Length > 0)
                {
                    // we only support fields, methods, and nested types in modules.
                    switch (members[0].MemberType)
                    {
                    case MemberTypes.Field:
                        Debug.Assert(members.Length == 1);

                        var fieldInfo = (FieldInfo)members[0];
                        if (fieldInfo.IsStatic)
                        {
                            value = ((FieldInfo)members[0]).GetValue(null);
                        }
                        else
                        {
                            throw new InvalidOperationException("instance field declared on module.  Fields should stored as PythonGlobals, should be static readonly, or marked as PythonHidden.");
                        }

                        if (publish)
                        {
                            LazyAdd(name, value);
                        }
                        return(true);

                    case MemberTypes.Method:
                        if (!((MethodInfo)members[0]).IsSpecialName)
                        {
                            var          methods = new MethodInfo[members.Length];
                            FunctionType ft      = FunctionType.ModuleMethod | FunctionType.AlwaysVisible;
                            for (int i = 0; i < members.Length; i++)
                            {
                                var method = (MethodInfo)members[i];
                                if (method.IsStatic)
                                {
                                    ft |= FunctionType.Function;
                                }
                                else
                                {
                                    ft |= FunctionType.Method;
                                }

                                methods[i] = method;
                            }

                            var builtinFunc = BuiltinFunction.MakeMethod(
                                name,
                                methods,
                                members[0].DeclaringType,
                                ft
                                );

                            if ((ft & FunctionType.Method) != 0 && Instance != null)
                            {
                                value = builtinFunc.BindToInstance(Instance);
                            }
                            else
                            {
                                value = builtinFunc;
                            }

                            if (publish)
                            {
                                LazyAdd(name, value);
                            }
                            return(true);
                        }
                        break;

                    case MemberTypes.Property:
                        Debug.Assert(members.Length == 1);

                        var propInfo = (PropertyInfo)members[0];
                        if ((propInfo.GetGetMethod() ?? propInfo.GetSetMethod()).IsStatic)
                        {
                            value = ((PropertyInfo)members[0]).GetValue(null, ArrayUtils.EmptyObjects);
                        }
                        else
                        {
                            throw new InvalidOperationException("instance property declared on module.  Propreties should be declared as static, marked as PythonHidden, or you should use a PythonGlobal.");
                        }

                        if (publish)
                        {
                            LazyAdd(name, value);
                        }

                        return(true);

                    case MemberTypes.NestedType:
                        if (members.Length == 1)
                        {
                            value = DynamicHelpers.GetPythonTypeFromType(((TypeInfo)members[0]).AsType());
                        }
                        else
                        {
                            TypeTracker tt = (TypeTracker)MemberTracker.FromMemberInfo(members[0]);
                            for (int i = 1; i < members.Length; i++)
                            {
                                tt = TypeGroup.UpdateTypeEntity(tt, (TypeTracker)MemberTracker.FromMemberInfo(members[i]));
                            }

                            value = tt;
                        }

                        if (publish)
                        {
                            LazyAdd(name, value);
                        }
                        return(true);
                    }
                }
            }

            value = null;
            return(false);
        }
        internal static DynamicMetaObject FallbackWorker(PythonContext context, DynamicMetaObject /*!*/ self, DynamicMetaObject /*!*/ codeContext, string name, GetMemberOptions options, DynamicMetaObjectBinder action, DynamicMetaObject errorSuggestion)
        {
            if (self.NeedsDeferral())
            {
                return(action.Defer(self));
            }
            PythonOverloadResolverFactory resolverFactory = new PythonOverloadResolverFactory(context.Binder, codeContext.Expression);

            PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "FallbackGet");

            bool isNoThrow = ((options & GetMemberOptions.IsNoThrow) != 0) ? true : false;
            Type limitType = self.GetLimitType();

            if (limitType == typeof(DynamicNull) || PythonBinder.IsPythonType(limitType))
            {
                // look up in the PythonType so that we can
                // get our custom method names (e.g. string.startswith)
                PythonType argType = DynamicHelpers.GetPythonTypeFromType(limitType);

                // if the name is defined in the CLS context but not the normal context then
                // we will hide it.
                if (argType.IsHiddenMember(name))
                {
                    DynamicMetaObject baseRes = PythonContext.GetPythonContext(action).Binder.GetMember(
                        name,
                        self,
                        resolverFactory,
                        isNoThrow,
                        errorSuggestion
                        );
                    Expression failure = GetFailureExpression(limitType, self, name, isNoThrow, action);

                    return(BindingHelpers.FilterShowCls(codeContext, action, baseRes, failure));
                }
            }

            if (self.GetLimitType() == typeof(OldInstance))
            {
                if ((options & GetMemberOptions.IsNoThrow) != 0)
                {
                    return(new DynamicMetaObject(
                               Ast.Field(
                                   null,
                                   typeof(OperationFailed).GetField("Value")
                                   ),
                               self.Restrictions.Merge(BindingRestrictionsHelpers.GetRuntimeTypeRestriction(self.Expression, typeof(OldInstance)))
                               ));
                }
                else
                {
                    return(new DynamicMetaObject(
                               Ast.Throw(
                                   Ast.Call(
                                       typeof(PythonOps).GetMethod("AttributeError"),
                                       AstUtils.Constant("{0} instance has no attribute '{1}'"),
                                       Ast.NewArrayInit(
                                           typeof(object),
                                           AstUtils.Constant(((OldInstance)self.Value)._class._name),
                                           AstUtils.Constant(name)
                                           )
                                       )
                                   ),
                               self.Restrictions.Merge(BindingRestrictionsHelpers.GetRuntimeTypeRestriction(self.Expression, typeof(OldInstance)))
                               ));
                }
            }

            var res = PythonContext.GetPythonContext(action).Binder.GetMember(name, self, resolverFactory, isNoThrow, errorSuggestion);

            // Default binder 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 = new DynamicMetaObject(
                    AstUtils.Convert(res.Expression, typeof(object)),
                    res.Restrictions
                    );
            }

            return(res);
        }
Beispiel #20
0
 // note: returns "instance" rather than type name if o is an OldInstance
 internal static string GetName(object o)
 {
     return(DynamicHelpers.GetPythonType(o).Name);
 }
Beispiel #21
0
 private static string FixCtorDoc(Type type, string autoDoc)
 {
     return(autoDoc.Replace("__new__(cls)", DynamicHelpers.GetPythonTypeFromType(type).Name + "()").
            Replace("__new__(cls, ", DynamicHelpers.GetPythonTypeFromType(type).Name + "("));
 }
Beispiel #22
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));
 }
Beispiel #23
0
        public static object __new__(CodeContext context, PythonType cls, object x)
        {
            Extensible <string> es;

            if (x is string)
            {
                return(ReturnObject(context, cls, ParseBigIntegerSign((string)x, 10)));
            }
            else if ((es = x as Extensible <string>) != null)
            {
                object value;
                if (PythonTypeOps.TryInvokeUnaryOperator(context, x, "__long__", out value))
                {
                    return(ReturnObject(context, cls, (BigInteger)value));
                }

                return(ReturnObject(context, cls, ParseBigIntegerSign(es.Value, 10)));
            }
            if (x is double)
            {
                return(ReturnObject(context, cls, DoubleOps.__long__((double)x)));
            }
            if (x is int)
            {
                return(ReturnObject(context, cls, (BigInteger)(int)x));
            }
            if (x is BigInteger)
            {
                return(ReturnObject(context, cls, x));
            }

            if (x is Complex)
            {
                throw PythonOps.TypeError("can't convert complex to long; use long(abs(z))");
            }

            if (x is decimal)
            {
                return(ReturnObject(context, cls, (BigInteger)(decimal)x));
            }

            object     result;
            int        intRes;
            BigInteger bigintRes;

            if (PythonTypeOps.TryInvokeUnaryOperator(context, x, "__long__", out result) &&
                !Object.ReferenceEquals(result, NotImplementedType.Value) ||
                x is OldInstance &&
                PythonTypeOps.TryInvokeUnaryOperator(context, x, "__int__", out result) &&
                !Object.ReferenceEquals(result, NotImplementedType.Value))
            {
                if (result is int || result is BigInteger ||
                    result is Extensible <int> || result is Extensible <BigInteger> )
                {
                    return(ReturnObject(context, cls, result));
                }
                else
                {
                    throw PythonOps.TypeError("__long__ returned non-long (type {0})", PythonTypeOps.GetOldName(result));
                }
            }
            else if (PythonOps.TryGetBoundAttr(context, x, "__trunc__", out result))
            {
                result = PythonOps.CallWithContext(context, result);
                if (Converter.TryConvertToInt32(result, out intRes))
                {
                    return(ReturnObject(context, cls, (BigInteger)intRes));
                }
                else if (Converter.TryConvertToBigInteger(result, out bigintRes))
                {
                    return(ReturnObject(context, cls, bigintRes));
                }
                else
                {
                    throw PythonOps.TypeError("__trunc__ returned non-Integral (type {0})", PythonTypeOps.GetOldName(result));
                }
            }

            if (x is OldInstance)
            {
                throw PythonOps.AttributeError("{0} instance has no attribute '__trunc__'",
                                               ((OldInstance)x)._class.Name);
            }
            else
            {
                throw PythonOps.TypeError("long() argument must be a string or a number, not '{0}'",
                                          DynamicHelpers.GetPythonType(x).Name);
            }
        }
Beispiel #24
0
        public static object OverloadedNewClsKW(CodeContext context, BuiltinFunction overloads\u00F8, PythonType type\u00F8, [ParamDictionary] IDictionary <object, object> kwargs\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, null, null, args\u00F8, kwargs\u00F8));
        }
Beispiel #25
0
 /// <summary>
 /// Returns the code representation of the object.  The default implementation returns
 /// a string which consists of the type and a unique numerical identifier.
 /// </summary>
 public static string __repr__(object self)
 {
     return(String.Format("<{0} object at {1}>",
                          DynamicHelpers.GetPythonType(self).Name,
                          PythonOps.HexId(self)));
 }
Beispiel #26
0
 public static object NonDefaultNew(CodeContext context, 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(type\u00F8.CreateInstance(context, args\u00F8));
 }
Beispiel #27
0
        public static object __new__(CodeContext /*!*/ context, PythonType cls)
        {
            if (cls == null)
            {
                throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(cls)));
            }

            return(cls.CreateInstance(context));
        }
Beispiel #28
0
        public static object NonDefaultNewKWNoParams(CodeContext context, 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)));
            }

            string[] names;
            object[] args;
            GetKeywordArgs(kwargs\u00F8, ArrayUtils.EmptyObjects, out args, out names);
            return(type\u00F8.CreateInstance(context, args, names));
        }
Beispiel #29
0
        /// <summary>
        /// Returns a pointer instance for the given CData
        /// </summary>
        public static Pointer pointer(CodeContext /*!*/ context, CData data)
        {
            PythonType ptrType = POINTER(context, DynamicHelpers.GetPythonType(data));

            return((Pointer)ptrType.CreateInstance(context, data));
        }
Beispiel #30
0
 internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value)
 {
     owner = CheckGetArgs(context, instance, owner);
     value = new Method(_func, owner, DynamicHelpers.GetPythonType(owner));
     return(true);
 }