华悦琴行 發表於 2019-11-14 08:44:00

.NET手撸绘制TypeScript类图——上篇

<h1 id="net手撸绘制typescript类图上篇">.NET手撸绘制TypeScript类图——上篇</h1>
<p>近年来随着交互界面的精细化,<code>TypeScript</code>越来越流行,前端的设计也越来复杂,而<code>类图</code>正是用简单的箭头和方块,反映对象与对象之间关系/依赖的好方式。许多工具都能生成<code>C#</code>类图,有些工具也能生成<code>TypeScript</code>类图,如<code>tsuml</code>,但存在一些局限性。</p>
<p>我们都是<code>.NET</code>开发,为啥不干脆就用<code>.NET</code>撸一个<code>TypeScript</code>类图呢?</p>
<p>说干就干!为了搞到类图,一共分两步走:</p>
<ol>
<li>解析<code>.ts</code>文件,生成抽象语法树(<code>AST</code>),并转换为简单的<code>类</code>、<code>属性</code>、<code>方法</code>等对象</li>
<li>将这个对象绘制出来</li>
</ol>
<p>本文将分上下两部分,上篇将介绍我移植的一个.NET Standard 2.0的TypeScript解析库,下篇将介绍如何将AST转换为真正的图,并实现一些基本的交互。</p>
<h1 id="ts文件生成抽象语法树">.ts文件生成抽象语法树</h1>
<p>正常来说编译原理挺难的,但好在有人赶在了我的前头😁。</p>
<h2 id="typescript解析库">TypeScript解析库</h2>
<p>我在<code>Github</code>上找到了一个叫<code>TypeScriptAST</code>的项目,它刚好就能将<code>.ts</code>文件转换为<code>AST</code>。但它仅提供了<code>.NET Framework</code>版本。我看了一下实现方式,它是从微软官方的TypeScript仓库按源代码翻译的。其中<code>Parse.cs</code>高达近<code>8000</code>行代码,能把如此巨大的工作翻译完成,可见作者花了不少时间。</p>
<p>我拿了过来,稍微改造了一下,移植到了<code>.NET Core</code>。<code>NuGet</code>包地址为:</p>
<blockquote>
<p>https://www.nuget.org/packages/Sdcb.TypeScriptAST/</p>
</blockquote>
<p>我移植的这个版本源代码也开放到了<code>Github</code>,使用相同的<code>Apache-2.0</code>协议开源,开源项目链接如下:</p>
<blockquote>
<p>https://github.com/sdcb/TypeScriptAST</p>
</blockquote>
<p>虽然不知道是不是第一个移植的,但可以确定的是今后<code>.NET Core</code>也能解析<code>TypeScript</code>了:)</p>
<blockquote>
<p>注意:官方没有提供<code>TypeScript</code>的<code>.NET</code>解析工具,也没建议用<code>.NET</code>,使用<code>ts</code>解析是正常做法,官方的包用起来显然也更有自信——但这就是<code>骚操作</code>,不挑战一下怎么知道极限在哪呢?</p>
</blockquote>
<h2 id="简单使用">简单使用</h2>
<p>假如有如下<code>TypeScript</code>代码:</p>
<pre><code class="language-ts">class Class1
{
        td: number = 3;
        ts: string = 'hello';

    doWork(): string {
      return `${3+this.td}-${this.ts}`;
    }
}

var tc = new Class1();
</code></pre>
<p>我们可以使用<code>TypeScriptAST</code>的类进行分析,只需使用<code>TypeScriptAST</code>类:</p>
<pre><code class="language-csharp">var ast = new TypeScriptAST(source: tsSourceStringContent);
</code></pre>
<p>该类有许多对象,提供了丰富的解析方式,使用如下代码,即可将代码中的类抽出来:</p>
<pre><code class="language-csharp">var classAsts = ast.OfKind(SyntaxKind.ClassDeclaration);
</code></pre>
<p>由于<code>AST</code>中的属性太多,我们调试时抽重要的显示出来,并转换为<code>JSON</code>:</p>
<pre><code class="language-csharp">JsonSerializer.Serialize(classAsts.Select(c =&gt; new
{
        c.IdentifierStr,
        Children = c.Children.Skip(1).Select(x =&gt; x.IdentifierStr),
}), new JsonSerializerOptions { WriteIndented = true}).Dump();
</code></pre>
<p>结果如下:</p>
<pre><code class="language-json">[
{
    "IdentifierStr": "Class1",
    "Children": [
      "td",
      "ts",
      "doWork"
    ]
}
]
</code></pre>
<p>有了这个,我们即可定义一些类型,用于后续绘制<code>AST</code>:</p>
<pre><code class="language-csharp">class ClassDef
{
    public string Name { get; set; }

    public List&lt;PropertyDef&gt; Properties { get; set; }

    public List&lt;MethodDef&gt; Methods { get; set; }
}

class PropertyDef
{
    public string Name { get; set; }
    public bool IsPublic { get; set; }
    public bool IsStatic { get; set; }
    public string Type { get; set; }
    public override string ToString() =&gt; (IsPublic ? "+" : "-") + $" {Name}: " + (String.IsNullOrWhiteSpace(Type) ? "any" : Type);
}

class MethodDef
{
    public string Name { get; set; }
    public bool IsPublic { get; set; }
    public bool IsStatic { get; set; }
    public List&lt;ParameterDef&gt; Parameters { get; set; }
    public string ReturnType { get; set; }
    public override string ToString() =&gt;
      (IsPublic ? "+" : "-")
      + $" {Name}({String.Join(", ", Parameters)})"
      + (Name == ".ctor" ? "" : $": {ReturnType}");
}

class ParameterDef
{
    public string Name { get; set; }
    public string Type { get; set; }
    public override string ToString() =&gt; $"{Name}: {Type}";
}
</code></pre>
<p>借助于<code>.NET</code>强大的<code>LINQ</code>,可以将代码写得特别精练,最后可以达到“<strong>一行代码</strong>*”完成<code>.ts</code>到<code>AST</code>的转换:</p>
<pre><code class="language-csharp">static Dictionary&lt;string, ClassDef&gt; ParseFiles(IEnumerable&lt;string&gt; files) =&gt;
    files
    .Select(x =&gt; new TypeScriptAST(File.ReadAllText(x), x))
    .SelectMany(x =&gt; x.OfKind(SyntaxKind.ClassDeclaration))
    .Select(x =&gt; new ClassDef
    {
      Name = x.OfKind(SyntaxKind.Identifier).FirstOrDefault().GetText(),
      Properties = x.OfKind(SyntaxKind.PropertyDeclaration)
            .Select(x =&gt; new PropertyDef
            {
                Name = x.IdentifierStr,
                IsPublic = x.First.Kind != SyntaxKind.PrivateKeyword,
                IsStatic = x.OfKind(SyntaxKind.StaticKeyword).Any(),
                Type = GetType(x),
            }).ToList(),
      Methods = x.OfKind(SyntaxKind.Constructor).Concat(x.OfKind(SyntaxKind.MethodDeclaration))
            .Select(x =&gt; new MethodDef
            {
                Name = x is ConstructorDeclaration ctor ? ".ctor" : x.IdentifierStr,
                IsPublic = x.First.Kind != SyntaxKind.PrivateKeyword,
                IsStatic = x.OfKind(SyntaxKind.StaticKeyword).Any(),
                Parameters = ((ISignatureDeclaration)x).Parameters.Select(x =&gt; new ParameterDef
                {
                  Name = x.OfKind(SyntaxKind.Identifier).FirstOrDefault().GetText(),
                  Type = GetType(x),
                }).ToList(),
                ReturnType = GetReturnType(x),
            }).ToList(),
    }).ToDictionary(x =&gt; x.Name, v =&gt; v);
</code></pre>
<p>两个函数稍微提取一下,代码能更精练:</p>
<pre><code class="language-csharp">static string GetReturnType(Node node) =&gt; node.Children.OfType&lt;TypeNode&gt;().FirstOrDefault()?.GetText();

static string GetType(Node node) =&gt; node switch
{
    var x when x.OfKind(SyntaxKind.TypeReference).Any() =&gt; x.OfKind(SyntaxKind.TypeReference).First().GetText(),
    _ =&gt; node.Last switch
    {
      LiteralExpression literal =&gt; literal.Kind.ToString()[..^7].ToLower() switch
      {
            "numeric" =&gt; "number",
            var x =&gt; x,
      },
      var x =&gt; x.GetText(),
    },
};
</code></pre>
<h2 id="使用">使用</h2>
<p>我对这个ShootR项目进行了分析,分析代码如下:</p>
<pre><code class="language-csharp">ParseFiles(Directory.EnumerateFiles(
      path: @"C:\Users\dotnet-lover\source\repos\ShootR\ShootR\ShootR\Client\Ships", "*.ts")
    ).Dump();
</code></pre>
<p>分析结果:<br>
<img src="https://img2018.cnblogs.com/blog/233608/201911/233608-20191114000437731-1520982044.png" alt="" loading="lazy"></p>
<p>成功找到了完整的<code>7</code>个类,并将<code>类名</code>、<code>字段名</code>、<code>字段类型</code>、<code>方法名</code>、<code>方法参数</code>和<code>返回值</code>等信息都解析出来了。</p>
<h1 id="总结">总结</h1>
<p>在本篇我们介绍了如何使用<code>.NET</code>解析<code>TypeScript</code>,并推荐了我移植的一个<code>NuGet</code>包:<code>Sdcb.TypeScriptAST</code>。</p>
<p>下篇将在这篇的基础上,介绍如何使用代码将类图渲染出来。</p>
<p>本文所用到的<strong>完整代码</strong>,可以在我的<code>Github</code>仓库中下载:<br>
https://github.com/sdcb/blog-data/tree/master/2019/20191113-ts-uml-with-dotnet</p>
<p>喜欢的朋友 请关注我的微信公众号:【DotNet骚操作】</p>
<p><img src="https://img2018.cnblogs.com/blog/233608/201908/233608-20190825165420518-990227633.jpg" alt="DotNet骚操作" loading="lazy"></p><br><br>
来源:https://www.cnblogs.com/sdcb/p/20191113-ts-uml-with-dotnet-1.html
頁: [1]
查看完整版本: .NET手撸绘制TypeScript类图——上篇