internal BuiltinClassInfo MakeGenericType(Type clrType, params Type[] clrIndexTypes)
        {
            var genType = clrType.MakeGenericType(clrIndexTypes);
            var pyType  = ClrModule.GetPythonType(genType);

            return(GetCached(pyType, () => new BuiltinClassInfo(pyType, this)));
        }
Beispiel #2
0
 public BuiltinEventInfo(ReflectedEvent value, ProjectState projectState)
     : base(ClrModule.GetPythonType(value.Info.EventHandlerType), projectState)
 {
     _value = value;
     _doc   = null;
     _type  = ClrModule.GetPythonType(value.Info.EventHandlerType);
 }
Beispiel #3
0
 public BuiltinFieldInfo(ReflectedField value, ProjectState projectState)
     : base(new LazyDotNetDict(ClrModule.GetPythonType(value.FieldType), projectState, true))
 {
     _value = value;
     _doc   = null;
     _type  = ClrModule.GetPythonType(value.FieldType);
 }
Beispiel #4
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;
        }
        public static void InjectType(this ScriptScope scope, Type t)
        {
            string name = t.Name;

            if (t.IsGenericTypeDefinition)
            {
                name = name.Substring(0, name.IndexOf('`'));
            }
            scope.SetVariable(name, ClrModule.GetPythonType(t));
        }
Beispiel #6
0
        public static void AddExtensionType(this ModuleContext mc, Type type)
        {
            System.Type ExtensionMethodSet = typeof(PythonContext).Assembly.GetType("IronPython.Runtime.ExtensionMethodSet");
            var         extsetProp         = typeof(ModuleContext).GetProperty("ExtensionMethods",
                                                                               BindingFlags.NonPublic | BindingFlags.Instance);
            object existingExt = extsetProp.GetValue(mc, null);
            var    args        = new object[] { mc.Context, existingExt, ClrModule.GetPythonType(type) };
            object newExt      = ExtensionMethodSet.GetMethod("AddType").Invoke(null, args);

            extsetProp.SetValue(mc, newExt, null);
        }
Beispiel #7
0
        public BuiltinMethodInfo(BuiltinMethodDescriptor method, ProjectState projectState)
            : base(ClrModule.GetPythonType(typeof(BuiltinMethodDescriptor)), projectState)
        {
            // TODO: get return information, parameters, members
            _method = method;

            var function = PythonOps.GetBuiltinMethodDescriptorTemplate(method);

            _returnTypes = Utils.GetReturnTypes(function, projectState);
            _doc         = null;
        }
        internal static ParameterResult GetParameterResultFromParameterInfo(ParameterInfo param)
        {
            // TODO: Get parameter documentation
            var pyType = ClrModule.GetPythonType(param.ParameterType);

            string name     = param.Name;
            string typeName = PythonType.Get__name__(pyType);

            if (param.IsDefined(typeof(ParamArrayAttribute), false))
            {
                name = "*" + name;
                if (param.ParameterType.IsArray)
                {
                    var elemType = param.ParameterType.GetElementType();
                    if (elemType == typeof(object))
                    {
                        typeName = "sequence";
                    }
                    else
                    {
                        typeName = PythonType.Get__name__(DynamicHelpers.GetPythonTypeFromType(elemType)) + " sequence";
                    }
                }
            }
            else if (param.IsDefined(typeof(ParamDictionaryAttribute), false))
            {
                name     = "**" + name;
                typeName = "object";
            }

            bool isOptional = false;

            if (param.DefaultValue != DBNull.Value && !(param.DefaultValue is Missing))
            {
                name = name + " = " + PythonOps.Repr(DefaultContext.Default, param.DefaultValue);
            }
            else if (param.IsOptional)
            {
                object missing = CompilerHelpers.GetMissingValue(param.ParameterType);
                if (missing != Missing.Value)
                {
                    name = name + " = " + PythonOps.Repr(DefaultContext.Default, missing);
                }
                else
                {
                    isOptional = true;
                }
            }

            return(new ParameterResult(name, "", typeName, isOptional));
        }
Beispiel #9
0
        public override ISet <Namespace> GetMember(Node node, AnalysisUnit unit, string name)
        {
            if (name == "get")
            {
                if (_getMethod == null)
                {
                    var getter = ProjectState.GetMember <BuiltinMethodDescriptor>(ClrModule.GetPythonType(typeof(PythonDictionary)), "get");
                    _getMethod = new DictionaryGetMethod(getter, ProjectState, this).SelfSet;
                }
                return(_getMethod);
            }

            return(base.GetMember(node, unit, name));
        }
Beispiel #10
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);
        }
Beispiel #11
0
        private void FillCommandsFromScriptSource(ScriptSource script)
        {
            CompiledCode code;

            try
            {
                code = script.Compile();
            }
            catch (SyntaxErrorException e)
            {
                throw new SyntaxErrorExceptionPrettyWrapper(string.Format("Error compiling '{0}", _fileFullName), e);
            }

            ScriptScope scope = _engine.CreateScope();

            scope.SetVariable("IIronPythonCommand", ClrModule.GetPythonType(typeof(IIronPythonCommand)));
            scope.SetVariable("BaseIronPythonCommand", ClrModule.GetPythonType(typeof(BaseIronPythonCommand)));
            scope.SetVariable("UserContext", UserContext.Instance);
            scope.SetVariable("WindowUtility", WindowUtility.Instance);
            scope.SetVariable("clr", _engine.GetClrModule());
            try
            {
                code.Execute(scope);
            }
            catch (UnboundNameException e)
            {
                throw new PythonException(string.Format("Error compiling '{0}'", _fileFullName), e);
            }


            var pluginClasses = scope.GetItems()
                                .Where(kvp => kvp.Value is IronPython.Runtime.Types.PythonType)
                                .Where(
                kvp =>
                typeof(IIronPythonCommand).IsAssignableFrom(((IronPython.Runtime.Types.PythonType)kvp.Value).__clrtype__()))
                                .Where(kvp => kvp.Key != "BaseIronPythonCommand" && kvp.Key != "IIronPythonCommand");


            var pluginMethods = scope.GetItems()
                                .Where(kvp => _engine.Operations.IsCallable(kvp.Value) && kvp.Value is PythonFunction)
                                .Where(kvp => !kvp.Key.StartsWith("_"));

            foreach (var nameAndClass in pluginClasses)
            {
                var plugin      = (IIronPythonCommand)_engine.Operations.Invoke(nameAndClass.Value, new object[] { });
                var commandName = CamelToSpaced(nameAndClass.Key);

                var description = _engine.Operations.GetDocumentation(nameAndClass.Value);
                if (plugin as BaseIronPythonCommand != null)
                {
                    // retrieving the class name from the python time is a bit trickier without access to the engine
                    // so we pass this here
                    ((BaseIronPythonCommand)plugin).SetDefaultName(commandName);
                }
                var command = new IronPythonPluginCommand(_fileFullName, plugin, description);

                _localCommands.Add(command);
            }

            foreach (var pluginMethod in pluginMethods)
            {
                var commandName       = CamelToSpaced(pluginMethod.Key);
                var method            = pluginMethod.Value;
                var commandFromMethod = new IronPythonCommandFromMethod(commandName, arguments => _engine.Operations.Invoke(method, arguments).ToString());

                var description = _engine.Operations.GetDocumentation(pluginMethod.Value);
                if (!string.IsNullOrEmpty(description))
                {
                    commandFromMethod.SetDescription(description);
                }

                var ironPythonPluginCommand = new IronPythonPluginCommand(_fileFullName, commandFromMethod, description);

                _localCommands.Add(ironPythonPluginCommand);
            }
        }
 internal BuiltinClassInfo GetBuiltinType(Type type)
 {
     return(GetBuiltinType(ClrModule.GetPythonType(type)));
 }
 internal BuiltinInstanceInfo GetInstance(Type type)
 {
     return(GetInstance(ClrModule.GetPythonType(type)));
 }
        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>();
        }