2008-04-16 Marek Habersack <mhabersack@novell.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 #if NET_2_0
52                 static string windowsvbncPath;
53 #endif
54
55                 static VBCodeCompiler ()
56                 {
57                         if (Path.DirectorySeparatorChar == '\\') {
58                                 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
59                                 MethodInfo get_gac = gac.GetGetMethod (true);
60                                 string p = Path.GetDirectoryName (
61                                         (string) get_gac.Invoke (null, null));
62                                 windowsMonoPath = Path.Combine (
63                                         Path.GetDirectoryName (
64                                                 Path.GetDirectoryName (p)),
65                                         "bin\\mono.bat");
66                                 if (!File.Exists (windowsMonoPath))
67                                         windowsMonoPath = Path.Combine (
68                                                 Path.GetDirectoryName (
69                                                         Path.GetDirectoryName (p)),
70                                                 "bin\\mono.exe");
71 #if NET_2_0
72                                 windowsvbncPath =
73                                         Path.Combine (p, "2.0\\vbnc.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 #if NET_2_0
133                 static string BuildArgs (CompilerParameters options, string[] fileNames)
134                 {
135                         StringBuilder args = new StringBuilder ();
136                         args.Append ("/quiet ");
137                         if (options.GenerateExecutable)
138                                 args.Append ("/target:exe ");
139                         else
140                                 args.Append ("/target:library ");
141
142                         /* Disabled. It causes problems now. -- Gonzalo
143                         if (options.IncludeDebugInformation)
144                                 args.AppendFormat("/debug ");
145                         */
146
147                         if (options.TreatWarningsAsErrors)
148                                 args.Append ("/warnaserror ");
149
150                         /* Disabled. vbnc does not support warninglevels.
151                         if (options.WarningLevel != -1)
152                                 args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
153                         */
154
155                         if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
156                                 string ext = (options.GenerateExecutable ? "exe" : "dll");
157                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext, !options.GenerateInMemory);
158                         }
159
160                         args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
161
162                         bool Reference2MSVBFound;
163                         Reference2MSVBFound = false;
164                         if (null != options.ReferencedAssemblies) {
165                                 foreach (string import in options.ReferencedAssemblies) {
166                                         if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
167                                                 Reference2MSVBFound = true;
168                                         args.AppendFormat ("/r:\"{0}\" ", import);
169                                 }
170                         }
171                         
172                         // add standard import to Microsoft.VisualBasic if missing
173                         if (!Reference2MSVBFound)
174                                 args.Append ("/r:\"Microsoft.VisualBasic.dll\" ");
175
176                         if (options.CompilerOptions != null) {
177                                 args.Append (options.CompilerOptions);
178                                 args.Append (" ");
179                         }
180                         /* Disabled, vbnc does not support this.
181                         args.Append (" -- "); // makes vbnc not try to process filenames as options
182                         */
183                         foreach (string source in fileNames)
184                                 args.AppendFormat (" \"{0}\" ", source);
185
186                         return args.ToString ();
187                 }
188
189                 static CompilerError CreateErrorFromString (string error_string)
190                 {
191                         CompilerError error = new CompilerError ();
192                         Regex reg = new Regex (@"^(\s*(?<file>.*)?\((?<line>\d*)(,(?<column>\d*))?\)\s+)?:\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
201                         if (String.Empty != match.Result ("${file}"))
202                                 error.FileName = match.Result ("${file}").Trim ();
203
204                         if (String.Empty != match.Result ("${line}"))
205                                 error.Line = Int32.Parse (match.Result ("${line}"));
206
207                         if (String.Empty != match.Result ("${column}"))
208                                 error.Column = Int32.Parse (match.Result ("${column}"));
209
210                         if (match.Result ("${level}").Trim () == "Warning")
211                                 error.IsWarning = true;
212
213                         error.ErrorNumber = match.Result ("${number}");
214                         error.ErrorText = match.Result ("${message}");
215                         
216                         return error;
217                 }
218
219                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
220                 {
221                         return temp_files.AddExtension (extension, keepFile);
222                 }
223 #endif
224
225                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
226                 {
227                         return temp_files.AddExtension (extension);
228                 }
229
230                 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
231                 {
232                         
233 #if !NET_2_0
234                         throw new NotSupportedException (
235 @"Compilation of Visual Basic code is not supported for v1.0/v1.1 assemblies, please use the v2.0 assemblies.
236 - If this is a web application, use xsp2/mod_mono_server2 instead of xsp/mono_mono_server (see http://www.mono-project.com/Mod_mono#ASP.NET_2_apps_do_not_work).
237 - If this is a desktop application, use gmcs to compile your application instead of mcs.");                                      
238 #else
239                         if (options == null) {
240                                 throw new ArgumentNullException ("options");
241                         }
242
243                         if (fileNames == null) {
244                                 throw new ArgumentNullException ("fileNames");
245                         }
246
247                         CompilerResults results = new CompilerResults (options.TempFiles);
248                         Process vbnc = new Process ();
249
250                         string vbnc_output = "";
251                         string[] vbnc_output_lines;
252                         // FIXME: these lines had better be platform independent.
253                         if (Path.DirectorySeparatorChar == '\\') {
254                                 vbnc.StartInfo.FileName = windowsMonoPath;
255                                 vbnc.StartInfo.Arguments = windowsvbncPath + ' ' + BuildArgs (options, fileNames);
256                         } else {
257                                 vbnc.StartInfo.FileName = "vbnc";
258                                 vbnc.StartInfo.Arguments = BuildArgs (options, fileNames);
259                         }
260                         //Console.WriteLine (vbnc.StartInfo.Arguments);
261                         vbnc.StartInfo.CreateNoWindow = true;
262                         vbnc.StartInfo.UseShellExecute = false;
263                         vbnc.StartInfo.RedirectStandardOutput = true;
264                         try {
265                                 vbnc.Start ();
266                                 vbnc_output = vbnc.StandardOutput.ReadToEnd ();
267                                 vbnc.WaitForExit ();
268                         } finally {
269                                 results.NativeCompilerReturnValue = vbnc.ExitCode;
270                                 vbnc.Close ();
271                         }
272
273                         bool loadIt = true;
274                         if (results.NativeCompilerReturnValue == 1) {
275                                 loadIt = false;
276                                 vbnc_output_lines = vbnc_output.Split (Environment.NewLine.ToCharArray ());
277                                 foreach (string error_line in vbnc_output_lines) {
278                                         CompilerError error = CreateErrorFromString (error_line);
279                                         if (null != error) {
280                                                 results.Errors.Add (error);
281                                         }
282                                 }
283                         }
284                         
285                         if ((loadIt == false && !results.Errors.HasErrors) // Failed, but no errors? Probably couldn't parse the compiler output correctly. 
286                             || (results.NativeCompilerReturnValue != 0 && results.NativeCompilerReturnValue != 1)) // Neither success (0), nor failure (1), so it crashed. 
287                         {
288                                 // Show the entire output as one big error message.
289                                 loadIt = false;
290                                 CompilerError error = new CompilerError (string.Empty, 0, 0, "VBNC_CRASH", vbnc_output);
291                                 results.Errors.Add (error);
292                         };
293
294                         if (loadIt) {
295                                 if (options.GenerateInMemory) {
296                                         using (FileStream fs = File.OpenRead (options.OutputAssembly)) {
297                                                 byte[] buffer = new byte[fs.Length];
298                                                 fs.Read (buffer, 0, buffer.Length);
299                                                 results.CompiledAssembly = Assembly.Load (buffer, null, options.Evidence);
300                                                 fs.Close ();
301                                         }
302                                 } else {
303                                         results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
304                                         results.PathToAssembly = options.OutputAssembly;
305                                 }
306                         } else {
307                                 results.CompiledAssembly = null;
308                         }
309
310                         return results;
311 #endif
312                 }
313
314                 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
315                 {
316                         if (options == null) {
317                                 throw new ArgumentNullException ("options");
318                         }
319
320                         if (ea == null) {
321                                 throw new ArgumentNullException ("ea");
322                         }
323
324                         string[] fileNames = new string[ea.Length];
325                         StringCollection assemblies = options.ReferencedAssemblies;
326
327                         for (int i = 0; i < ea.Length; i++) {
328                                 CodeCompileUnit compileUnit = ea[i];
329                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
330                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
331                                 StreamWriter s = new StreamWriter (f);
332                                 if (compileUnit.ReferencedAssemblies != null) {
333                                         foreach (string str in compileUnit.ReferencedAssemblies) {
334                                                 if (!assemblies.Contains (str))
335                                                         assemblies.Add (str);
336                                         }
337                                 }
338
339                                 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
340                                 s.Close ();
341                                 f.Close ();
342                         }
343                         return CompileAssemblyFromFileBatch (options, fileNames);
344                 }
345
346                 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
347                 {
348                         if (options == null) {
349                                 throw new ArgumentNullException ("options");
350                         }
351
352                         if (sources == null) {
353                                 throw new ArgumentNullException ("sources");
354                         }
355
356                         string[] fileNames = new string[sources.Length];
357
358                         for (int i = 0; i < sources.Length; i++) {
359                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
360                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
361                                 using (StreamWriter s = new StreamWriter (f)) {
362                                         s.Write (sources[i]);
363                                         s.Close ();
364                                 }
365                                 f.Close ();
366                         }
367                         return CompileFromFileBatch (options, fileNames);
368                 }
369         }
370 }
371