やじゅ@アプリケーション・ラボ わんくま支局

目次

Blog 利用状況

ニュース

プロフィール

MSMVP

Visual BasicでRoslynを使ってみる その3

これは、Visual Basic Advent Calendar 2013 12/15日の記事。

Roslynの機能としてコード解析の一部をコーディングしてみます。
その前にVBならではの問題点を紹介します。
ソースコードを文字列変数に格納するコードをC#で書いた場合、下記のようになります。

public static string src = @"
        using System;
 
        namespace HelloWorld {
            class Program {
             static void Main(string[] args) {
                Console.WriteLine(""Hello, World!"");
             }
            }
        }
        ";
ところが、これと同じことをVBで書いてみますと、下記コードのように悲しいことになるわけです。
Dim src As String =
    "Imports System" & vbNewLine &
    vbNewLine &
    "Namespace HelloWorld" & vbNewLine &
    "  Module Program" & vbNewLine &
    "    Sub Main(args As String())" & vbNewLine &
    "      Console.WriteLine(""Hello, World!"")" & vbNewLine &
    "    End Sub" & vbNewLine &
    "  End Module" & vbNewLine &
    "End Namespace"
これ、なんとかならないかなーと調べていくと、下記サイトがいい解決法を提示してくれています。
Mutliline String Literals in VB.NET
Dim src As String =
    <string>
    Imports System

    Namespace HelloWorld
        Module Program
           Sub Main(args As String())
               Console.WriteLine("Hello, World!")
           End Sub
        End Module
    End Namespace
    </string>.Value

XMLリテラルにすれば、C#と同様な感じで記述できるようになります。
今回は”<string>”タグにしてますが、他の例をみると”<a>”タグを使用しているところもあります。
また、<![CDATA[文字列]]>.Valueでも同様のことが出来ますが、この場合、囲まれた文字列がVisual Studio上の文字色設定では薄いグレーで見辛いので、「VBのXML CDataセクション」の文字色を変更するといいでしょう。
あと、VB2010以降は暗黙の行継続である「_」(アンダースコア)が不要になっているので、読みやすくなっています。

下記のソースは、文字列変数のソースコードをコード解析して、ノード種類とノード値を「|」(パイプ)区切りで出力しています。
Imports Roslyn.Compilers
Imports Roslyn.Compilers.VisualBasic
Imports Roslyn.Scripting
Imports Roslyn.Scripting.VisualBasic

Module Module1

    Sub Main()
        Dim src As String =
       <string>
       Imports System

       Namespace HelloWorld
          Module Program
             Sub Main(args As String())
                Console.WriteLine("Hello, World!")
             End Sub
          End Module
       End Namespace
       </string>.Value

        Dim tree = SyntaxTree.ParseText(src)
        For Each node As SyntaxNode In tree.GetRoot().ChildNodesAndTokens()
            PrintSyntaxTree(node)
        Next

        Console.ReadLine()

    End Sub

    Private Sub PrintSyntaxTree(node As SyntaxNode)
        If node IsNot Nothing Then
            Console.WriteLine(node.Kind.ToString & " | " & node.ToString())
            For Each child As SyntaxNode In node.ChildNodes()
                PrintSyntaxTree(child)
            Next
        End If
    End Sub

End Module

【出力結果】
ImportsStatement | Imports System
MembersImportsClause | System
IdentifierName | System
NamespaceBlock | Namespace HelloWorld
                Module Program
                   Sub Main(args As String())
                       Console.WriteLine("Hello, World!")
                   End Sub
                End Module
            End Namespace
NamespaceStatement | Namespace HelloWorld
IdentifierName | HelloWorld
ModuleBlock | Module Program
                   Sub Main(args As String())
                       Console.WriteLine("Hello, World!")
                   End Sub
                End Module
ModuleStatement | Module Program
SubBlock | Sub Main(args As String())
                       Console.WriteLine("Hello, World!")
                   End Sub
SubStatement | Sub Main(args As String())
ParameterList | (args As String())
Parameter | args As String()
ModifiedIdentifier | args
SimpleAsClause | As String()
ArrayType | String()
PredefinedType | String
ArrayRankSpecifier | ()
CallStatement | Console.WriteLine("Hello, World!")
InvocationExpression | Console.WriteLine("Hello, World!")
MemberAccessExpression | Console.WriteLine
IdentifierName | Console
IdentifierName | WriteLine
ArgumentList | ("Hello, World!")
SimpleArgument | "Hello, World!"
StringLiteralExpression | "Hello, World!"
EndSubStatement | End Sub
EndModuleStatement | End Module
EndNamespaceStatement | End Namespace

次回は、Roslynについてもう少し踏み込んだことをしてみます。

投稿日時 : 2013年12月15日 20:17

コメントを追加

# Hi, just wanted to mention, I enjoyed this blog post. It was funny. Keep on posting! 2021/12/24 5:11 Hi, just wanted to mention, I enjoyed this blog po

Hi, just wanted to mention, I enjoyed this blog post.
It was funny. Keep on posting!

# ivermectin tablets order http://stromectolabc.com/
ivermectin generic cream 2022/02/07 17:11 Busjdhj

ivermectin tablets order http://stromectolabc.com/
ivermectin generic cream

# doxycycline mono https://doxycyline1st.com/
buy doxycycline 2022/02/25 21:57 Doxycycline

doxycycline mono https://doxycyline1st.com/
buy doxycycline

# doxycycline tablets https://doxycyline1st.com/
doxycycline order online 2022/02/26 9:11 Doxycycline

doxycycline tablets https://doxycyline1st.com/
doxycycline order online

# cheap erectile dysfunction https://erectionpills.best/
generic ed pills 2022/06/28 10:36 ErectionPills

cheap erectile dysfunction https://erectionpills.best/
generic ed pills

# paxlovid eua fact sheet https://paxlovid.best/
paxlovid indications 2022/09/07 22:26 Paxlovid

paxlovid eua fact sheet https://paxlovid.best/
paxlovid indications

# write an expository essay c37qlf 2022/09/08 19:53 AaronBlact


Fantastic write ups. Cheers! https://definitionessays.com/ hugh gallagher college essay

# buy prednisone canada https://prednisone20mg.icu/ 2022/10/15 6:54 Prednisone

buy prednisone canada https://prednisone20mg.icu/

# prednisone cream rx https://prednisone20mg.site/
25 mg prednisone 2022/11/15 10:45 Prednisone

prednisone cream rx https://prednisone20mg.site/
25 mg prednisone

# prednisone otc uk https://prednisonepills.site/
prednisone over the counter south africa 2022/11/28 16:30 Prednisone

prednisone otc uk https://prednisonepills.site/
prednisone over the counter south africa

# free and best https://datingsiteonline.site/
dating singles site 2022/12/05 17:02 Tading

free and best https://datingsiteonline.site/
dating singles site

# dating personal https://datingonlinehot.com/
dating single 2022/12/09 11:37 Dating

dating personal https://datingonlinehot.com/
dating single

# the best ed pill https://edpills.science/
ed meds online 2023/01/07 8:18 EdPills

the best ed pill https://edpills.science/
ed meds online

# who invented homework n38ivx 2023/02/10 8:47 Albertosed

You mentioned it exceptionally well.
https://essaywritingservicelinked.com/ write my essay cheap

# thesis statment c55ekp 2023/03/03 8:04 Josephbried

You actually expressed that terrifically.
help write thesis statement https://writingthesistops.com/ service quality thesis philippines

# admission essay editing services l928ph 2023/03/07 2:26 Gregorysaipt


Nicely put, Cheers.
steps to write an essay https://service-essay.com essay help live chat https://essaywritinghelperonline.com

# writing the winning thesis or dissertation a90pgb 2023/03/07 20:27 EugeneSib


Many thanks. I value it!
do my essay for cheap https://service-essay.com phd thesis writing help https://phdthesisdissertation.com

# how to write a university essay l92ypa 2023/03/08 12:12 EugeneSib


Whoa tons of wonderful info!
pay to write an essay https://essaywritingservicebbc.com writing a good essay for college https://domyhomeworkformecheap.com

# cheap ghost writer services t97fkh 2023/03/08 23:03 Gregorysaipt


Kudos! Numerous write ups.
postgraduate thesis https://buyanessayscheaponline.com help writing a thesis statement https://writingpaperforme.com

# college essay cover page s132gx 2023/03/09 4:53 EugeneSib

You actually said this perfectly.
write essay https://researchproposalforphd.com essay thesis https://writingresearchtermpaperservice.com

# write my essay for cheap z98vie 2023/03/09 19:44 EugeneSib

You reported this fantastically.
best essay writing https://buyanessayscheaponline.com coursework writing help https://homeworkcourseworkhelps.com

# 250 word college essay a39soy 2023/03/10 10:14 EugeneSib


Truly plenty of very good tips!
dissertation funding https://helpwritingdissertation.com instant essay writer https://writingresearchtermpaperservice.com

# best dissertation writers c571sy 2023/03/10 18:05 Gregorysaipt

You revealed that well!
copy writing services https://buycheapessaysonline.com help me write a thesis statement https://essaywriting4you.com

# help me write an essay t426mj 2023/03/11 0:52 EugeneSib


Whoa a lot of excellent material.
technical writing help https://bestmasterthesiswritingservice.com writing a reflective essay https://essaywritingserviceahrefs.com

# phd research proposal k25pwf 2023/03/11 15:55 Gregorysaipt


Nicely put, Appreciate it!
good college admission essays https://cheapessaywriteronlineservices.com website for essay writing https://writingresearchtermpaperservice.com

# article rewriting service x445ic 2023/03/12 6:53 EugeneSib


Regards! An abundance of facts!
phd research proposal https://customthesiswritingservice.com phd writer https://writinganessaycollegeservice.com

# dissertation help online p56fnp 2023/03/12 13:35 Gregorysaipt


Effectively voiced of course. .
how to write a paragraph essay https://argumentativethesis.com cheap ghost writer services https://customthesiswritingservice.com

# dissertation phrases t12kif 2023/03/13 11:22 Gregorysaipt


With thanks! Ample information.
cv writing services usa https://quality-essays.com write my essay https://homeworkcourseworkhelps.com

# website that writes essays for you i592uo 2023/03/13 12:00 EugeneSib


Whoa lots of very good information!
dissertation writing for construction students https://homeworkcourseworkhelps.com best web content writing services https://essaywritingservicetop.com

# awesome college essays w278hf 2023/04/01 7:36 EugeneSib

You actually suggested it terrifically.
doctoral theses https://writinganessaycollegeservice.com how to write essay about myself https://topswritingservices.com

# canadian pharcharmy online https://pillswithoutprescription.pro/# 2023/05/14 14:53 PillsPresc

canadian pharcharmy online https://pillswithoutprescription.pro/#

# ed medications https://edpill.pro/# - treatment of ed 2023/06/27 5:15 EdPills

ed medications https://edpill.pro/# - treatment of ed

# best ed pills non prescription https://edpills.ink/# - treatment for ed 2023/07/26 14:09 EdPills

best ed pills non prescription https://edpills.ink/# - treatment for ed

# Cost of Plavix on Medicare https://plavix.guru/ plavix best price 2023/10/23 16:39 Plavixxx

Cost of Plavix on Medicare https://plavix.guru/ plavix best price

# buy doxycycline for dogs https://doxycycline.forum/ buy cheap doxycycline 2023/11/25 3:42 Doxycycline

buy doxycycline for dogs https://doxycycline.forum/ buy cheap doxycycline

# order prednisone with mastercard debit https://prednisone.bid/ compare prednisone prices 2023/12/27 2:25 Prednisone

order prednisone with mastercard debit https://prednisone.bid/ compare prednisone prices

タイトル  
名前  
URL
コメント