~ruther/NosSmooth

ref: ba49ad7e1b0431be4a22b3209670e439050b2548 NosSmooth/Core/NosSmooth.PacketSerializersGenerator/Extensions/SyntaxNodeExtensions.cs -rw-r--r-- 1.8 KiB
ba49ad7e — František Boháček Merge pull request #14 from Rutherther/packets-span 3 years ago
                                                                                
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
//
//  SyntaxNodeExtensions.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace NosSmooth.PacketSerializersGenerator.Extensions;

/// <summary>
/// Extensions for <see cref="SyntaxNode"/>.
/// </summary>
public static class SyntaxNodeExtensions
{
    /// <summary>
    /// Gets the prefix of the given member (class or namespace).
    /// </summary>
    /// <param name="member">The member to get prefix of.</param>
    /// <returns>The full name.</returns>
    public static string GetPrefix(this SyntaxNode? member)
    {
        if (member is null)
        {
            return string.Empty;
        }

        StringBuilder sb = new StringBuilder();
        SyntaxNode node = member;

        while (node.Parent != null)
        {
            node = node.Parent;

            if (node is NamespaceDeclarationSyntax)
            {
                var namespaceDeclaration = (NamespaceDeclarationSyntax)node;

                sb.Insert(0, ".");
                sb.Insert(0, namespaceDeclaration.Name.ToString());
            }
            else if (node is FileScopedNamespaceDeclarationSyntax fileScopedNamespaceDeclarationSyntax)
            {
                sb.Insert(0, ".");
                sb.Insert(0, fileScopedNamespaceDeclarationSyntax.Name.ToString());
            }
            else if (node is ClassDeclarationSyntax)
            {
                var classDeclaration = (ClassDeclarationSyntax)node;

                sb.Insert(0, ".");
                sb.Insert(0, classDeclaration.Identifier.ToString());
            }
        }

        return sb.ToString().Trim('.');
    }
}
Do not follow this link