使用Roslyn编译语法树

5
我正在尝试使用Roslyn生成和编译一个包含get/set属性的简单对象的运行时库。
然而,由于某些原因,编译程序集失败,并出现了添加Linq命名空间的错误 (error CS0246: 无法找到类型或命名空间名称 'System.Linq' (是否缺少 using 指令或程序集引用?)})。
我已经尝试过多种方式来操作生成的树并编译每个树,但是编译仍然失败。
唯一使编译成功的方法是将树解析为字符串,然后将其解析回语法树再进行编译。
以下代码执行以下操作:
  1. 构建包含编译单元、使用、命名空间、类和属性的简单语法树。
  2. 尝试编译树(失败)
  3. 使用C#6选项生成新语法树并进行编译(失败)
  4. 格式化语法树并编译(失败)
  5. 将树序列化为字符串,然后使用SyntaxFactory.ParseSyntaxTree解析生成的树并进行编译(成功)
代码如下:
    private static readonly CSharpCompilationOptions DefaultCompilationOptions =
        new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                .WithOverflowChecks(true)
                .WithPlatform(Platform.X86)
                .WithOptimizationLevel(OptimizationLevel.Release)
                .WithUsings(DefaultNamespaces);
    private static readonly IEnumerable<string> DefaultNamespaces =
        new[]
        {
                    "System",
                    "System.IO",
                    "System.Net",
                    "System.Linq",
                    "System.Text",
                    "System.Text.RegularExpressions"
        };

    private static readonly IEnumerable<MetadataReference> DefaultReferences =
        new[]
        {
                    MetadataReference.CreateFromFile(typeof (object).Assembly.Location),
                    MetadataReference.CreateFromFile(typeof (System.Linq.Enumerable).Assembly.Location),
                    MetadataReference.CreateFromFile(typeof (System.GenericUriParser).Assembly.Location),
                    MetadataReference.CreateFromFile(typeof (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly.Location)
        };

    static void Main(string[] args)
    {
        MakeAssembly();
        Console.ReadLine();
    }

    private static void MakeAssembly()
    {
        //Compilation Unit and Usings
        CompilationUnitSyntax cu = SyntaxFactory.CompilationUnit()
            .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System")),
            SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName(typeof(System.Linq.Enumerable).Namespace)))
        ;

        // NameSpace
        NamespaceDeclarationSyntax ns = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName("Roslyn"));

        // Class
        ClassDeclarationSyntax classNode = SyntaxFactory.ClassDeclaration("MyClass")
                        .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                    ;

        // Property
        classNode= classNode.AddMembers(
                                SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName("Int32"), "MyProperty")
                                        .AddAccessorListAccessors(
                                        SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                                        SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))).
                                        AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)));
        ns = ns.AddMembers(classNode);
        cu = cu.AddMembers(ns);

        // Try To Compile Syntax Tree root
        var root = cu.SyntaxTree.GetRoot();
        var st = root.SyntaxTree;
        var assembly = CompileAndLoad(st);

        if (assembly != null)
        {
            Console.WriteLine("Success compile syntax tree root");
            return;
        }
        else
            Console.WriteLine("failed to compile syntax tree root");

        // Try to compile new syntax tree
        var stNew = SyntaxFactory.SyntaxTree(cu, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6));
        assembly = CompileAndLoad(stNew);
        if (assembly != null)
        {
            Console.WriteLine("Success compile new syntax tree");
            return;
        }
        else
            Console.WriteLine("failed to compile new syntax tree");

        // Try to format node
        AdhocWorkspace cw = new AdhocWorkspace();
        OptionSet options = cw.Options;
        options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInMethods, false);
        options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInTypes, false);

        SyntaxNode formattedNode = Formatter.Format(cu, cw, options);
        var stFormat = SyntaxFactory.SyntaxTree(cu, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6));
        assembly = CompileAndLoad(stFormat);
        if (assembly != null)
        {
            Console.WriteLine("Success compile formatted syntax tree");
            return;
        }
        else
            Console.WriteLine("failed to compile formatted syntax tree");


        // Try to serialize and parse
        StringBuilder sb = new StringBuilder();
        using (StringWriter writer = new StringWriter(sb))
        {
            formattedNode.WriteTo(writer);
        }
        var treeAsString = sb.ToString();
        var stParsed = SyntaxFactory.ParseSyntaxTree(treeAsString);
        assembly = CompileAndLoad(stParsed);
        if (assembly != null)
        {
            Console.WriteLine("Success compile parsed syntax tree");
            return;
        }   
        else
            Console.WriteLine("failed to compile formatted syntax tree");

    }

    private static Assembly CompileAndLoad(SyntaxTree st)
    {
        var compilation
            = CSharpCompilation.Create("TestRoslyn.dll", new SyntaxTree[] { st }, null, DefaultCompilationOptions);
        compilation = compilation.WithReferences(DefaultReferences);
        using (var stream = new MemoryStream())
        {
            EmitResult result = compilation.Emit(stream);
            if (result.Success)
            {
                var assembly = Assembly.Load(stream.GetBuffer());
                return assembly;
            }
            return null;
        }
    }
2个回答

10

我也曾在Roslyn中陷入这个陷阱。using指令不仅表达为一个字符串,限定名的每个部分都是语法节点。你需要像这样创建你的节点:

我之前在Roslyn也掉进了这个陷阱。using指令不仅仅是一个字符串,限定名中的每个部分都是一个语法节点。你需要像这样创建你的节点:

var qualifiedName= SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"),    
                                                 SyntaxFactory.IdentifierName("Linq"));     
var usingDirective = SyntaxFactory.UsingDirective(qualifedName);

我写了一个辅助方法来将字符串转换为正确的语法节点。


private UsingDirectiveSyntax CreateUsingDirective(string usingName)
{
    NameSyntax qualifiedName = null;

    foreach (var identifier in usingName.Split('.'))
    {
        var name = SyntaxFactory.IdentifierName(identifier);

        if (qualifiedName != null)
        {
            qualifiedName = SyntaxFactory.QualifiedName(qualifiedName, name);
        }
        else
        {
            qualifiedName = name;
        }
    }

    return SyntaxFactory.UsingDirective(qualifiedName);
}

4
您可以使用SyntaxFactory.ParseName,它可以处理字符串的解析,并构建适用于您的using指令的限定名称语法节点:
var qualifiedName = SyntaxFactory.ParseName("System.Linq");
var usingDirective = SyntaxFactory.UsingDirective(qualifiedName);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接