当前位置: 移动技术网 > IT编程>开发语言>c# > C# 9 新特性:代码生成器、编译时反射

C# 9 新特性:代码生成器、编译时反射

2020年05月01日  | 移动技术网IT编程  | 我要评论

前言

今天 .net 官方博客宣布 c# 9 source generators 第一个预览版发布,这是一个用户已经喊了快 5 年特性,今天终于发布了。

简介

source generators 顾名思义代码生成器,它允许开发者在代码编译过程中获取查看用户代码并且生成新的 c# 代码参与编译过程,并且可以很好的与代码分析器集成提供 intellisense、调试信息和报错信息,可以用它来做代码生成,因此也相当于是一个加强版本的编译时反射。

使用 source generators,可以做到这些事情:

  • 获取一个 compilation 对象,这个对象表示了所有正在编译的用户代码,你可以从中获取 ast 和语义模型等信息
  • 可以向 compilation 对象中插入新的代码,让编译器连同已有的用户代码一起编译

source generators 作为编译过程中的一个阶段执行:

编译运行 -> [分析源代码 -> 生成新代码] -> 将生成的新代码添加入编译过程 -> 编译继续。

上述流程中,中括号包括的内容即为 source generators 所参与的阶段和能做到的事情。

作用

.net 明明具备运行时反射和动态 il 织入功能,那这个 source generators 有什么用呢?

编译时反射 - 0 运行时开销

拿 asp.net core 举例,启动一个 asp.net core 应用时,首先会通过运行时反射来发现 controllers、services 等的类型定义,然后在请求管道中需要通过运行时反射获取其构造函数信息以便于进行依赖注入。然而运行时反射开销很大,即使缓存了类型签名,对于刚刚启动后的应用也无任何帮助作用,而且不利于做 aot 编译。

source generators 将可以让 asp.net core 所有的类型发现、依赖注入等在编译时就全部完成并编译到最终的程序集当中,最终做到 0 运行时反射使用,不仅利于 aot 编译,而且运行时 0 开销。

除了上述作用之外,grpc 等也可以利用此功能在编译时织入代码参与编译,不需要再利用任何的 msbuild task 做代码生成啦!

另外,甚至还可以读取 xml、json 直接生成 c# 代码参与编译,dto 编写全自动化都是没问题的。

aot 编译

source generators 的另一个作用是可以帮助消除 aot 编译优化的主要障碍。

许多框架和库都大量使用反射,例如system.text.json、system.text.regularexpressions、asp.net core 和 wpf 等等,它们在运行时从用户代码中发现类型。这些非常不利于 aot 编译优化,因为为了使反射能够正常工作,必须将大量额外甚至可能不需要的类型元数据编译到最终的原生映像当中。

有了 source generators 之后,只需要做编译时代码生成便可以避免大部分的运行时反射的使用,让 aot 编译优化工具能够更好的运行。

例子

inotifypropertychanged

写过 wpf 或 uwp 的都知道,在 viewmodel 中为了使属性变更可被发现,需要实现 inotifypropertychanged 接口,并且在每一个需要的属性的 setter 处触发属性更改事件:

class myviewmodel : inotifypropertychanged
{
    public event propertychangedeventhandler? propertychanged;

    private string _text;
    public string text
    {
        get => _text;
        set
        {
            _text = value;
            propertychanged?.invoke(this, new propertychangedeventargs(nameof(text)));
        }
    }
}

当属性多了之后将会非常繁琐,先前 c# 引入了 callermembername 用于简化属性较多时候的情况:

class myviewmodel : inotifypropertychanged
{
    public event propertychangedeventhandler? propertychanged;

    private string _text;
    public string text
    {
        get => _text;
        set
        {
            _text = value;
            onpropertychanged();
        }
    }

    protected virtual void onpropertychanged([callermembername] string? propertyname = null)
    {
        propertychanged?.invoke(this, new propertychangedeventargs(propertyname));
    }
}

即,用 callermembername 指示参数,在编译时自动填充调用方的成员名称。

但是还是不方便。

如今有了 source generators,我们可以在编译时生成代码做到这一点了。

为了实现 source generators,我们需要写个实现了 isourcegenerator 并且标注了 generator 的类型。

完整的 source generators 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using microsoft.codeanalysis;
using microsoft.codeanalysis.csharp;
using microsoft.codeanalysis.csharp.syntax;
using microsoft.codeanalysis.text;

namespace mysourcegenerator
{
    [generator]
    public class autonotifygenerator : isourcegenerator
    {
        private const string attributetext = @"
using system;
namespace autonotify
{
    [attributeusage(attributetargets.field, inherited = false, allowmultiple = false)]
    sealed class autonotifyattribute : attribute
    {
        public autonotifyattribute()
        {
        }
        public string propertyname { get; set; }
    }
}
";

        public void initialize(initializationcontext context)
        {
            // 注册一个语法接收器,会在每次生成时被创建
            context.registerforsyntaxnotifications(() => new syntaxreceiver());
        }

        public void execute(sourcegeneratorcontext context)
        {
            // 添加 attrbite 文本
            context.addsource("autonotifyattribute", sourcetext.from(attributetext, encoding.utf8));

            // 获取先前的语法接收器 
            if (!(context.syntaxreceiver is syntaxreceiver receiver))
                return;

            // 创建处目标名称的属性
            csharpparseoptions options = (context.compilation as csharpcompilation).syntaxtrees[0].options as csharpparseoptions;
            compilation compilation = context.compilation.addsyntaxtrees(csharpsyntaxtree.parsetext(sourcetext.from(attributetext, encoding.utf8), options));

            // 获取新绑定的 attribute,并获取inotifypropertychanged
            inamedtypesymbol attributesymbol = compilation.gettypebymetadataname("autonotify.autonotifyattribute");
            inamedtypesymbol notifysymbol = compilation.gettypebymetadataname("system.componentmodel.inotifypropertychanged");

            // 遍历字段,只保留有 autonotify 标注的字段
            list<ifieldsymbol> fieldsymbols = new list<ifieldsymbol>();
            foreach (fielddeclarationsyntax field in receiver.candidatefields)
            {
                semanticmodel model = compilation.getsemanticmodel(field.syntaxtree);
                foreach (variabledeclaratorsyntax variable in field.declaration.variables)
                {
                    // 获取字段符号信息,如果有 autonotify 标注则保存
                    ifieldsymbol fieldsymbol = model.getdeclaredsymbol(variable) as ifieldsymbol;
                    if (fieldsymbol.getattributes().any(ad => ad.attributeclass.equals(attributesymbol, symbolequalitycomparer.default)))
                    {
                        fieldsymbols.add(fieldsymbol);
                    }
                }
            }

            // 按 class 对字段进行分组,并生成代码
            foreach (igrouping<inamedtypesymbol, ifieldsymbol> group in fieldsymbols.groupby(f => f.containingtype))
            {
                string classsource = processclass(group.key, group.tolist(), attributesymbol, notifysymbol, context);
               context.addsource($"{group.key.name}_autonotify.cs", sourcetext.from(classsource, encoding.utf8));
            }
        }

        private string processclass(inamedtypesymbol classsymbol, list<ifieldsymbol> fields, isymbol attributesymbol, isymbol notifysymbol, sourcegeneratorcontext context)
        {
            if (!classsymbol.containingsymbol.equals(classsymbol.containingnamespace, symbolequalitycomparer.default))
            {
                // todo: 必须在顶层,产生诊断信息
                return null;
            }

            string namespacename = classsymbol.containingnamespace.todisplaystring();

            // 开始构建要生成的代码
            stringbuilder source = new stringbuilder($@"
namespace {namespacename}
{{
    public partial class {classsymbol.name} : {notifysymbol.todisplaystring()}
    {{
");

            // 如果类型还没有实现 inotifypropertychanged 则添加实现
            if (!classsymbol.interfaces.contains(notifysymbol))
            {
                source.append("public event system.componentmodel.propertychangedeventhandler propertychanged;");
            }

            // 生成属性
            foreach (ifieldsymbol fieldsymbol in fields)
            {
                processfield(source, fieldsymbol, attributesymbol);
            }

            source.append("} }");
            return source.tostring();
        }

        private void processfield(stringbuilder source, ifieldsymbol fieldsymbol, isymbol attributesymbol)
        {
            // 获取字段名称
            string fieldname = fieldsymbol.name;
            itypesymbol fieldtype = fieldsymbol.type;

            // 获取 autonotify attribute 和相关的数据
            attributedata attributedata = fieldsymbol.getattributes().single(ad => ad.attributeclass.equals(attributesymbol, symbolequalitycomparer.default));
            typedconstant overridennameopt = attributedata.namedarguments.singleordefault(kvp => kvp.key == "propertyname").value;

            string propertyname = choosename(fieldname, overridennameopt);
            if (propertyname.length == 0 || propertyname == fieldname)
            {
                //todo: 无法处理,产生诊断信息
                return;
            }

            source.append($@"
public {fieldtype} {propertyname} 
{{
    get 
    {{
        return this.{fieldname};
    }}
    set
    {{
        this.{fieldname} = value;
        this.propertychanged?.invoke(this, new system.componentmodel.propertychangedeventargs(nameof({propertyname})));
    }}
}}
");

            string choosename(string fieldname, typedconstant overridennameopt)
            {
                if (!overridennameopt.isnull)
                {
                    return overridennameopt.value.tostring();
                }

                fieldname = fieldname.trimstart('_');
                if (fieldname.length == 0)
                    return string.empty;

                if (fieldname.length == 1)
                    return fieldname.toupper();

                return fieldname.substring(0, 1).toupper() + fieldname.substring(1);
            }

        }

        // 语法接收器,将在每次生成代码时被按需创建
        class syntaxreceiver : isyntaxreceiver
        {
            public list<fielddeclarationsyntax> candidatefields { get; } = new list<fielddeclarationsyntax>();

            // 编译中在访问每个语法节点时被调用,我们可以检查节点并保存任何对生成有用的信息
            public void onvisitsyntaxnode(syntaxnode syntaxnode)
            {
                // 将具有至少一个 attribute 的任何字段作为候选
                if (syntaxnode is fielddeclarationsyntax fielddeclarationsyntax
                    && fielddeclarationsyntax.attributelists.count > 0)
                {
                    candidatefields.add(fielddeclarationsyntax);
                }
            }
        }
    }
}

有了上述代码生成器之后,以后我们只需要这样写 viewmodel 就会自动生成通知接口的事件触发调用:

public partial class myviewmodel
{
    [autonotify]
    private string _text = "private field text";

    [autonotify(propertyname = "count")]
    private int _amount = 5;
}

上述代码将会在编译时自动生成以下代码参与编译:

public partial class myviewmodel : system.componentmodel.inotifypropertychanged
{
    public event system.componentmodel.propertychangedeventhandler propertychanged;

    public string text
    {
        get 
        {
            return this._text;
        }
        set
        {
            this._text = value;
            this.propertychanged?.invoke(this, new system.componentmodel.propertychangedeventargs(nameof(text)));
        }
    }

    public int count
    {
        get 
        {
            return this._amount;
        }
        set
        {
            this._amount = value;
            this.propertychanged?.invoke(this, new system.componentmodel.propertychangedeventargs(nameof(count)));
        }
    }
}

非常方便!

使用时,将 source generators 部分作为一个独立的 .net standard 2.0 程序集(暂时不支持 2.1),用以下方式引入到你的项目即可:

<itemgroup>
  <analyzer include="..\mysourcegenerator\bin\$(configuration)\netstandard2.0\mysourcegenerator.dll" />
</itemgroup>

<itemgroup>
  <projectreference include="..\mysourcegenerator\mysourcegenerator.csproj" />
</itemgroup>

注意需要最新的 .net 5 preview(写文章时还在 artifacts 里没正式 release),并指定语言版本为 preview

<propertygroup>
  <langversion>preview</langversion>
</propertygroup>

另外,source generators 需要引入两个 nuget 包:

<itemgroup>
  <packagereference include="microsoft.codeanalysis.csharp.workspaces" version="3.6.0-3.final" privateassets="all" />
  <packagereference include="microsoft.codeanalysis.analyzers" version="3.0.0" privateassets="all" />
</itemgroup>

限制

source generators 仅能用于访问和生成代码,但是不能修改已有代码,这有一定原因是出于安全考量。

文档

source generators 处于早期预览阶段,docs.microsoft.com 上暂时没有相关文档,关于它的文档请访问在 roslyn 仓库中的文档:

后记

目前 source generators 仍处于非常早期的预览阶段,api 后期还可能会有很大的改动,因此现阶段不要用于生产。

另外,关于与 ide 的集成、诊断信息、断点调试信息等的开发也在进行中,请期待后续的 preview 版本吧。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网