Microsoft MVP성태의 닷넷 이야기
.NET Framework: 256. Roslyn 맛보기 - Syntax Analysis (Roslyn Syntax API) [링크 복사], [링크+제목 복사],
조회: 29882
글쓴 사람
정성태 (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을 이용한 응용 프로그램을 작성할 때 꽤 도움이 될 것 같습니다. ^^
정성태

... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12740정성태7/29/202114679오류 유형: 747. SharePoint - InvalidOperationException 0x80131509
12739정성태7/28/202115057오류 유형: 746. Azure Active Directory - IDW10106: The 'ClientId' option must be provided.
12738정성태7/28/202115990오류 유형: 745. Azure Active Directory - Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
12737정성태7/28/202115102오류 유형: 744. Azure Active Directory - The resource principal named api://...[client_id]... was not found in the tenant
12736정성태7/28/202115387오류 유형: 743. Active Azure Directory에서 "API permissions"의 권한 설정이 "Not granted for ..."로 나오는 문제
12735정성태7/27/202115224.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms) [2]파일 다운로드1
12734정성태7/26/202132041스크립트: 20. 특정 단어로 시작하거나/끝나는 문자열을 포함/제외하는 정규 표현식 - Look-around
12733정성태7/23/202119957.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면? [1]파일 다운로드2
12732정성태7/23/202113397오류 유형: 742. SharePoint - The super user account utilized by the cache is not configured.
12731정성태7/23/202115412개발 환경 구성: 584. Add Internal URLs 화면에서 "Save" 버튼이 비활성화 된 경우
12730정성태7/23/202116871개발 환경 구성: 583. Visual Studio Code - Go 코드에서 입력을 받는 경우
12729정성태7/22/202115316.NET Framework: 1080. xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture
12728정성태7/22/202115351.NET Framework: 1079. MSTestv2 단위 테스트에 메서드/클래스/어셈블리 수준의 문맥 제공
12727정성태7/21/202116529.NET Framework: 1078. C# 단위 테스트 - MSTestv2/NUnit의 Assert.Inconclusive 사용법(?) [1]
12726정성태7/21/202116292VS.NET IDE: 169. 비주얼 스튜디오 - 단위 테스트 선택 시 MSTestv2 외의 xUnit, NUnit 사용법 [1]
12725정성태7/21/202114785오류 유형: 741. Failed to find the "go" binary in either GOROOT() or PATH
12724정성태7/21/202117714개발 환경 구성: 582. 윈도우 환경에서 Visual Studio Code + Go (Zip) 개발 환경 [1]
12723정성태7/21/202114537오류 유형: 740. SharePoint - Alternate access mappings have not been configured 경고
12722정성태7/20/202114313오류 유형: 739. MSVCR110.dll이 없어 exe 실행이 안 되는 경우
12721정성태7/20/202115501오류 유형: 738. The trust relationship between this workstation and the primary domain failed. - 세 번째 이야기
12720정성태7/19/202114783Linux: 43. .NET Core/5+ 응용 프로그램의 Ubuntu (Debian) 패키지 준비
12719정성태7/19/202113940오류 유형: 737. SharePoint 설치 시 "0x800710D8 The object identifier does not represent a valid object." 오류 발생
12718정성태7/19/202113950개발 환경 구성: 581. Windows에서 WSL로 파일 복사 시 root 소유권으로 적용되는 문제파일 다운로드1
12717정성태7/18/202114146Windows: 195. robocopy에서 파일의 ADS(Alternate Data Stream) 정보 복사를 제외하는 방법
12716정성태7/17/202115278개발 환경 구성: 580. msbuild의 Exec Task에 robocopy를 사용하는 방법파일 다운로드1
12715정성태7/17/202122461오류 유형: 736. Windows - MySQL zip 파일 버전의 "mysqld --skip-grant-tables" 실행 시 비정상 종료 [1]
... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...