首页 > 解决方案 > 为 IronPython 实现“智能感知”

问题描述

在我的 C# 应用程序中,我有一个文本编辑器,允许用户输入 IronPython 脚本。我已经实现了一组可供 python 环境使用的 C# 类。

我现在想实现一个“intellisense”类型的系统,用户输入一个变量名,然后是一个点,它会提示用户提供可用方法和属性的列表。

例如,这是一个 IronPython 脚本:

foo = MyClass()
foo.

此时光标就在点之后。C# 中的 MyClass 示例:

public class MyClass {
    public void Func1() ...
    public void Func2() ...
}

现在我想给用户一个显示 Func1()、Func2() 等的弹出列表。

我需要做的是获取变量名“foo”并获取类 MyClass。

请注意,我无法执行 IronPython 代码来执行此操作,因为它在用户界面中执行操作。

这是我能做到的:

ScriptSource Source = engine.CreateScriptSourceFromString(pycode, SourceCodeKind.File);

SourceUnit su = HostingHelpers.GetSourceUnit(Source);
Microsoft.Scripting.Runtime.CompilerContext Ctxt = new Microsoft.Scripting.Runtime.CompilerContext(su, new IronPython.Compiler.PythonCompilerOptions(), ErrorSink.Null);
IronPython.Compiler.Parser Parser = IronPython.Compiler.Parser.CreateParser(Ctxt, new IronPython.PythonOptions());

IronPython.Compiler.Ast.PythonAst ast = Parser.ParseFile(false);

if (ast.Body is IronPython.Compiler.Ast.SuiteStatement)
{
    IronPython.Compiler.Ast.SuiteStatement ss = ast.Body as IronPython.Compiler.Ast.SuiteStatement;
    foreach (IronPython.Compiler.Ast.Statement s in ss.Statements)
    {
        if (s is IronPython.Compiler.Ast.ExpressionStatement)
        {
            IronPython.Compiler.Ast.ExpressionStatement es = s as IronPython.Compiler.Ast.ExpressionStatement;
        }
    }
}

我可以看到脚本的最后一行foo.是一个 ExpressionStatement,我可以从那里向下钻取以获取“foo”的 NameExpression,但我看不到如何获取变量的类型。

有一个更好的方法吗?甚至可能吗?

谢谢!

标签: c#ironpythoncode-completion

解决方案


推荐阅读