2006-02-14 Rafael Teixeira <rafaelteixeirabr@hotmail.com>
[mono.git] / mcs / class / System / Microsoft.VisualBasic / VBCodeCompiler.cs
1 //
2 // Microsoft VisualBasic VBCodeCompiler Class implementation
3 //
4 // Authors:
5 //      Jochen Wezel (jwezel@compumaster.de)
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //
8 // (c) 2003 Jochen Wezel (http://www.compumaster.de)
9 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
10 //
11 // Modifications:
12 // 2003-11-28 JW: create reference to Microsoft.VisualBasic if not explicitly done
13
14 //
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
22 // 
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
25 // 
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 //
34
35 using System;
36 using System.CodeDom;
37 using System.CodeDom.Compiler;
38 using System.IO;
39 using System.Text;
40 using System.Reflection;
41 using System.Collections;
42 using System.Collections.Specialized;
43 using System.Diagnostics;
44 using System.Text.RegularExpressions;
45
46 namespace Microsoft.VisualBasic
47 {
48         internal class VBCodeCompiler : VBCodeGenerator, ICodeCompiler
49         {
50                 static string windowsMonoPath;
51                 static string windowsMbasPath;
52                 static VBCodeCompiler ()
53                 {
54                         if (Path.DirectorySeparatorChar == '\\') {
55                                 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
56                                 MethodInfo get_gac = gac.GetGetMethod (true);
57                                 string p = Path.GetDirectoryName (
58                                         (string) get_gac.Invoke (null, null));
59                                 windowsMonoPath = Path.Combine (
60                                         Path.GetDirectoryName (
61                                                 Path.GetDirectoryName (p)),
62                                         "bin\\mono.bat");
63                                 if (!File.Exists (windowsMonoPath))
64                                         windowsMonoPath = Path.Combine (
65                                                 Path.GetDirectoryName (
66                                                         Path.GetDirectoryName (p)),
67                                                 "bin\\mono.exe");
68 #if NET_2_0
69                                 windowsMbasPath =
70                                         Path.Combine (p, "2.0\\mbas.exe");
71 #else
72                                 windowsMbasPath =
73                                         Path.Combine (p, "1.0\\mbas.exe");
74 #endif
75                         }
76                 }
77
78                 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
79                 {
80                         return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
81                 }
82
83                 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
84                 {
85                         if (options == null) {
86                                 throw new ArgumentNullException ("options");
87                         }
88
89                         try {
90                                 return CompileFromDomBatch (options, ea);
91                         } finally {
92                                 options.TempFiles.Delete ();
93                         }
94                 }
95
96                 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
97                 {
98                         return CompileAssemblyFromFileBatch (options, new string[] { fileName });
99                 }
100
101                 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
102                 {
103                         if (options == null) {
104                                 throw new ArgumentNullException ("options");
105                         }
106
107                         try {
108                                 return CompileFromFileBatch (options, fileNames);
109                         } finally {
110                                 options.TempFiles.Delete ();
111                         }
112                 }
113
114                 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
115                 {
116                         return CompileAssemblyFromSourceBatch (options, new string[] { source });
117                 }
118
119                 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
120                 {
121                         if (options == null) {
122                                 throw new ArgumentNullException ("options");
123                         }
124
125                         try {
126                                 return CompileFromSourceBatch (options, sources);
127                         } finally {
128                                 options.TempFiles.Delete ();
129                         }
130                 }
131
132                 static string BuildArgs (CompilerParameters options, string[] fileNames)
133                 {
134                         StringBuilder args = new StringBuilder ();
135                         args.Append ("/quiet ");
136                         if (options.GenerateExecutable)
137                                 args.Append ("/target:exe ");
138                         else
139                                 args.Append ("/target:library ");
140
141                         /* Disabled. It causes problems now. -- Gonzalo
142                         if (options.IncludeDebugInformation)
143                                 args.AppendFormat("/debug ");
144                         */
145
146                         if (options.TreatWarningsAsErrors)
147                                 args.Append ("/warnaserror ");
148
149                         if (options.WarningLevel != -1)
150                                 args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
151
152                         if (options.OutputAssembly == null) {
153                                 string ext = (options.GenerateExecutable ? "exe" : "dll");
154                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext, !options.GenerateInMemory);
155                         }
156
157                         args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
158
159                         bool Reference2MSVBFound;
160                         Reference2MSVBFound = false;
161                         if (null != options.ReferencedAssemblies) {
162                                 foreach (string import in options.ReferencedAssemblies) {
163                                         if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
164                                                 Reference2MSVBFound = true;
165                                         args.AppendFormat ("/r:\"{0}\" ", import);
166                                 }
167                         }
168                         
169                         // add standard import to Microsoft.VisualBasic if missing
170                         if (!Reference2MSVBFound)
171                                 args.Append ("/r:\"Microsoft.VisualBasic\" ");
172
173                         if (options.CompilerOptions != null) {
174                                 args.Append (options.CompilerOptions);
175                         }
176                         
177                         args.Append (" -- "); // makes mbas not try to process filenames as options
178
179                         foreach (string source in fileNames)
180                                 args.AppendFormat ("\"{0}\" ", source);
181
182                         return args.ToString ();
183                 }
184
185                 static CompilerError CreateErrorFromString (string error_string)
186                 {
187                         // When IncludeDebugInformation is true, prevents the debug symbols stats from braeking this.
188                         if (error_string.StartsWith ("WROTE SYMFILE") || error_string.StartsWith ("OffsetTable"))
189                                 return null;
190
191                         CompilerError error = new CompilerError ();
192                         Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)\s+)*" +
193                                                 @"(?<level>error|warning)\s*(?<number>.*):\s(?<message>.*)",
194                                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
195
196                         Match match = reg.Match (error_string);
197                         if (!match.Success)
198                                 return null;
199
200                         if (String.Empty != match.Result ("${file}"))
201                                 error.FileName = match.Result ("${file}");
202
203                         if (String.Empty != match.Result ("${line}"))
204                                 error.Line = Int32.Parse (match.Result ("${line}"));
205
206                         if (String.Empty != match.Result ("${column}"))
207                                 error.Column = Int32.Parse (match.Result ("${column}"));
208
209                         if (match.Result ("${level}") == "warning")
210                                 error.IsWarning = true;
211
212                         error.ErrorNumber = match.Result ("${number}");
213                         error.ErrorText = match.Result ("${message}");
214                         return error;
215                 }
216
217                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
218                 {
219                         return temp_files.AddExtension (extension, keepFile);
220                 }
221
222                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
223                 {
224                         return temp_files.AddExtension (extension);
225                 }
226
227                 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
228                 {
229                         if (options == null) {
230                                 throw new ArgumentNullException ("options");
231                         }
232
233                         if (fileNames == null) {
234                                 throw new ArgumentNullException ("fileNames");
235                         }
236
237                         CompilerResults results = new CompilerResults (options.TempFiles);
238                         Process mbas = new Process ();
239
240                         string mbas_output;
241                         string[] mbas_output_lines;
242                         // FIXME: these lines had better be platform independent.
243                         if (Path.DirectorySeparatorChar == '\\') {
244                                 mbas.StartInfo.FileName = windowsMonoPath;
245                                 mbas.StartInfo.Arguments = windowsMbasPath + ' ' + BuildArgs (options, fileNames);
246                         } else {
247                                 mbas.StartInfo.FileName = "mbas";
248                                 mbas.StartInfo.Arguments = BuildArgs (options, fileNames);
249                         }
250                         mbas.StartInfo.CreateNoWindow = true;
251                         mbas.StartInfo.UseShellExecute = false;
252                         mbas.StartInfo.RedirectStandardOutput = true;
253                         try {
254                                 mbas.Start ();
255                                 mbas_output = mbas.StandardOutput.ReadToEnd ();
256                                 mbas.WaitForExit ();
257                         } finally {
258                                 results.NativeCompilerReturnValue = mbas.ExitCode;
259                                 mbas.Close ();
260                         }
261
262                         mbas_output_lines = mbas_output.Split (Environment.NewLine.ToCharArray ());
263                         bool loadIt = true;
264                         foreach (string error_line in mbas_output_lines) {
265                                 CompilerError error = CreateErrorFromString (error_line);
266                                 if (null != error) {
267                                         results.Errors.Add (error);
268                                         if (!error.IsWarning)
269                                                 loadIt = false;
270                                 }
271                         }
272
273                         if (loadIt) {
274                                 if (options.GenerateInMemory) {
275                                         using (FileStream fs = File.OpenRead (options.OutputAssembly)) {
276                                                 byte[] buffer = new byte[fs.Length];
277                                                 fs.Read (buffer, 0, buffer.Length);
278                                                 results.CompiledAssembly = Assembly.Load (buffer, null, options.Evidence);
279                                                 fs.Close ();
280                                         }
281                                 } else {
282                                         results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
283                                         results.PathToAssembly = options.OutputAssembly;
284                                 }
285                         } else {
286                                 results.CompiledAssembly = null;
287                         }
288
289                         return results;
290                 }
291
292                 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
293                 {
294                         if (options == null) {
295                                 throw new ArgumentNullException ("options");
296                         }
297
298                         if (ea == null) {
299                                 throw new ArgumentNullException ("ea");
300                         }
301
302                         string[] fileNames = new string[ea.Length];
303                         StringCollection assemblies = options.ReferencedAssemblies;
304
305                         for (int i = 0; i < ea.Length; i++) {
306                                 CodeCompileUnit compileUnit = ea[i];
307                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
308                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
309                                 StreamWriter s = new StreamWriter (f);
310                                 if (compileUnit.ReferencedAssemblies != null) {
311                                         foreach (string str in compileUnit.ReferencedAssemblies) {
312                                                 if (!assemblies.Contains (str))
313                                                         assemblies.Add (str);
314                                         }
315                                 }
316
317                                 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
318                                 s.Close ();
319                                 f.Close ();
320                         }
321                         return CompileAssemblyFromFileBatch (options, fileNames);
322                 }
323
324                 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
325                 {
326                         if (options == null) {
327                                 throw new ArgumentNullException ("options");
328                         }
329
330                         if (sources == null) {
331                                 throw new ArgumentNullException ("sources");
332                         }
333
334                         string[] fileNames = new string[sources.Length];
335
336                         for (int i = 0; i < sources.Length; i++) {
337                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
338                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
339                                 using (StreamWriter s = new StreamWriter (f)) {
340                                         s.Write (sources[i]);
341                                         s.Close ();
342                                 }
343                                 f.Close ();
344                         }
345                         return CompileFromFileBatch (options, fileNames);
346                 }
347         }
348 }
349