Microsoft MVP성태의 닷넷 이야기
.NET Framework: 256. Roslyn 맛보기 - Syntax Analysis (Roslyn Syntax API) [링크 복사], [링크+제목 복사],
조회: 29998
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 7개 있습니다.)

Roslyn 맛보기 - Syntax Analysis (Roslyn Syntax API)


Roslyn 맛보기 (1) - C# 소스 코드를 스크립트 처럼 다루는 방법
Roslyn 맛보기 (2) - C# Interactive (1)
Roslyn 맛보기 (3) - C# Interactive (2)
Roslyn 맛보기 (4) - Roslyn Services APIs를 이용한 Code Issue 및 Code Action 기능 소개
Roslyn 맛보기 (5) - Syntax Analysis (Roslyn Syntax API)
Roslyn 맛보기 (6) - Roslyn Symbol / Binding API
Roslyn 맛보기 (7) - SyntaxTree 조작

지난 글에서 Roslyn을 이용한 C# 스크립트 엔진을 다뤘는데요.

Roslyn 맛보기 - C# 소스 코드를 스크립트 처럼 다루는 방법
; https://www.sysnet.pe.kr/2/0/1153

이번에는 "%PROGRAMFILES% (x86)\Microsoft Codename Roslyn CTP\Documentation\Getting Started - Syntax Analysis (CSharp).docx" 문서에서 설명하고 있는 "Syntax API"를 소개해 보겠습니다.

Rosyln에서 제공되는 Syntax API는 곧, C# 언어에 대한 Parser를 제공하는 것과 같다고 보면 되겠습니다. 코드 먼저 보고, 설명을 해볼까요?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            SyntaxTree tree = SyntaxTree.ParseCompilationUnit(
                @"using System;
                using System.Collections.Generic;
                using System.Linq;
 
                namespace HelloWorld
                {
                    class Program
                    {
                        static void Main(string[] args)
                        {
                            Console.WriteLine(""Hello, World!"");
                        }
                    }
                }");

            var root = (CompilationUnitSyntax)tree.Root;
        }
    }
}

 

사용법이 생각보다 간단하지요? ^^ 보시는 바와 같이 "하나의 코드 파일"에 대해서 그에 매칭되는 "하나의 SyntaxTree"를 얻어내고 있습니다. (SyntaxTree는 Immutable입니다.)

자, 그럼 말 그대로 SyntaxTree이니, 하위 구조가 Tree 유형으로 발전할텐데 이 트리에 속하는 구성요소를 보면 다음과 같이 크게 4가지로 나뉠 수 있습니다.

SyntaxTree 클래스: 완전한 하나의 parse tree를 이루는 인스턴스
SyntaxNode 클래스: 구문 구조(Syntax construct)에 해당하는 요소들. 가령 declarations, statements, clauses, expressions.
SyntaxToken 구조체: 개별적인 keyword, identifier, operator, punctuation 요소들
SyntaxTrivia 구조체: 실질적인 C# 소스 코드에 크게 영향이 없는 요소들. 가령 whitespace between tokens, preprocessor directives, comments.


위와 같은 정보와 함께, 문서에 있는 예제 트리 구조를 보면 대강의 이해가 되실 것입니다. ^^

syntax_tree_1.png

다시 소스 코드로 돌아가서,

var root = (CompilationUnitSyntax)tree.Root;

이렇게 구해진 CompilationUnitSyntax 타입의 root 인스턴스는 다음과 같은 4개의 컬렉션 속성값을 가지고 있습니다.

Attributes: [assembly] 특성이 정의된 목록
Externs: "extern alias" 키워드로 정의된 목록
Members: namespace, class, interface, struct, ... 등의 요소들
Usings: "using System"과 같은 using 지시문이 사용된 목록


따라서, 위와 같은 소스 코드의 경우 "firstMember = root.Members[0]"은 첫 번째로 정의된 클래스를 나타내며 이에 대한 정보를 MemberDeclarationSyntax 타입을 상속받은 ClassDeclarationSyntax 타입으로 구현하고 있습니다.

firstMember.Kind == SyntaxKind.ClassDeclaration
firstMember.GetType().FullName == Roslyn.Compilers.CSharp.ClassDeclarationSyntax

문서에 의하면, 이렇게 ClassDeclarationSyntax까지 구한 다음 여전히 하위 노드 목록을 구하기 위해 Members 속성으로 접근하도록 되어 있는데 현재 공개된 CTP에서는 더 이상 Members 속성은 제공되지 않고, 대신 ChildNodes() 메서드를 통해서 하위에 접근할 수 있게 해주고 있습니다. (아마도, 정식 버전이 나오기까지 이런 부분들은 계속해서 변할지도 모릅니다.)

foreach (var item in firstMember.ChildNodes())
{
    Console.WriteLine(item.Kind);
}

예제 소스 코드의 경우, 당연히 ClassDeclarationSyntax의 첫번째로 열람되는 ChildNode는 Main 메서드에 해당하는 "MethodDeclarationSyntax" 타입을 가리킵니다.

대충 감이 잡히시죠? ^^

어찌 보면, Reflection 기능과 별반 차이가 없어보이는데요. 중요한 차이점을 하나 정리해 드리자면, Syntax API는 "소스 코드"와 정확히 매핑되어 연동된다는 겁니다. 일례로, "Getting Started - Syntax Analysis (CSharp).docx" 문서에서는 주어진 C# 코드에서 사용된 "using" 문 중에서 "System."으로 시작하지 않은 다른 참조들을 열람하는 기능을 구현한 예제를 소개하고 있습니다. Reflection으로는 그런 기능을 도저히 구현할 수가 없지요. ^^

결론적으로 "Roslyn"만 있다면, 필요한 경우 언제든 C# 소스 코드를 마음껏 분석할 수 있다는 것!




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/17/2021]

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

비밀번호

댓글 작성자
 



2011-11-14 10시23분
C# - "extern alias"에 대한 적용 예

Assembly redirection in .NET
; (broken) http://www.dotnetscraps.com/dotnetscraps/post/Assembly-redirection-in-NET.aspx
정성태
2011-11-22 11시02분
Roslyn Syntax Visualizers
; https://devblogs.microsoft.com/visualstudio/roslyn-syntax-visualizers/

C# 코드 윈도우의 내용을 Roslyn SyntaxTree로 보여주는 Visual Studio IDE 윈도우가 소개되고 있습니다. 아울러, 디버깅 시에 SyntaxTree를 담고 있는 변수의 내용도 보여주는 Debugger Visualizer도 있고.

이것들을 활용하면 Roslyn을 이용한 응용 프로그램을 작성할 때 꽤 도움이 될 것 같습니다. ^^
정성태

... 106  107  108  109  110  111  112  [113]  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11100정성태11/7/201628858개발 환경 구성: 304. Wi-Fi Direct 지원 여부 확인 방법 [1]
11099정성태11/7/201630773.NET Framework: 620. C#에서 C/C++ 함수로 콜백 함수를 전달하는 예제 코드파일 다운로드1
11098정성태11/7/201620117오류 유형: 368. 빌드 이벤트에서 robocopy 사용 시 $(TargetDir) 매크로를 지정하는 경우 오류 발생
11097정성태11/7/201623050오류 유형: 367. go install: no install location for directory [...경로...] outside GOPATH
11096정성태11/6/201626832디버깅 기술: 83. PDB 파일을 수동으로 다운로드하는 방법
11095정성태11/6/201623095.NET Framework: 619. C# - Cognitive Services 중의 하나인 Face API를 사용해 얼굴 인식 및 흐림(blur) 효과 적용 [1]파일 다운로드1
11094정성태11/5/201624757VC++: 105. Visual Studio 2013/2015 - Ceemple OpenCV 확장을 이용한 웹캠 영상 출력
11093정성태11/4/201624684웹: 34. Edge 브라우저도 지원하는 클립보드 복사를 위한 자바스크립트 코드
11092정성태11/3/201631617.NET Framework: 618. C# - NAudio를 이용한 MP3 파일 재생 [5]파일 다운로드1
11091정성태11/3/201626318VC++: 104. std::call_once를 이용해 thread-safe한 Singleton 객체 생성파일 다운로드1
11090정성태11/1/201627782VC++: 103. C++ CreateTimerQueue, CreateTimerQueueTimer 예제 코드 [9]파일 다운로드1
11089정성태11/1/201626735디버깅 기술: 82. Windows 10을 위한 Symbol(PDB) 파일 내려받는 방법 [2]
11088정성태11/1/201630814.NET Framework: 617. C# - AForge.NET을 이용한 MP4 동영상 파일 재생 [7]파일 다운로드1
11087정성태11/1/201625198.NET Framework: 616. AForge.Video.FFMPEG를 최신 버전의 ffmpeg 파일로 의존성을 변경하는 방법파일 다운로드1
11086정성태11/1/201619067오류 유형: 366. The Microsoft Passport Container service terminated with the following error: General access denied error
11085정성태10/27/201633460.NET Framework: 615. C# - AForge.NET을 이용한 웹캠 영상 출력 [2]파일 다운로드1
11084정성태10/26/201621414오류 유형: 365. The User Profile Service service failed to the sign-in.
11083정성태10/26/201627976Windows: 131. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선 순위 조정 기능 [1]
11082정성태10/26/201629911.NET Framework: 614. C# - DateTime.Ticks의 정밀도 [4]파일 다운로드1
11081정성태10/26/201620407오류 유형: 364. You need to fix your Microsoft Account for apps on your other devices to be able to launch apps and continue experiences on this device.
11080정성태10/24/201623559Windows: 130. Windows Server 2016 Nano 서버 설치 방법
11079정성태10/21/201620690Windows: 129. Windows Server 2016 설치 CD에 있는 Convert-WindowsImage.ps1 사용 방법 정리
11078정성태10/21/201622012Windows: 128. Windows Server 2016 Nano 서버 VHD 이미지 만드는 방법 - TP5 기준
11077정성태10/21/201620505오류 유형: 363. Active Directory 서버의 NETLOGON 서비스가 멈췄을 때 발생하는 문제
11076정성태10/21/201620084오류 유형: 362. 윈도우 백업 시 오류 - 0x80780040
11075정성태10/20/201621006Windows: 127. Convert-WindowsImage.ps1 사용 방법 정리
... 106  107  108  109  110  111  112  [113]  114  115  116  117  118  119  120  ...