Microsoft MVP성태의 닷넷 이야기
.NET Framework: 256. Roslyn 맛보기 - Syntax Analysis (Roslyn Syntax API) [링크 복사], [링크+제목 복사],
조회: 29894
글쓴 사람
정성태 (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)
11049정성태9/24/201620952오류 유형: 357. 윈도우 백업 시 오류 - 0x81000037
11048정성태9/24/201621998VC++: 100. 전역 변수 유형별 실행 파일 크기 차이점
11047정성태9/21/201625803기타: 61. algospot.com - 양자화(Quantization) 문제 [2]파일 다운로드1
11046정성태9/15/201627457개발 환경 구성: 298. Windows 10 - bash 실행 시 시작 디렉터리 자동 변경
11045정성태9/15/201620104Windows: 119. Windows 10 - bash 명령어 창을 실행했는데 바로 닫히는 경우
11044정성태9/15/201620355VS.NET IDE: 112. Visual Studio 확장 - 편집 화면 내에서 링크를 누르면 외부 웹 브라우저에서 열기
11043정성태9/15/201621780.NET Framework: 606. .NET 스레드 콜 스택 덤프 (7) - ClrMD(Microsoft.Diagnostics.Runtime)를 이용한 방법 [1]파일 다운로드1
11042정성태9/14/201619945오류 유형: 356. Unknown custom metadata item kind: 6
11041정성태9/10/201619421.NET Framework: 605. CLR4 보안 - yield 구문 내에서 SecurityCritical 메서드 사용 불가 - 2번째 이야기
11040정성태9/10/201626711.NET Framework: 604. C# Windows Forms - Drag & Drop 예제 코드 [2]파일 다운로드1
11039정성태9/9/201623221오류 유형: 355. Visual Studio 빌드 오류 - error CS0122: '__ComObject' is inaccessible due to its protection level
11038정성태9/9/201625061VC++: 99. 서로 다른 프로세스에서 WM_DROPFILES 메시지를 전송하는 방법파일 다운로드1
11037정성태9/8/201628301.NET Framework: 603. socket - shutdown 호출이 필요한 사례파일 다운로드1
11036정성태8/29/201624779개발 환경 구성: 297. 소스 코드가 없는 닷넷 어셈블리를 디버깅할 때 지역 변숫값을 확인하는 방법
11035정성태8/29/201620410오류 유형: 354. .NET Reflector - PDB 생성 화면에서 "Clear Store"를 하면 "Index and length must refer to a location within the string" 예외 발생
11034정성태8/25/201624432개발 환경 구성: 296. .NET Core 프로젝트를 NuGet Gallery에 배포하는 방법 [2]
11033정성태8/24/201622321오류 유형: 353. coreclr 빌드 시 error C3249: illegal statement or sub-expression for 'constexpr' function
11032정성태8/23/201621530개발 환경 구성: 295. 최신의 Visual C++ 컴파일러 도구를 사용하는 방법 [1]
11031정성태8/23/201617771오류 유형: 352. Error encountered while pushing to the remote repository: Response status code does not indicate success: 403 (Forbidden).
11030정성태8/23/201620325VS.NET IDE: 111. Team Explorer - 추가한 Git Remote 저장소가 Branch에 보이지 않는 경우
11029정성태8/18/201627461.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [1]파일 다운로드1
11028정성태8/15/201621524오류 유형: 351. Octave 설치 시 JRE 경로 문제
11027정성태8/15/201622584.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상
11026정성태8/13/201623573Math: 19. 행렬 연산으로 본 해밍코드
11025정성태8/12/201622287개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201621585오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
... 106  107  108  109  110  111  112  113  114  [115]  116  117  118  119  120  ...