File: JavaContractWriter.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 (472 lines) | stat: -rw-r--r-- 17,757 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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// <copyright file="JavaContractWriter.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 JavaContractWriter : ContractWriter
{
    public const string JavaDateTimeType = "java.util.Date";
    public const string PackageName = "com.microsoft.tunnels.contracts";
    public const string RegexPatternType = "java.util.regex.Pattern";
    public const string SerializedNameTagFormat = "@SerializedName(\"{0}\")";
    public const string SerializedNameType = $"com.google.gson.annotations.SerializedName";
    public const string ClassDeclarationHeader = "public class";
    public const string StaticClassDeclarationHeader = "public static class";
    public const string EnumDeclarationHeader = "public enum";
    public const string GsonExposeType = "com.google.gson.annotations.Expose";
    public const string GsonExposeTag = "@Expose";
    public const string DeprecatedTag = "@Deprecated";

    public JavaContractWriter(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 = type.Name + ".java";
        var filePath = GetAbsolutePath(Path.Combine("java", "src", "main", "java", "com", "microsoft", "tunnels", "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();
        s.AppendLine($"package {PackageName};");
        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};")) +
                Environment.NewLine + Environment.NewLine;
            s.Insert(importsOffset, importLines);
        }


        if (!Directory.Exists(Path.GetDirectoryName(filePath)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(filePath));
        }

        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))
        {
            WriteEnumContract(s, indent, type);
            imports.Add(SerializedNameType);
        }
        else
        {
            WriteClassContract(s, indent, type, imports);
        }
    }

    public void WriteNestedTypes(
        StringBuilder s,
        string indent,
        ITypeSymbol type,
        SortedSet<string> imports)
    {
        var nestedTypes = type.GetTypeMembers()
            .Where((t) => !ContractsGenerator.ExcludedContractTypes.Contains(t.Name))
            .ToArray();
        if (nestedTypes.Length > 0)
        {
            foreach (var nestedType in nestedTypes.Where(
                (t) => !ContractsGenerator.ExcludedContractTypes.Contains(t.Name)))
            {
                s.AppendLine();
                WriteContractType(s, indent + "    ", nestedType, imports);
            }
        }
    }

    private void WriteClassContract(
        StringBuilder s,
        string indent,
        ITypeSymbol type,
        SortedSet<string> imports)
    {
        var baseTypeName = type.BaseType?.Name;
        if (baseTypeName == nameof(Object))
        {
            baseTypeName = null;
        }
        var staticClass = type.IsStatic && type.GetMembers().All((m) => m.IsStatic);
        if (!staticClass) {
            imports.Add(GsonExposeType);
        }

        var enumClass = type.IsStatic && type.GetMembers()
            .Where((m) => m.DeclaredAccessibility == Accessibility.Public)
            .All((m) => m is IFieldSymbol);

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

        var extends = "";
        if (baseTypeName != null)
        {
            extends = " extends " + baseTypeName;
        }

        // Only inner classes can be declared static in Java.
        var header = type.IsStatic && type.ContainingType != null
          ? StaticClassDeclarationHeader : ClassDeclarationHeader;
        s.Append($"{indent}{header} {type.Name}{extends} {{");

        CopyConstructor(s, indent + "    ", type, imports);

        var serializedNameTagImportAdded = false;
        foreach (var member in type.GetMembers()
            .Where((m) => m is IPropertySymbol || m is IFieldSymbol field))
        {
            if (member.DeclaredAccessibility != Accessibility.Public &&
                (enumClass || member.DeclaredAccessibility != Accessibility.Internal))
            {
                continue;
            }

            var property = member as IPropertySymbol;
            var field = member as IFieldSymbol;

            if (field != null && !field.IsConst)
            {
                continue;
            }

            s.AppendLine();
            s.Append(FormatDocComment(member.GetDocumentationCommentXml(), indent + "    ", GetJavaDoc(member)));
            if (GetObsoleteAttribute(member) != null)
            {
               s.AppendLine($"{indent}    {DeprecatedTag}");
            }

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

            var accessMod = member.DeclaredAccessibility == Accessibility.Public ? "public " : "";
            var staticKeyword = member.IsStatic ? "static " : "";
            var finalKeyword = field?.IsConst == true || property?.IsReadOnly == true ? "final " : "";
            var javaName = ToCamelCase(member.Name);
            var javaType = GetJavaTypeForCSType(memberType, javaName, imports);

            // Static properties in a non-static class are linked to the non-generated *Statics.java class.
            var value = field?.IsConst != true && member.IsStatic && !staticClass ?
                $"{type.Name}Statics.{javaName}" : GetMemberInitializer(member);

            if (!member.IsStatic && field?.IsConst != true) {
                if (property.TryGetJsonPropertyName(out var jsonPropertyName))
                {
                    s.AppendLine($"{indent}    {string.Format(SerializedNameTagFormat, jsonPropertyName)}");
                    if (!serializedNameTagImportAdded)
                    {
                        imports.Add(SerializedNameType);
                        serializedNameTagImportAdded = true;
                    }
                }

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

            if (value != null && !value.Equals("null") && !value.Equals("null!"))
            {
                s.AppendLine($"{indent}    {accessMod}{staticKeyword}{finalKeyword}{javaType} {javaName} = {value};");
            }
            else
            {
                // Uninitialized java fields are null by default.
                s.AppendLine($"{indent}    {accessMod}{staticKeyword}{finalKeyword}{javaType} {javaName};");
            }
        }

        foreach (var method in type.GetMembers().OfType<IMethodSymbol>()) {
            if (method.IsStatic && method.MethodKind == MethodKind.Ordinary && method.DeclaredAccessibility == Accessibility.Public) {
                s.AppendLine();
                s.Append(FormatDocComment(method.GetDocumentationCommentXml(), indent + "    "));
                if (GetObsoleteAttribute(method) != null)
                {
                    s.AppendLine($"{indent}    {DeprecatedTag}");
                }
                var javaName = ToCamelCase(method.Name);
                var javaReturnType = GetJavaTypeForCSType(method.ReturnType.ToDisplayString(), javaName, imports);

                var parameters = new Dictionary<String, String>() { };
                foreach (var parameter in method.Parameters)
                {
                    var parameterType = parameter.Type.ToDisplayString();
                    var javaParameterName = ToCamelCase(parameter.Name);
                    var javaParameterType = GetJavaTypeForCSType(parameterType, javaName, imports);
                    parameters.Add(javaParameterName, javaParameterType);
                }
                var parameterString = String.Join(", ", parameters.Select(p => String.Format("{0} {1}", p.Value, p.Key)));
                var returnKeyword = javaReturnType != "void" ? "return " : "";

                s.AppendLine($"{indent}    public static {javaReturnType} {javaName}({parameterString}) {{");
                s.AppendLine($"{indent}        {returnKeyword}{type.Name}Statics.{javaName}({String.Join(", ", parameters.Keys)});");
                s.AppendLine($"{indent}    }}");
            }
        }

        WriteNestedTypes(s, indent, type, imports);
        s.AppendLine($"{indent}}}");
    }

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

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

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

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

            if (member != null && GetObsoleteAttribute(member) != null)
            {
                s.AppendLine($"{indent}    {DeprecatedTag}");
            }

            s.AppendLine($"{indent}    {string.Format(SerializedNameTagFormat, field.Name)}");
            s.AppendLine($"{indent}    {field.Name},");
        }
        s.AppendLine($"{indent}}}");
    }

    private void CopyConstructor(
        StringBuilder s,
        string indent,
        ITypeSymbol type,
        SortedSet<string> imports)
    {
        foreach (var method in type.GetMembers().OfType<IMethodSymbol>())
        {
            if (method.Name == ".ctor")
            {
                // We assume that
                // (1) the constructor only performs property assignments and
                // (2) the property and parameter names match.
                // Then we simply do those assignments.
                var parameters = new Dictionary<String, String>() { };
                foreach (var parameter in method.Parameters)
                {
                    var parameterType = parameter.Type.ToDisplayString();
                    var javaName = ToCamelCase(parameter.Name);
                    var javaType = GetJavaTypeForCSType(parameterType, javaName, imports);
                    parameters.Add(javaName, javaType);
                }
                // No need to write the default constructor.
                if (parameters.Count == 0)
                {
                    return;
                }
                s.AppendLine();
                var parameterString = parameters.Select(p => String.Format("{0} {1}", p.Value, p.Key));
                s.Append($"{indent}{type.Name} ({String.Join(", ", parameterString)}) {{");
                s.AppendLine();
                foreach (String parameter in parameters.Keys)
                {
                    s.AppendLine($"{indent}    this.{parameter} = {parameter};");
                }
                s.AppendLine($"{indent}}}");
            }
        }
    }

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

    private string FormatDocComment(string? comment, string indent, List<string>? javaDoc = 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 (javaDoc != null)
        {
            foreach (var line in javaDoc)
            {
                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 Java expression. This involes several
        // weak assumptions, and will not work for many kinds of expressions. But it might
        // be good enough.
        var javaExpression = csExpression
            .Replace("new Regex", $"{RegexPatternType}.compile")
            .Replace("Replace", "replace");

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

        return javaExpression;
    }

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

        if (csType.EndsWith("?"))
        {
            csType = csType.Substring(0, csType.Length - 1);
        }

        string javaType;
        if (csType.StartsWith(this.csNamespace + "."))
        {
            javaType = csType.Substring(csNamespace.Length + 1);
        }
        else
        {
            javaType = csType switch
            {
                "void" => "void",
                "bool" => "boolean",
                "short" => "short",
                "ushort" => "int",
                "int" => "int",
                "uint" => "int",
                "long" => "long",
                "ulong" => "long",
                "string" => "String",
                "System.DateTime" => JavaDateTimeType,
                "System.Text.RegularExpressions.Regex" => RegexPatternType,
                "System.Collections.Generic.IDictionary<string, string>"
                    => $"java.util.Map<String, String>",
                "System.Collections.Generic.IDictionary<string, string[]>"
                    => $"java.util.Map<String, String[]>",
                "System.Uri" => "java.net.URI",
                "System.Collections.Generic.IEnumerable<string>" => "java.util.Collection<String>",
                _ => throw new NotSupportedException("Unsupported C# type: " + csType),
            };
        }

        if (javaType.Contains('.')) {
            imports.Add(javaType.Split('<')[0]);
            javaType = javaType.Split('.').Last();
        }
        javaType += suffix;
        return javaType;
    }

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

        return doc;
    }
}