Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1167. C# -Version 1 Source Generator 실습 [링크 복사], [링크+제목 복사]
조회: 7925
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)
(시리즈 글이 4개 있습니다.)
.NET Framework: 908. C# - Source Generator 소개
; https://www.sysnet.pe.kr/2/0/12223

.NET Framework: 909. C# - Source Generator를 적용한 XmlCodeGenerator
; https://www.sysnet.pe.kr/2/0/12228

.NET Framework: 1167. C# -Version 1 Source Generator 실습
; https://www.sysnet.pe.kr/2/0/12985

.NET Framework: 1168.  C# -IIncrementalGenerator를 적용한 Version 2 Source Generator 실습
; https://www.sysnet.pe.kr/2/0/12986




C# -Version 1 Source Generator 실습

예전 글에서 "Soruce Generator"를 소개했는데요,

C# - Source Generator 소개
; https://www.sysnet.pe.kr/2/0/12223

C# - Source Generator를 적용한 XmlCodeGenerator
; https://www.sysnet.pe.kr/2/0/12228

그때와 살짝 달라진 면이 있어서 다시 정리를 했습니다.




실습을 위해 프로젝트(이 글에서는 "PropertySrcGenerator")를 다음과 같이 설정하고,

<Project Sdk="Microsoft.NET.Sdk">

	<PropertyGroup>
		<TargetFramework>netstandard2.0</TargetFramework>
		<ImplicitUsings>enable</ImplicitUsings>
		<LangVersion>10.0</LangVersion>
		<Nullable>enable</Nullable>
	</PropertyGroup>

	<ItemGroup>
		<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" />
		<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.11.0" />
	</ItemGroup>

</Project>

소스 생성기의 뼈대도 다음과 같이 구성하면 됩니다.

using Microsoft.CodeAnalysis;

namespace V1Generator
{
    [Generator]
    public class PropertySrcGenerator : ISourceGenerator
    {
        public void Initialize(GeneratorInitializationContext context)
        {
        }

        public void Execute(GeneratorExecutionContext context)
        {
        }
    }
}

자, 이 상태에서 우리가 하고 싶은 것은 사용자가 작성한 클래스가 "partial"이면서 "[AutoProp]" 속성을 적용했다면,

[AutoProp]
public partial class Book
{
    string writer;
}

자동으로 그 클래스가 소유한 필드에 대해 다음과 같은 코드를 만들어 주는 것입니다.

partial class Book
{
    string writer;

    public string Writer 
    { 
        get => writer; 
        set => writer = value; 
    }
}

그리고 개발의 편의를 위해 Source Generator를 그때그때 동작을 확인하는 용도로 PropertySrcGenerator 프로젝트를 참조하는 예제 프로젝트를 하나 만들고,

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <Nullable>enable</Nullable>
  </PropertyGroup>

	<ItemGroup>
		<ProjectReference Include="..\PropertySrcGenerator\PropertySrcGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
	</ItemGroup>

</Project>

다음과 같이 코드를 추가합니다.

using System;

internal class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
    }
}

[AutoProp]
public partial class Book
{
    string writer = "";
}

자, 이제 여기서 첫 번째 목표가 나왔군요. 위의 코드가 오류 없이 컴파일되려면, 소스 코드 생성기에서 우선 AutoProp 특성을 사용자가 고정적으로 사용할 수 있게 만들어야 하는데요, 이를 위해 Initialize 단계에서 아래와 같은 코드를 포함하면 됩니다.

[Generator]
public class PropertySrcGenerator : ISourceGenerator
{
    public const string AutoPropAttribute = @"
namespace System
{
    [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)]
    public class AutoPropAttribute : System.Attribute
    {
    }
}";

    public void Initialize(GeneratorInitializationContext context)
    {
        context.RegisterForPostInitialization((ctx) =>
        {
            ctx.AddSource("AutoPropAttribute.g.cs", SourceText.From(AutoPropAttribute, Encoding.UTF8));
        });
    }

    public void Execute(GeneratorExecutionContext context)
    {
    }
}

그다음, 사용자가 작성한 클래스의 필드에 대해 get/set 속성을 생성하는 코드를 만들어야 하는데요, 이것이 가능하게 만들려면 사용자가 만든 클래스가 우리가 원하는 조건에 맞는 코드인지를 먼저 판정을 할 수 있어야 합니다. 즉, "자동 생성할" 대상 클래스를 먼저 식별해야 하는데요, 이 작업을 구현하기 위한 2가지 선택이 있습니다.

첫 번째로, Execute 코드에 1) 대상 식별과 2) 소스 코드 생성을 모두 넣는 것입니다. 당연히 이렇게 하면 Execute 코드 작업이 무거워질 것입니다. 테스트를 해보시면 알겠지만, Execute 코드는 Visual Studio IDE가 소스 코드에 변경이 가해질 때마다 수시로 불리는 구조입니다. 의미인즉, Execute 코드에서 하는 일이 많을 수록 코드 편집 창의 반응 속도는 점점 악화될 수 있다는 것입니다. 그래서, 첫 번째 방식처럼 Execute에서 모든 작업을 담당하는 구조는 XmlSrcGenerator처럼 구문 분석이 필요 없는 경우에 적합합니다.

두 번째로, Initialize 단계에서 RegisterForSyntaxNotifications을 등록해 Visual Studio IDE가 코드 수정 중 발생하는 구문 분석 단계에서 콜백을 발생시켜 Execute 코드의 대상 식별 단계를 분리해 내는 것입니다. 방법도 어렵지 않은데, 단순히 ISyntaxReceiver를 구현한 클래스의 인스턴스 생성을 하는 델리게이트를 전달해 두면,

public void Initialize(GeneratorInitializationContext context)
{
    context.RegisterForPostInitialization((ctx) =>
    {
        ctx.AddSource("AutoPropAttribute.g.cs", SourceText.From(AutoPropAttribute, Encoding.UTF8));
    });

    context.RegisterForSyntaxNotifications(() => new AutoPropSyntaxReceiver());
}

이후 비주얼 스튜디오는 코드 편집기에서 구문 분석을 수행할 때마다 콜백을 호출하므로,

class AutoPropSyntaxReceiver : ISyntaxReceiver
{

    public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
    {
    }
}

단지 개발자는 OnVisitSyntaxNode에서 대상 코드가 자동 생성될 조건을 만족하는지 식별을 해주면 됩니다. 그리고, 이후 Execute 단계에서는 OnVisitSyntaxNode에서 식별해 두었던 노드 정보를 바탕으로 소스 코드만 생성해 주면 끝입니다.

정리해 보면 이렇게 뼈대를 구성할 수 있습니다.

// ...[생략]...

namespace V1Generator
{
    [Generator]
    public class PropertySrcGenerator : ISourceGenerator
    {
        // ...[생략]...

        public void Initialize(GeneratorInitializationContext context)
        {
            // ...[생략]...

            context.RegisterForSyntaxNotifications(() => new AutoPropSyntaxReceiver());
        }

        public void Execute(GeneratorExecutionContext context)
        {
            AutoPropSyntaxReceiver? recv = context.SyntaxReceiver as AutoPropSyntaxReceiver;

            // 미리 대상 클래스를 식별해 보관해 두었던 AutoPropSyntaxReceiver.AutoPropClasses로부터 소스 코드 자동 생성
        }
    }

    class AutoPropSyntaxReceiver : ISyntaxReceiver
    {
        public List AutoPropClasses = new List();

        public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
        {
            // [AutoProp] 특성이 적용됐고, partial 클래스라면 AutoPropClasses 목록에 추가
        }
    }
}

간단하게 언급하긴 했지만, 구분 분석에 따른 자잘한 코드가 많아 생각보다 꽤 코딩 분량이 많아집니다. 아래는 위의 내용을 구현한 전체 소스 코드입니다.

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

namespace V1Generator
{
    [Generator]
    public class PropertySrcGenerator : ISourceGenerator
    {
        public const string AutoPropAttribute = @"
namespace System
{
    [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)]
    public class AutoPropAttribute : System.Attribute
    {
    }
}";

        public void Initialize(GeneratorInitializationContext context)
        {
            context.RegisterForPostInitialization((ctx) =>
            {
                ctx.AddSource("AutoPropAttribute.g.cs", SourceText.From(AutoPropAttribute, Encoding.UTF8));
            });

            context.RegisterForSyntaxNotifications(() => new AutoPropSyntaxReceiver());
        }

        public void Execute(GeneratorExecutionContext context)
        {
            AutoPropSyntaxReceiver? recv = context.SyntaxReceiver as AutoPropSyntaxReceiver;
            if (recv == null)
            {
                return;
            }

            if (recv.AutoPropClasses.Count == 0)
            {
                return;
            }

            foreach (var cls in recv.AutoPropClasses)
            {
                List<AutoFieldInfo> fieldList = GetFieldList(context.Compilation, cls);
                if (fieldList.Count == 0)
                {
                    continue;
                }

                string clsNamespace = GetNamespace(context.Compilation, cls);

                string src = GenerateSource(clsNamespace, cls.Identifier.ValueText, fieldList);
                context.AddSource($"{cls.Identifier.ValueText}.g.cs", SourceText.From(src, Encoding.UTF8));
            }
        }

        private string GetNamespace(Compilation compilation, ClassDeclarationSyntax cls)
        {
            var model = compilation.GetSemanticModel(cls.SyntaxTree);

            foreach (NamespaceDeclarationSyntax ns in cls.Ancestors().OfType<NamespaceDeclarationSyntax>())
            {
                return ns.Name.ToString();
            }

            return "";
        }

        private string GenerateSource(string clsNamespace, string className, List<AutoFieldInfo> fieldList)
        {
            IndentText sb = new IndentText();

            bool hasNamespace = string.IsNullOrEmpty(clsNamespace) == false;

            if (hasNamespace)
            {
                sb.AppendLine($"namespace {clsNamespace}");
                sb.AppendLine("{");
            }

            using (sb.Indent(hasNamespace))
            {
                sb.AppendLine(@$"partial class {className}");
                sb.AppendLine("{");

                using (sb.Indent())
                {
                    sb.Append($"public {className}(", true);
                    int count = 0;
                    foreach (var field in fieldList)
                    {
                        sb.Append($"{(count == 0 ? "" : ", ")}{field.TypeName} {field.Identifier}");
                        count++;
                    }
                    sb.AppendLine(")", false);

                    sb.AppendLine("{");

                    using (sb.Indent())
                    {
                        foreach (var field in fieldList)
                        {
                            sb.AppendLine($"this.{field.Identifier} = {field.Identifier};");
                        }
                    }

                    sb.AppendLine("}");

                    foreach (var field in fieldList)
                    {
                        sb.AppendLine($"public {field.TypeName} {GetSafeFieldName(field.Identifier)} {{ get => {field.Identifier}; set => {field.Identifier} = value; }}");
                    }
                }

                sb.AppendLine("}");
            }

            if (string.IsNullOrEmpty(clsNamespace) == false)
            {
                sb.AppendLine("}");
            }

            return sb.ToString();
        }

        private string GetSafeFieldName(string identifier)
        {
            if (identifier[0] == '_')
            {
                return identifier.Substring(0);
            }

            if (char.IsLower(identifier[0]))
            {
                return identifier[0].ToString().ToUpper() + identifier.Substring(1);
            }

            return identifier.ToUpper();
        }

        private List<AutoFieldInfo> GetFieldList(Compilation compilation, ClassDeclarationSyntax cls)
        {
            List<AutoFieldInfo> fieldList = new List<AutoFieldInfo>();

            var model = compilation.GetSemanticModel(cls.SyntaxTree);

            foreach (FieldDeclarationSyntax field in cls.DescendantNodes().OfType<FieldDeclarationSyntax>())
            {
                foreach (var item in field.Declaration.Variables)
                {
                    AutoFieldInfo info = new AutoFieldInfo
                    {
                        Identifier = item.Identifier.ValueText,
                        TypeName = field.Declaration.Type.ToString()
                    };

                    fieldList.Add(info);
                }
            }

            return fieldList;
        }
    }

    public struct AutoFieldInfo
    {
        public string Identifier;
        public string TypeName;
    }

    class AutoPropSyntaxReceiver : ISyntaxReceiver
    {
        public List<ClassDeclarationSyntax> AutoPropClasses = new List<ClassDeclarationSyntax>();

        public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
        {
            if (syntaxNode is not ClassDeclarationSyntax cds)
            {
                return;
            }

            foreach (var item in cds.AttributeLists)
            {
                foreach (var attr in item.Attributes)
                {
                    string attrName = attr.Name.ToString();

                    switch (attrName)
                    {
                        case "AutoProp":
                        case "System.AutoProp":
                        case "AutoPropAttribute":
                        case "System.AutoPropAttribute":

                            foreach (var mod in cds.Modifiers)
                            {
                                if (mod.ValueText == "partial")
                                {
                                    AutoPropClasses.Add(cds);
                                    return;
                                }
                            }
                            break;
                    }
                }
            }
        }
    }
}

이렇게 해서 Source Generator의 Version 1 규약을 이용해 자동 소스 코드 생성을 해봤습니다. ^^

(이 글의 소스 생성기 프로젝트는 PropertySrcGenerator이고, 그것을 적용한 예제 프로젝트는 PropertySrcSample입니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/28/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13578정성태3/11/20241631닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241878닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241545닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241679닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241558닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241567닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241645닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241624닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241636닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241546닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241608닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241618오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241632오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241479닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241614Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241651디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241648오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20241747닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20241749디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242626오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20241822닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241622Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241685Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20241959닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241710VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241737닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...