File: TSContractWriter.cs

package info (click to toggle)
golang-github-microsoft-dev-tunnels 0.0.25-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,988 kB
  • sloc: cs: 9,969; java: 2,767; javascript: 328; xml: 186; makefile: 5
file content (443 lines) | stat: -rw-r--r-- 15,110 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// <copyright file="TSContractWriter.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
// </copyright>

using Microsoft.CodeAnalysis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Microsoft.DevTunnels.Generator;

internal class TSContractWriter : ContractWriter
{

    public TSContractWriter(string repoRoot, string csNamespace) : base(repoRoot, csNamespace)
    {
    }

    public override void WriteContract(ITypeSymbol type, ICollection<ITypeSymbol> allTypes)
    {
        var csFilePath = GetRelativePath(type.Locations.Single().GetLineSpan().Path);

        var fileName = ToCamelCase(type.Name) + ".ts";
        var filePath = GetAbsolutePath(Path.Combine("ts", "src", "contracts", fileName));

        var s = new StringBuilder();
        s.AppendLine("// Copyright (c) Microsoft Corporation.");
        s.AppendLine("// Licensed under the MIT license.");
        s.AppendLine($"// Generated from ../../../{csFilePath}");
        s.AppendLine("/* eslint-disable */");
        s.AppendLine();

        var importsOffset = s.Length;
        var imports = new SortedSet<string>();

        WriteContractType(s, "", type, imports);

        imports.Remove(type.Name);
        if (imports.Count > 0)
        {
            var importLines = string.Join(Environment.NewLine, imports.Select(
                (i) => $"import {{ {i} }} from './{ToCamelCase(i!)}';")) +
                Environment.NewLine + Environment.NewLine;
            s.Insert(importsOffset, importLines);
        }

        File.WriteAllText(filePath, s.ToString());
    }

    private void WriteContractType(
        StringBuilder s,
        string indent,
        ITypeSymbol type,
        SortedSet<string> imports)
    {
        var members = type.GetMembers();
        if (type.BaseType?.Name == nameof(Enum) || members.All((m) =>
            m.DeclaredAccessibility != Accessibility.Public ||
            (m is IFieldSymbol field &&
             ((field.IsConst && field.Type.Name == nameof(String)) || field.Name == "All")) ||
            (m is IMethodSymbol method && method.MethodKind == MethodKind.StaticConstructor)))
        {
            WriteEnumContract(s, indent, type);
        }
        else if (type.IsStatic && members.All((m) => m.IsStatic))
        {
            WriteStaticClassContract(s, indent, type, imports);
        }
        else
        {
            WriteInterfaceContract(s, indent, type, imports);
        }

        var nestedTypes = type.GetTypeMembers()
            .Where((t) => !ContractsGenerator.ExcludedContractTypes.Contains(t.Name))
            .ToArray();
        if (nestedTypes.Length > 0)
        {
            s.AppendLine();
            s.Append($"{indent}namespace {type.Name} {{");

            foreach (var nestedType in nestedTypes.Where(
                (t) => !ContractsGenerator.ExcludedContractTypes.Contains(t.Name)))
            {
                s.AppendLine();
                WriteContractType(s, indent + "    ", nestedType, imports);
            }

            s.AppendLine($"{indent}}}");
        }
    }

    private void WriteInterfaceContract(
        StringBuilder s,
        string indent,
        ITypeSymbol type,
        SortedSet<string> imports)
    {
        var baseTypeName = type.BaseType?.Name;
        if (baseTypeName == nameof(Object))
        {
            baseTypeName = null;
        }

        if (!string.IsNullOrEmpty(baseTypeName))
        {
            imports.Add(baseTypeName!);
        }

        s.Append(FormatDocComment(type.GetDocumentationCommentXml(), indent));

        var extends = baseTypeName != null ? " extends " + baseTypeName : "";

        s.Append($"{indent}export interface {type.Name}{extends} {{");

        foreach (var property in type.GetMembers().OfType<IPropertySymbol>()
            .Where((p) => !p.IsStatic))
        {
            s.AppendLine();
            s.Append(FormatDocComment(property.GetDocumentationCommentXml(), indent + "    "));

            var propertyType = property.Type.ToDisplayString();
            var isNullable = propertyType.EndsWith("?");
            if (isNullable)
            {
                propertyType = propertyType.Substring(0, propertyType.Length - 1);
            }

            // Make booleans always nullable since undefined is falsy anyway.
            isNullable |= propertyType == "bool";

            var tsName = ToCamelCase(property.Name);
            if (property.TryGetJsonPropertyName(out var jsonPropertyName))
            {
                tsName = jsonPropertyName!;
            }

            var tsType = GetTSTypeForCSType(propertyType, tsName, imports);

            s.AppendLine($"{indent}    {tsName}{(isNullable ? "?" : "")}: {tsType};");
        }

        s.AppendLine($"{indent}}}");

        var constMemberNames = new List<string>();
        foreach (var field in type.GetMembers().OfType<IFieldSymbol>()
            .Where((f) => f.IsConst))
        {
            if (field.DeclaredAccessibility == Accessibility.Public)
            {
                constMemberNames.Add(ToCamelCase(field.Name));
            }
            else if (field.DeclaredAccessibility != Accessibility.Internal)
            {
                continue;
            }

            s.AppendLine();
            s.Append(FormatDocComment(field.GetDocumentationCommentXml(), indent, GetJsDoc(field)));
            s.AppendLine($"{indent}export const {ToCamelCase(field.Name)} = '{field.ConstantValue}';");
        }

        s.Append(ExportStaticMembers(type, constMemberNames));
    }

    private void WriteEnumContract(
        StringBuilder s,
        string indent,
        ITypeSymbol type)
    {
        s.Append(FormatDocComment(type.GetDocumentationCommentXml(), indent));

        s.Append($"{indent}export enum {type.Name} {{");

        foreach (var member in type.GetMembers())
        {
            if (!(member is IFieldSymbol field) || !field.HasConstantValue ||
                field.DeclaredAccessibility != Accessibility.Public)
            {
                continue;
            }

            s.AppendLine();
            s.Append(FormatDocComment(field.GetDocumentationCommentXml(), indent + "    ", GetJsDoc(field)));

            var value = type.BaseType?.Name == "Enum" ? field.Name : field.ConstantValue;
            s.AppendLine($"{indent}    {field.Name} = '{value}',");
        }

        s.AppendLine($"{indent}}}");

        s.Append(ExportStaticMembers(type));
    }

    private void WriteStaticClassContract(
        StringBuilder s,
        string indent,
        ITypeSymbol type,
        SortedSet<string> imports)
    {
        s.Append(FormatDocComment(type.GetDocumentationCommentXml(), indent));

        s.Append($"namespace {type.Name} {{");

        foreach (var member in type.GetMembers())
        {
            var property = member as IPropertySymbol;
            var field = member as IFieldSymbol;
            if (!member.IsStatic || !(property?.IsReadOnly == true || field?.IsConst == true))
            {
                continue;
            }

            var memberType = (property?.Type ?? field!.Type).ToDisplayString();
            var isNullable = memberType.EndsWith("?");
            if (isNullable)
            {
                memberType = memberType.Substring(0, memberType.Length - 1);
            }

            // Make booleans always nullable since undefined is falsy anyway.
            isNullable |= memberType == "bool";

            var tsName = ToCamelCase(member.Name);
            var tsType = GetTSTypeForCSType(memberType, tsName, imports);
            var value = GetMemberInitializer(member);
            if (value != null)
            {
                s.AppendLine();
                s.Append(FormatDocComment(member.GetDocumentationCommentXml(), indent + "    ", GetJsDoc(member)));
                s.AppendLine($"{indent}    " +
                    $"export const {tsName}: {tsType}{(isNullable ? " | null" : "")} = {value};");
            }
        }

        s.AppendLine("}");
    }

    private static string ExportStaticMembers(
        ITypeSymbol type, ICollection<string>? constMemberNames = null)
    {
        var s = new StringBuilder();
        constMemberNames ??= Array.Empty<string>();

        var staticMemberNames = type.GetMembers()
            .Where((s) => s.IsStatic && s.DeclaredAccessibility == Accessibility.Public &&
                (s is IPropertySymbol p ||
                    (s is IMethodSymbol m && m.MethodKind == MethodKind.Ordinary)))
            .Select((m) => ToCamelCase(m.Name))
            .ToArray();
        if (staticMemberNames.Length > 0)
        {
            s.AppendLine();
            s.AppendLine("// Import static members from a non-generated file,");
            s.AppendLine("// and re-export them as an object with the same name as the interface.");
            s.AppendLine("import {");

            foreach (var memberName in staticMemberNames)
            {
                s.AppendLine($"    {memberName},");
            }

            s.AppendLine($"}} from './{ToCamelCase(type.Name)}Statics';");
        }

        if (constMemberNames.Count > 0 || staticMemberNames.Length > 0)
        {
            s.AppendLine();
            s.AppendLine($"export const {type.Name} = {{");

            foreach (var memberName in constMemberNames.Concat(staticMemberNames))
            {
                s.AppendLine($"    {memberName},");
            }

            s.AppendLine("};");
        }

        return s.ToString();
    }

    internal static string ToCamelCase(string name)
    {
        return name.Substring(0, 1).ToLowerInvariant() + name.Substring(1);
    }

    private string FormatDocComment(string? comment, string indent, List<string>? jsdoc = null)
    {
        if (comment == null)
        {
            return string.Empty;
        }

        comment = comment.Replace("\r", "");
        comment = new Regex("\n *").Replace(comment, " ");
        comment = new Regex($"<see cref=\".:({this.csNamespace}\\.)?(\\w+)\\.(\\w+)\" ?/>")
            .Replace(comment, (m) => $"{{@link {m.Groups[2].Value}.{ToCamelCase(m.Groups[3].Value)}}}");
        comment = new Regex($"<see cref=\".:({this.csNamespace}\\.)?([^\"]+)\" ?/>")
            .Replace(comment, "{@link $2}");

        var summary = new Regex("<summary>(.*)</summary>").Match(comment).Groups[1].Value.Trim();
        var remarks = new Regex("<remarks>(.*)</remarks>").Match(comment).Groups[1].Value.Trim();

        var s = new StringBuilder();
        s.AppendLine(indent + "/**");

        foreach (var commentLine in WrapComment(summary, 90 - 3 - indent.Length))
        {
            s.AppendLine(indent + " * " + commentLine);
        }

        if (!string.IsNullOrEmpty(remarks))
        {
            s.AppendLine(indent + " *");
            foreach (var commentLine in WrapComment(remarks, 90 - 3 - indent.Length))
            {
                s.AppendLine(indent + " * " + commentLine);
            }
        }

        if (jsdoc != null)
        {
            foreach (var line in jsdoc)
            {
                s.AppendLine(indent + " * " + line);
            }
        }

        s.AppendLine(indent + " */");

        return s.ToString();
    }

    private static string? GetMemberInitializer(ISymbol member)
    {
        var location = member.Locations.Single();
        var sourceSpan = location.SourceSpan;
        var sourceText = location.SourceTree!.ToString();
        var eolIndex = sourceText.IndexOf('\n', sourceSpan.End);
        var equalsIndex = sourceText.IndexOf('=', sourceSpan.End);

        if (equalsIndex < 0 || equalsIndex > eolIndex)
        {
            // The member does not have an initializer.
            return null;
        }

        var semicolonIndex = sourceText.IndexOf(';', equalsIndex);
        if (semicolonIndex < 0)
        {
            // Invalid syntax??
            return null;
        }

        var csExpression = sourceText.Substring(
            equalsIndex + 1, semicolonIndex - equalsIndex - 1).Trim();

        // Attempt to convert the CS expression to a TS expression. This involves several
        // weak assumptions, and will not work for many kinds of expressions. But it might
        // be good enough.
        var tsExpression = csExpression
            .Replace("'", "^^^").Replace("\\\"", "$$$").Replace('"', '\'').Replace("$$$", "\"").Replace("^^^", "\\'")
            .Replace("Regex", "RegExp")
            .Replace("Replace", "replace");

        // Assume any PascalCase identifiers are referncing other variables in scope.
        tsExpression = new Regex("([A-Z][a-z]+){2,6}\\b(?!\\()").Replace(
            tsExpression, (m) =>
            {
                return (member.ContainingType.MemberNames.Contains(m.Value) ?
                    member.ContainingType.Name + "." : string.Empty) + ToCamelCase(m.Value);
            });

        return tsExpression;
    }

    private string GetTSTypeForCSType(string csType, string propertyName, SortedSet<string> imports)
    {
        var suffix = "";
        if (csType.EndsWith("[]"))
        {
            suffix = "[]";
            csType = csType.Substring(0, csType.Length - 2);
        }

        string tsType;
        if (csType.StartsWith(this.csNamespace + "."))
        {
            tsType = csType.Substring(csNamespace.Length + 1);

            if (!imports.Contains(tsType))
            {
                imports.Add(tsType);
            }

            if (tsType == "ResourceStatus")
            {
                tsType = "number | ResourceStatus";
            }
        }
        else
        {
            tsType = csType switch
            {
                "bool" => "boolean",
                "short" => "number",
                "ushort" => "number",
                "int" => "number",
                "uint" => "number",
                "long" => "number",
                "ulong" => "number",
                "string" => "string",
                "System.DateTime" => "Date",
                "System.Text.RegularExpressions.Regex" => "RegExp",
                "System.Collections.Generic.IDictionary<string, string>"
                    => $"{{ [{(propertyName == "accessTokens" ? "scope" : "key")}: string]: string }}",
                "System.Collections.Generic.IDictionary<string, string[]>"
                    => $"{{ [{(propertyName == "errors" ? "property" : "key")}: string]: string[] }}",
                _ => throw new NotSupportedException("Unsupported C# type: " + csType),
            };
        }

        tsType += suffix;
        return tsType;
    }

    private static List<string> GetJsDoc(ISymbol symbol)
    {
        var doc = new List<string>();
        var obsoleteAttribute = GetObsoleteAttribute(symbol);
        if (obsoleteAttribute != null)
        {
            var message = GetObsoleteMessage(obsoleteAttribute);
            doc.Add($"@deprecated {message}");
        }

        return doc;
    }
}