ICodeCompilerを使って簡易コンパイラを作る

注意:
この文書は以前「.NETでいきまっしょい!」で公開していたものですが、公開以降メンテナンスされていません。 今や古い情報となった内容が記載されている場合があるのでご注意ください。

ICodeCompilerを使って簡易コンパイラを作る


 System.CodeDom.Compiler名前空間にあるICodeCompilerを使うとインコードコンパイル(ソースコードによるコンパイル)を行うことができます。 これを使えば、Visual Studio .NETを使用せずに独自に作成したアプリケーション内でVB.NETやC#のソースコードをコンパイルすることができます。 これを行う詳しい手順などの解説はしませんが、VB.NETで作成したアプリケーションでVB.NETとC#のソースコードをコンパイルするサンプルを作りました。 細部にコメントをふってあるので説明は不用だと思います。 また、そのクラスがどの名前空間に属するかわかりやすいように完全限定名で宣言しています。 クラスの詳細を知りたい場合はこれを参考にMSDNなどを活用して下さい。
インコードコンパイルを行うアプリケーション(VB.NET)
ソースコード
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
Public Class SimpleCompilerDialog
    Inherits System.Windows.Forms.Form

#Region " Windows フォーム デザイナで生成されたコード "

    Public Sub New()
        MyBase.New()

        ' この呼び出しは Windows フォーム デザイナで必要です。
        InitializeComponent()

        ' InitializeComponent() 呼び出しの後に初期化を追加します。

    End Sub

    ' Form は dispose をオーバーライドしてコンポーネント一覧を消去します。
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    ' Windows フォーム デザイナで必要です。
    Private components As System.ComponentModel.IContainer

    ' メモ : 以下のプロシージャは、Windows フォーム デザイナで必要です。
    ' Windows フォーム デザイナを使って変更してください。  
    ' コード エディタは使用しないでください。
    Friend WithEvents richTextBoxSourceCode As System.Windows.Forms.RichTextBox
    Friend WithEvents richTextBoxOutput As System.Windows.Forms.RichTextBox
    Friend WithEvents textBoxOutputAssembly As System.Windows.Forms.TextBox
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents buttonCompile As System.Windows.Forms.Button
    Friend WithEvents groupBoxSourceLanguage As System.Windows.Forms.GroupBox
    Friend WithEvents radioButtonLangVB As System.Windows.Forms.RadioButton
    Friend WithEvents radioButtonLangCS As System.Windows.Forms.RadioButton
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents Label3 As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.richTextBoxSourceCode = New System.Windows.Forms.RichTextBox()
        Me.richTextBoxOutput = New System.Windows.Forms.RichTextBox()
        Me.textBoxOutputAssembly = New System.Windows.Forms.TextBox()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.buttonCompile = New System.Windows.Forms.Button()
        Me.groupBoxSourceLanguage = New System.Windows.Forms.GroupBox()
        Me.radioButtonLangCS = New System.Windows.Forms.RadioButton()
        Me.radioButtonLangVB = New System.Windows.Forms.RadioButton()
        Me.Label2 = New System.Windows.Forms.Label()
        Me.Label3 = New System.Windows.Forms.Label()
        Me.groupBoxSourceLanguage.SuspendLayout()
        Me.SuspendLayout()
        '
        'richTextBoxSourceCode
        '
        Me.richTextBoxSourceCode.AcceptsTab = True
        Me.richTextBoxSourceCode.AutoWordSelection = True
        Me.richTextBoxSourceCode.Font = New System.Drawing.Font("MS ゴシック", 9.0!, _
        System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(128, Byte))
        Me.richTextBoxSourceCode.Location = New System.Drawing.Point(16, 32)
        Me.richTextBoxSourceCode.Name = "richTextBoxSourceCode"
        Me.richTextBoxSourceCode.Size = New System.Drawing.Size(464, 272)
        Me.richTextBoxSourceCode.TabIndex = 0
        Me.richTextBoxSourceCode.Text = "richTextBoxSourceCode"
        Me.richTextBoxSourceCode.WordWrap = False
        '
        'richTextBoxOutput
        '
        Me.richTextBoxOutput.AcceptsTab = True
        Me.richTextBoxOutput.Font = New System.Drawing.Font("MS ゴシック", 9.0!, _
        System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(128, Byte))
        Me.richTextBoxOutput.Location = New System.Drawing.Point(16, 328)
        Me.richTextBoxOutput.Name = "richTextBoxOutput"
        Me.richTextBoxOutput.ReadOnly = True
        Me.richTextBoxOutput.Size = New System.Drawing.Size(664, 144)
        Me.richTextBoxOutput.TabIndex = 1
        Me.richTextBoxOutput.Text = "richTextBoxOutput"
        Me.richTextBoxOutput.WordWrap = False
        '
        'textBoxOutputAssembly
        '
        Me.textBoxOutputAssembly.Location = New System.Drawing.Point(496, 32)
        Me.textBoxOutputAssembly.Name = "textBoxOutputAssembly"
        Me.textBoxOutputAssembly.Size = New System.Drawing.Size(184, 19)
        Me.textBoxOutputAssembly.TabIndex = 2
        Me.textBoxOutputAssembly.Text = "textBoxOutputAssembly"
        '
        'Label1
        '
        Me.Label1.Location = New System.Drawing.Point(496, 16)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(184, 16)
        Me.Label1.TabIndex = 3
        Me.Label1.Text = "出力ファイル"
        '
        'buttonCompile
        '
        Me.buttonCompile.Location = New System.Drawing.Point(616, 184)
        Me.buttonCompile.Name = "buttonCompile"
        Me.buttonCompile.Size = New System.Drawing.Size(64, 32)
        Me.buttonCompile.TabIndex = 4
        Me.buttonCompile.Text = "コンパイル"
        '
        'groupBoxSourceLanguage
        '
        Me.groupBoxSourceLanguage.Controls.AddRange(New System.Windows.Forms.Control() _
        {Me.radioButtonLangCS, Me.radioButtonLangVB})
        Me.groupBoxSourceLanguage.Location = New System.Drawing.Point(496, 72)
        Me.groupBoxSourceLanguage.Name = "groupBoxSourceLanguage"
        Me.groupBoxSourceLanguage.Size = New System.Drawing.Size(184, 96)
        Me.groupBoxSourceLanguage.TabIndex = 5
        Me.groupBoxSourceLanguage.TabStop = False
        Me.groupBoxSourceLanguage.Text = "ソースファイルの言語"
        '
        'radioButtonLangCS
        '
        Me.radioButtonLangCS.Location = New System.Drawing.Point(8, 56)
        Me.radioButtonLangCS.Name = "radioButtonLangCS"
        Me.radioButtonLangCS.Size = New System.Drawing.Size(168, 24)
        Me.radioButtonLangCS.TabIndex = 1
        Me.radioButtonLangCS.Text = "Visual C# .NET"
        '
        'radioButtonLangVB
        '
        Me.radioButtonLangVB.Checked = True
        Me.radioButtonLangVB.Location = New System.Drawing.Point(8, 24)
        Me.radioButtonLangVB.Name = "radioButtonLangVB"
        Me.radioButtonLangVB.Size = New System.Drawing.Size(168, 24)
        Me.radioButtonLangVB.TabIndex = 0
        Me.radioButtonLangVB.TabStop = True
        Me.radioButtonLangVB.Text = "Visual Basic .NET"
        '
        'Label2
        '
        Me.Label2.Location = New System.Drawing.Point(16, 312)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(168, 16)
        Me.Label2.TabIndex = 6
        Me.Label2.Text = "出力"
        '
        'Label3
        '
        Me.Label3.Location = New System.Drawing.Point(16, 16)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(184, 16)
        Me.Label3.TabIndex = 7
        Me.Label3.Text = "ソースコード"
        '
        'SimpleCompilerDialog
        '
        Me.AcceptButton = Me.buttonCompile
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 12)
        Me.ClientSize = New System.Drawing.Size(696, 486)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.Label3, _
        Me.Label2, Me.groupBoxSourceLanguage, Me.buttonCompile, Me.Label1, _
        Me.textBoxOutputAssembly, Me.richTextBoxOutput, Me.richTextBoxSourceCode})
        Me.Name = "SimpleCompilerDialog"
        Me.Text = "シンプル コンパイラ"
        Me.groupBoxSourceLanguage.ResumeLayout(False)
        Me.ResumeLayout(False)

    End Sub

#End Region





    ' フォームのLoadイベント
    Private Sub SimpleCompilerDialog_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load

        richTextBoxOutput.Text = ""
        richTextBoxSourceCode.Text = ""

        textBoxOutputAssembly.Text = ""

    End Sub





    ' コンパイルを開始する
    Private Sub buttonCompile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonCompile.Click

        ' アセンブリ出力先
        Dim strOutputAssembly As String = textBoxOutputAssembly.Text

        ' 出力ファイル名を指定していなかった場合
        If strOutputAssembly = "" Then

            richTextBoxOutput.Text = "出力ファイル名が指定されていません。"

            Return

        End If

        ' ソースコード
        Dim strSourceCode As String = richTextBoxSourceCode.Text





        ' [VB/CSharp]CodeProviderクラスのインスタンスを作成
        ' [VB/CSharp]CodeProviderクラスはSystem.CodeDom.Compiler.CodeDomProviderの派生クラス
        Dim codeProvider As System.CodeDom.Compiler.CodeDomProvider

        ' 言語別のCodeProviderインスタンス作成
        If radioButtonLangVB.Checked Then

            codeProvider = New Microsoft.VisualBasic.VBCodeProvider()

        ElseIf radioButtonLangCS.Checked Then

            codeProvider = New Microsoft.CSharp.CSharpCodeProvider()

        Else

            richTextBoxOutput.Text = "言語が選択されていません"

            Return

        End If

        ' 作成したCodeProviderから、ICodeCompilerインターフェイスを取得
        Dim codeCompiler As System.CodeDom.Compiler.ICodeCompiler

        codeCompiler = codeProvider.CreateCompiler()

        ' コンパイラパラメータ
        Dim compilerParameters As New System.CodeDom.Compiler.CompilerParameters()

        With compilerParameters

            ' 実行可能ファイルを作成する
            .GenerateExecutable = True

            ' 出力ファイルを設定
            .OutputAssembly = strOutputAssembly

            ' デバッグ情報を含めない
            .IncludeDebugInformation = False

        End With

        ' コンパイル結果を取得するためのクラス ( CompileAssemblyFromSource()メソッドの戻り値 )
        Dim compilerResults As System.CodeDom.Compiler.CompilerResults

        Try

            ' コンパイル開始 ( ファイルからコンパイルする場合はCompileAssemblyFromFile()メソッドを用いる )
            compilerResults = codeCompiler.CompileAssemblyFromSource(compilerParameters, strSourceCode)

        Catch ex As Exception

            ' 出力ペインに表示
            richTextBoxOutput.Text = "例外がスルーされました。" + vbNewLine + ex.Message

            Return

        End Try





        ' コンパイル結果を出力
        Dim strCompilerResults As String = ""

        With compilerResults

            Try

                ' 出力されたアセンブリの情報
                If Not .CompiledAssembly Is Nothing Then

                    strCompilerResults = "出力されたアセンブリ名: " + .CompiledAssembly.FullName + vbNewLine

                End If

            Catch ex As Exception

                strCompilerResults += "アセンブリ情報が取得できませんでした。" + vbNewLine

                strCompilerResults += ex.Message + vbNewLine

            End Try

            strCompilerResults += "出力されたアセンブリへのパス: " + .PathToAssembly + vbNewLine


            ' 出力結果
            strCompilerResults += vbNewLine

            strCompilerResults += "---------------------------[ 出力結果 ]---------------------------" + vbNewLine

            Dim strOutput As String

            For Each strOutput In .Output

                strCompilerResults += strOutput + vbNewLine

            Next

        End With

        ' 出力ペインに表示
        richTextBoxOutput.Text = strCompilerResults

    End Sub

End Class

 このアプリケーションを実行すると次のようになります。
実行結果
実行結果

 このアプリケーションを用いて、次のVB.NETソースコードをコンパイルさせてみます。 また、出力結果も載せておきます。
ソースコード
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
Imports System

Class HelloWorld

    Public Shared Sub Main()

        Console.WriteLine( "Hello, world!" )

        Dim intResult As Integer = Message( "This is VB.NET code." )

        Console.WriteLine( intResult.ToString() )

    End Sub

    Public Shared Function Message( ByVal msg As String ) As Integer

        Console.WriteLine( msg )

        Return msg.Length

    End Function

End Class
出力結果
出力されたアセンブリ名: Test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
出力されたアセンブリへのパス: E:\HelloWorldVB.exe

---------------------------[ 出力結果 ]---------------------------
実行結果
Hello, world!
This is VB.NET code.
20

 つづいて、C#のソースコードをコンパイルさせてみます。
ソースコード
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
using System;

namespace HelloWorld
{
    class HelloWorld
    {
        [STAThread]
        public static void Main()
        {
            Console.WriteLine( "Hello, world!" );

            int iResult = Message( "This is C# code." );

            Console.WriteLine( iResult.ToString() );
        }

        public static int Message( string msg )
        {
            Console.WriteLine( msg );

            return msg.Length;
        }
    }
}
出力結果
出力されたアセンブリ名: HelloWorldCS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
出力されたアセンブリへのパス: E:\HelloWorldCS.exe

---------------------------[ 出力結果 ]---------------------------
実行結果
Hello, world!
This is C# code.
16

 このように、なんの問題もなくコンパイル・実行することができます。 つづいて、わざとエラーの出るようなソースコードをVB.NETで組んでコンパイルさせます。
ソースコード
001
002
003
004
005
006
007
008
009
010
011
using System

Class HelloWorld

    Public Static Sub Main()

        System.out.println( "Hello, world!" );

    End Sub

End Class
出力結果(VB.NETとしてコンパイル)
(都合上テンポラリフォルダの名前は隠してあります。)
(%Temporaly%の部分がシステムのテンポラリフォルダになります。)



アセンブリ情報が取得できませんでした。
ファイルまたはアセンブリ名 Test.exe、またはその依存関係の 1 つが見つかりませんでした。
出力されたアセンブリへのパス: E:\Test.exe

---------------------------[ 出力結果 ]---------------------------
E:\Visual Basic .NET Program\SimpleCompiler\bin> "d:\windows\microsoft.net\framework\v1.0.3705\vbc.exe" 
/t:exe /utf8output /out:"E:\Test.exe" /debug-  "D:\%Temporaly%4u7enswr.0.vb"


Microsoft(R) Visual Basic .NET Compiler version 7.00.9466
for Microsoft(R) .NET Framework version 1.00.3705.288
Copyright (C) Microsoft Corporation 1987-2001. All rights reserved.

vbc : error BC30737: 正しいシグニチャを持つ、アクセス可能な 'Main' メソッドは、'Test' に見つかりませんでした。
D:\%Temporaly%4u7enswr.0.vb(1) : error BC30188: 宣言が必要です。

using System
~~~~~       
D:\%Temporaly%4u7enswr.0.vb(5) : error BC30810: メソッドを 'Static' として宣言することはできません。

    Public Static Sub Main()
                      ~~~~  
D:\%Temporaly%4u7enswr.0.vb(7) : error BC30456: 'out' は 'System' のメンバではありません。

        System.out.println( "Hello, world!" );
        ~~~~~~~~~~                            
D:\%Temporaly%4u7enswr.0.vb(7) : error BC30037: 文字が有効ではありません。

        System.out.println( "Hello, world!" );
                                             ~

 エラーがある場合でも、このように詳細なエラー情報を取得することができます。