Microsoft MVP성태의 닷넷 이야기
.NET Framework: 256. Roslyn 맛보기 - Syntax Analysis (Roslyn Syntax API) [링크 복사], [링크+제목 복사],
조회: 30002
글쓴 사람
정성태 (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)
11000정성태7/16/201620601오류 유형: 342. Microsoft Visual Studio 2010 Tools for Office Runtime (x86 and x64) 설치 시 오류
10999정성태7/16/201622033오류 유형: 341. .NET Framework 4.5.2가 설치 안 되는 경우
10998정성태7/16/201621881.NET Framework: 598. C# - Excel 시트에 윈도우 폼 기능을 추가하는 방법 [1]파일 다운로드1
10997정성태7/16/201621216오류 유형: 340. HTTP Error 500.23 - Internal Server Error파일 다운로드1
10996정성태7/14/201626784Windows: 118. 유선 접속 상태에서 재부팅하면 무선 연결이 자동 연결 안되는 문제 [4]파일 다운로드1
10995정성태6/27/201620931VS.NET IDE: 109. Visual Studio 유료 버전 사용자의 주기적인 온라인 인증을 없애는 방법
10994정성태6/23/201620342개발 환경 구성: 285. 알고스팟(https://algospot.com)을 위한 Visual C++ 답안 작성 요령파일 다운로드1
10993정성태6/23/201621135.NET Framework: 597. 닷넷 메타데이터에 struct/class(값/참조 형식)의 구분이 있을까요?
10992정성태6/13/201618281오류 유형: 339. vbs 스크립트 실행 시 항상 실행 여부를 묻는 질문 창이 뜬다면?
10991정성태6/13/201622599오류 유형: 338. octave-gui 실행 시 "octave-gui.exe has stopped working" 오류
10990정성태6/13/201624120오류 유형: 337. missing type specifier - [type] assumed. Note: C++ does not support default-[type]
10989정성태6/7/201620619.NET Framework: 596. C# - WCF wsDualHttpBinding의 ClientBaseAddress 속성 - 두 번째 이야기
10988정성태6/3/201621588기타: 57. Outlook blocked access to the following potentially unsafe attachments
10987정성태6/2/201622646.NET Framework: 595. XLL 파일에 포함된 .NET 어셈블리를 추출하는 방법
10986정성태6/1/201623079.NET Framework: 594. C# - WCF wsDualHttpBinding의 ClientBaseAddress 속성
10985정성태6/1/201621613오류 유형: 336. An error occurred while ejecting 'DVD RW drive ...'
10984정성태5/31/201627328.NET Framework: 593. C# - wsDualHttpBinding WCF 예제 프로그램파일 다운로드1
10983정성태5/30/201621484VC++: 97. C++ 템플릿 remove_pointer, enable_if, is_pointer 사용 예제파일 다운로드1
10982정성태5/26/201619829오류 유형: 335. SQL Server Management Studio - The database ... is not accessible.
10981정성태5/24/201624791.NET Framework: 592. C# - Lights Out 퍼즐 풀기 [2]파일 다운로드1
10980정성태5/24/201622040VS.NET IDE: 108. Visual Studio 2013/2015를 위한 "Macros for Visual Studio"
10979정성태5/23/201625270.NET Framework: 591. C# - 조합(Combination) 예제 코드 - 두 번째 이야기파일 다운로드1
10978정성태5/23/201623944.NET Framework: 590. C# - 모든 경우의 수를 조합하는 코드 (2)파일 다운로드1
10977정성태5/23/201628419.NET Framework: 589. C# - 모든 경우의 수를 조합하는 코드 (1)파일 다운로드1
10976정성태5/20/201622827Math: 18. C# - 오일러 공식을 이용한 복소수 값의 라디안 회전파일 다운로드1
10975정성태5/20/201623258Math: 17. C# - 복소수 타입의 승수를 지원하는 Power 메서드파일 다운로드1
... 106  107  108  109  110  111  112  113  114  115  116  [117]  118  119  120  ...