Microsoft MVP성태의 닷넷 이야기
.NET Framework: 521. Roslyn을 이용해 C# 문법 변형하기 (2) [링크 복사], [링크+제목 복사],
조회: 15462
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

Roslyn을 이용해 C# 문법 변형하기 (2)

Pre build 단계를 거치는 것도 좋겠지만, 역시나 geek스러운 사람들이 원하는 것은 컴파일 시 변형입니다. 이에 대해 좋은 사례를 아래의 블로그에서 찾을 수 있습니다.

Adventures in Roslyn: Adding crazily powerful operator overloading to C# 6
; https://smellegantcode.wordpress.com/2014/04/24/adventures-in-roslyn-adding-crazily-powerful-operator-overloading-to-c-6/

위의 글을 정리해 보면.

원래 다음과 같이 배열을 연결하는 '+' 연산 기능은 C#에 없는데,

class Program
{
    static void Main(string[] args)
    {
        var nums1 = new[] { 1, 2, 3 };
        var nums2 = new[] { 4, 5 };

        var nums3 = nums1 + nums2;
    }
}

'+' 연산자가 사용된 피연산자에 대해 '확장 메서드'를 정의해 둔다면,

using System.Collections.Generic;
using System.Linq;

public static class EnumerableOperatorExtension
{
    public static IEnumerable<T> Addition<T>(this IEnumerable<T> left, IEnumerable<T> right)
    {
        return left.Concat(right);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var nums1 = new[] { 1, 2, 3 };
        var nums2 = new[] { 4, 5 };

        var nums3 = nums1 + nums2;
    }
}

어차피 '+' 연산자의 메서드 명이 "Addition"이기 때문에 그것과 연결지어 컴파일을 가능하게 만들자는 의도입니다. 이를 위해 수정한 곳은, Compilers / CSharp / CSharpCodeAnalysis 프로젝트의 Binder_Operators.cs 파일입니다.

// E:\roslyn\src\Compilers\CSharp\Portable\Binder\Binder_Operators.cs

private BoundExpression BindSimpleBinaryOperator(BinaryExpressionSyntax node, DiagnosticBag diagnostics,
    BoundExpression left, BoundExpression right, ref int compoundStringLength)
{
    // ...[생략]...

    LookupResultKind resultKind;
    ImmutableArray<MethodSymbol> originalUserDefinedOperators;
    var best = this.BinaryOperatorOverloadResolution(kind, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators);

    // However, as an implementation detail, we never "fail to find an applicable 
    // operator" during overload resolution if we have x == null, etc. We always
    // find at least the reference conversion object == object; the overload resolution
    // code does not reject that.  Therefore what we should do is only bind 
    // "x == null" as a nullable-to-null comparison if overload resolution chooses
    // the reference conversion.

    BoundExpression resultLeft = left;
    BoundExpression resultRight = right;
    MethodSymbol resultMethod = null;
    ConstantValue resultConstant = null;
    BinaryOperatorKind resultOperatorKind;
    TypeSymbol resultType;
    bool hasErrors;

    if (!best.HasValue)
    {
        resultOperatorKind = kind;
        resultType = CreateErrorType();
        hasErrors = true;
    }
    else
    {
        // ...[생략]...
    }

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

BinaryOperatorOverloadResolution 메서드에서 '+' 연산자에 대해 overload된 연산자를 못 찾게 되어 실패를 반환하기 때문에 if (!best.HasValue) 절에서 한번 더 다음과 같이 확장 메서드에서 찾아 보는 코드를 추가합니다.

if (!best.HasValue)
{
    string methodName = Enum.GetName(typeof(BinaryOperatorKind), kind);
    var methodCall = MakeInvocationExpression(node, left, methodName, ImmutableArray.Create(right), diagnostics);
    if (methodCall != null && !methodCall.HasAnyErrors)
    {
        return methodCall;
    }

    resultOperatorKind = kind;
    resultType = CreateErrorType();
    hasErrors = true;
}

사실, 저는 이 예제에서 '문법 확장'의 흥미로움보다는 이런 변화가 Visual Studio의 에디터에서도 일관되게 적용된다는 점이 마음에 듭니다. "Adventures in Roslyn: Adding crazily powerful operator overloading to C# 6" 글에서도 설명하고 있지만 Addition 확장 메서드가 없는 경우 다음과 같이 Visual Studio 코드 에디터에서 올바르지 않다는 적색선(red squiggle)이 보이지만,

roslyn1.jpg

Addition 확장 메서드를 추가하면 이렇게 사라집니다.

roslyn2.jpg

그런데, 직접 제가 현재 버전의 RoslynLight.sln 빌드로 해보니까 아쉽지만 다음과 같이 적색선이 보입니다. (물론, 컴파일은 잘 됩니다.)

roslyn3.png

이유를 대충 분석해 보면, Process Explorer를 통해 devenv.exe내에 로드된 "Microsoft.CodeAnalysis.CSharp.dll"의 경로가 원래의 Visual Studio가 쓰던 것이기 때문입니다.

C:\Windows\assembly\NativeImages_v4.0.30319_32\Microsoft.C1d3c2215#\a1f942b3d6393e8b6c1d6a89f416f941\Microsoft.CodeAnalysis.CSharp.ni.dll

즉, GAC가 아닌 "%LOCALAPPDATA%\Microsoft\VisualStudio\14.0Roslyn\Extensions\MSOpenTech\OpenSourceDebug\0.7" 폴더에 우리가 새롭게 빌드한 "Microsoft.CodeAnalysis.CSharp.dll" 어셈블리를 로드해야만 적색선이 안 보일텐데, 그렇지 않은 것입니다.

그렇긴 해도 과거의 어느 시점에는 저것이 통합되었다는 것을 의미하니... 아마도 정식 버전에서는 어떻게 바뀌는 지 두고 봐야 할 것 같습니다. ^^




"Adventures in Roslyn: Adding crazily powerful operator overloading to C# 6" 글에서 시도한 것은 어찌 보면 C# 6.0의 새로운 기능으로 추가된,

New Language Features in C# 6
; https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6

"Extension Add methods in collection initializers"라는 것과 다소 유사한 원칙을 따릅니다.




이 외에도 "Daniel Earwicker" 씨가 설명한 문법 변형 관련된 글이 2개가 더 있으니 관심있으신 분은 참고하세요. ^^

Adventures in Roslyn: A new kind of managed lvalue pointer
; https://smellegantcode.wordpress.com/2014/04/27/adventures-in-roslyn-a-new-kind-of-managed-lvalue-pointer/

Adventures in Roslyn: Using pointer syntax as a shorthand for IEnumerable
; https://smellegantcode.wordpress.com/2014/04/26/adventures-in-roslyn-using-pointer-syntax-as-a-shorthand-for-ienumerable/




그나저나, 이런 시도도 있었군요. ^^

Fody/Fody 
; https://github.com/Fody/Fody

Manipulating the IL of an assembly as part of a build requires a significant amount of plumbing code. This plumbing code involves knowledge of both the MSBuild and Visual Studio APIs. Fody attempts to eliminate that plumbing code through an extensible add-in model.






로슬린 소스 코드 중에는 자동 생성되는 코드들이 있으므로 해당 파일을 직접 수정하는 것에 유의해야 합니다. 가령 이름에 ".Generated."라고 붙은 것들이 있는데요.

E:\roslyn\Binaries\Obj\CSharpCodeAnalysis\Debug\Syntax.xml.Generated.cs

이런 경우 "E:\roslyn\src\Compilers\CSharp\Portable\Syntax\Syntax.xml" 파일로부터 자동 생성되는 것들이기 때문에 변경하고 싶다면 syntax.xml을 변경해야 합니다.

그럼, 어떻게 자동생성되는지 과정을 한번 찾아 볼까요? ^^

우선 Syntax.xml 파일을 담고 있는 프로젝트 파일의 내용을 보면 다음과 같이 VSL.Imports.targets 파일과 CSharpSyntaxGeneratorToolPath 항목을 정의하고 있습니다.

============== E:\roslyn\src\Compilers\CSharp\Portable\CSharpCodeAnalysis.csproj ==============

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c)  Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- ...[생략]... -->
    <CSharpSyntaxGeneratorToolPath>$(OutDir)CSharpSyntaxGenerator.exe</CSharpSyntaxGeneratorToolPath>
<!-- ...[생략]... -->
  <ImportGroup Label="Targets">
    <Import Project="..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Imports.targets" />
    <Import Project="..\..\..\..\build\VSL.Imports.Closed.targets" />
    <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  </ImportGroup>
</Project>

VSL.Imports.targets 파일을 보면 이것은 다시 내부에 GenerateCompilerInternals.targets을 포함합니다.

============== E:\roslyn\src\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Imports.targets ==============

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <!-- ...[생략]... -->
  <Import Project="GenerateCompilerInternals.targets" />
    <!-- ...[생략]... -->
</Project>

GenerateCompilerInternals.targets을 보면 이제 수수께끼가 풀립니다.

============== E:\roslyn\src\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\GenerateCompilerInternals.targets ==============
    <!-- ...[생략]... -->

    <Target
        Name="GenerateSyntaxModel"
        Inputs="@(SyntaxDefinition);$(VBSyntaxGeneratorToolPath);$(CSharpSyntaxGeneratorToolPath)"
        Outputs="@(SyntaxDefinition -> '$(IntermediateOutputPath)%(Filename)%(Extension).Generated$(DefaultLanguageSourceExtension)')"
        Condition="'$(Language)' == 'VB' or '$(Language)' == 'C#'"
        >
        <PropertyGroup>
            <SyntaxGenerator Condition="'$(Language)' == 'VB'">$(MonoPrefix) "$(VBSyntaxGeneratorToolPath)"</SyntaxGenerator>
            <SyntaxGenerator Condition="'$(Language)' == 'C#'">$(MonoPrefix) "$(CSharpSyntaxGeneratorToolPath)"</SyntaxGenerator>
            <GeneratedSyntaxModel>@(SyntaxDefinition -> '$(IntermediateOutputPath)%(Filename)%(Extension).Generated$(DefaultLanguageSourceExtension)')</GeneratedSyntaxModel>
        </PropertyGroup>

            <Exec
            Command='$(SyntaxGenerator) @(SyntaxDefinition) $(GeneratedSyntaxModel)'
            Outputs="$(GeneratedSyntaxModel)"
        >
            <Output TaskParameter="Outputs" ItemName="FileWrites" />
        </Exec>
    </Target>

    <!-- ...[생략]... -->

테스트를 위해 위의 <Exec /> 부분을 주석처리하면 Syntax.xml 파일을 변경해도 Syntax.xml.Generated.cs 파일의 내용이 변경되지 않습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/23/2021]

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

비밀번호

댓글 작성자
 



2015-06-23 03시34분
[이성환] AOP를 지원할 PostSharp 대체재를 찾다가 Fody 를 한 번 써봤는데
와~ 대박! 필요한 건 것들이 거의 다 들어 있더군요. 그것도 개발자 코드를 건드리지 않고 IL 수준에서 지원되는 것이 맘에 들었습니다.
Fody가 Mono.Cecil 을 이용하는 거라 Roslyn과 크게 관계가 있지는 않지만 Roslyn으로도 비슷한 기능들을 만들어낼 수 있게되었군요.
특히 AOP에 사용할 기능들을 만들기에 제격일 듯 합니다. 간단한 기능들은 한 번 만들어봐야 겠습니다. =ㅂ=b
[guest]
2015-06-24 12시20분
이성환님의 의견으로는 Fody가 나름 쓸만하다는 것이군요. ^^ 기회 되면 저도 한번 써봐야겠습니다.
정성태
2017-06-20 12시37분
정성태
2017-06-20 12시38분
Adding Matt operator to Roslyn - Syntax, Lexer and Parser
; http://marcinjuraszek.com/2017/05/adding-matt-operator-to-roslyn-part-1.html
정성태
2017-06-20 12시41분
정성태

... 46  47  48  49  50  51  52  53  54  55  56  57  58  59  [60]  ...
NoWriterDateCnt.TitleFile(s)
12129정성태1/26/202015311.NET Framework: 882. C# - 키움 Open API+ 사용 시 Registry 등록 없이 KHOpenAPI.ocx 사용하는 방법 [3]
12128정성태1/26/202010105오류 유형: 591. The code execution cannot proceed because mfc100.dll was not found. Reinstalling the program may fix this problem.
12127정성태1/25/20209980.NET Framework: 881. C# DLL에서 제공하는 Win32 export 함수의 내부 동작 방식(VT Fix up Table)파일 다운로드1
12126정성태1/25/202010797.NET Framework: 880. C# - PE 파일로부터 IMAGE_COR20_HEADER 및 VTableFixups 테이블 분석파일 다운로드1
12125정성태1/24/20208684VS.NET IDE: 141. IDE0019 - Use pattern matching
12124정성태1/23/202010504VS.NET IDE: 140. IDE1006 - Naming rule violation: These words must begin with upper case characters: ...
12123정성태1/23/202011980웹: 39. Google Analytics - gtag 함수를 이용해 페이지 URL 수정 및 별도의 이벤트 생성 방법 [2]
12122정성태1/20/20208981.NET Framework: 879. C/C++의 UNREFERENCED_PARAMETER 매크로를 C#에서 우회하는 방법(IDE0060 - Remove unused parameter '...')파일 다운로드1
12121정성태1/20/20209554VS.NET IDE: 139. Visual Studio - Error List: "Could not find schema information for the ..."파일 다운로드1
12120정성태1/19/202010967.NET Framework: 878. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 네 번째 이야기(IL 코드로 직접 구현)파일 다운로드1
12119정성태1/17/202010993디버깅 기술: 160. Windbg 확장 DLL 만들기 (3) - C#으로 만드는 방법
12118정성태1/17/202011638개발 환경 구성: 466. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 세 번째 이야기 [1]
12117정성태1/15/202010631디버깅 기술: 159. C# - 디버깅 중인 프로세스를 강제로 다른 디버거에서 연결하는 방법파일 다운로드1
12116정성태1/15/202011101디버깅 기술: 158. Visual Studio로 디버깅 시 sos.dll 확장 명령어를 (비롯한 windbg의 다양한 기능을) 수행하는 방법
12115정성태1/14/202010881디버깅 기술: 157. C# - PEB.ProcessHeap을 이용해 디버깅 중인지 확인하는 방법파일 다운로드1
12114정성태1/13/202012745디버깅 기술: 156. C# - PDB 파일로부터 심벌(Symbol) 및 타입(Type) 정보 열거 [1]파일 다운로드3
12113정성태1/12/202013363오류 유형: 590. Visual C++ 빌드 오류 - fatal error LNK1104: cannot open file 'atls.lib' [1]
12112정성태1/12/20209967오류 유형: 589. PowerShell - 원격 Invoke-Command 실행 시 "WinRM cannot complete the operation" 오류 발생
12111정성태1/12/202013190디버깅 기술: 155. C# - KernelMemoryIO 드라이버를 이용해 실행 프로그램을 숨기는 방법(DKOM: Direct Kernel Object Modification) [16]파일 다운로드1
12110정성태1/11/202011796디버깅 기술: 154. Patch Guard로 인해 블루 스크린(BSOD)가 발생하는 사례 [5]파일 다운로드1
12109정성태1/10/20209716오류 유형: 588. Driver 프로젝트 빌드 오류 - Inf2Cat error -2: "Inf2Cat, signability test failed."
12108정성태1/10/20209726오류 유형: 587. Kernel Driver 시작 시 127(The specified procedure could not be found.) 오류 메시지 발생
12107정성태1/10/202010688.NET Framework: 877. C# - 프로세스의 모든 핸들을 열람 - 두 번째 이야기
12106정성태1/8/202012117VC++: 136. C++ - OSR Driver Loader와 같은 Legacy 커널 드라이버 설치 프로그램 제작 [1]
12105정성태1/8/202010745디버깅 기술: 153. C# - PEB를 조작해 로드된 DLL을 숨기는 방법
12104정성태1/7/202011455DDK: 9. 커널 메모리를 읽고 쓰는 NT Legacy driver와 C# 클라이언트 프로그램 [4]
... 46  47  48  49  50  51  52  53  54  55  56  57  58  59  [60]  ...