Fix XMM scanning on Mac x86.
[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.ComponentModel;
39 using System.IO;
40 using System.Text;
41 using System.Reflection;
42 using System.Collections;
43 using System.Collections.Specialized;
44 using System.Diagnostics;
45 using System.Text.RegularExpressions;
46
47 namespace Microsoft.VisualBasic
48 {
49         internal class VBCodeCompiler : VBCodeGenerator, ICodeCompiler
50         {
51                 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
52                 {
53                         return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
54                 }
55
56                 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
57                 {
58                         if (options == null) {
59                                 throw new ArgumentNullException ("options");
60                         }
61
62                         try {
63                                 return CompileFromDomBatch (options, ea);
64                         } finally {
65                                 options.TempFiles.Delete ();
66                         }
67                 }
68
69                 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
70                 {
71                         return CompileAssemblyFromFileBatch (options, new string[] { fileName });
72                 }
73
74                 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
75                 {
76                         if (options == null) {
77                                 throw new ArgumentNullException ("options");
78                         }
79
80                         try {
81                                 return CompileFromFileBatch (options, fileNames);
82                         } finally {
83                                 options.TempFiles.Delete ();
84                         }
85                 }
86
87                 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
88                 {
89                         return CompileAssemblyFromSourceBatch (options, new string[] { source });
90                 }
91
92                 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
93                 {
94                         if (options == null) {
95                                 throw new ArgumentNullException ("options");
96                         }
97
98                         try {
99                                 return CompileFromSourceBatch (options, sources);
100                         } finally {
101                                 options.TempFiles.Delete ();
102                         }
103                 }
104
105                 static string BuildArgs (CompilerParameters options, string[] fileNames)
106                 {
107                         StringBuilder args = new StringBuilder ();
108                         args.Append ("/quiet ");
109                         if (options.GenerateExecutable)
110                                 args.Append ("/target:exe ");
111                         else
112                                 args.Append ("/target:library ");
113
114                         /* Disabled. It causes problems now. -- Gonzalo
115                         if (options.IncludeDebugInformation)
116                                 args.AppendFormat("/debug ");
117                         */
118
119                         if (options.TreatWarningsAsErrors)
120                                 args.Append ("/warnaserror ");
121
122                         /* Disabled. vbnc does not support warninglevels.
123                         if (options.WarningLevel != -1)
124                                 args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
125                         */
126
127                         if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
128                                 string ext = (options.GenerateExecutable ? "exe" : "dll");
129                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext, !options.GenerateInMemory);
130                         }
131
132                         args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
133
134                         bool Reference2MSVBFound;
135                         Reference2MSVBFound = false;
136                         if (null != options.ReferencedAssemblies) {
137                                 foreach (string import in options.ReferencedAssemblies) {
138                                         if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
139                                                 Reference2MSVBFound = true;
140                                         args.AppendFormat ("/r:\"{0}\" ", import);
141                                 }
142                         }
143                         
144                         // add standard import to Microsoft.VisualBasic if missing
145                         if (!Reference2MSVBFound)
146                                 args.Append ("/r:\"Microsoft.VisualBasic.dll\" ");
147
148                         if (options.CompilerOptions != null) {
149                                 args.Append (options.CompilerOptions);
150                                 args.Append (" ");
151                         }
152                         /* Disabled, vbnc does not support this.
153                         args.Append (" -- "); // makes vbnc not try to process filenames as options
154                         */
155                         foreach (string source in fileNames)
156                                 args.AppendFormat (" \"{0}\" ", source);
157
158                         return args.ToString ();
159                 }
160
161                 static CompilerError CreateErrorFromString (string error_string)
162                 {
163                         CompilerError error = new CompilerError ();
164                         Regex reg = new Regex (@"^(\s*(?<file>.*)?\((?<line>\d*)(,(?<column>\d*))?\)\s+)?:\s*" +
165                                                 @"(?<level>Error|Warning)?\s*(?<number>.*):\s(?<message>.*)",
166                                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
167
168                         Match match = reg.Match (error_string);
169                         if (!match.Success) {
170                                 return null;
171                         }
172
173                         if (String.Empty != match.Result ("${file}"))
174                                 error.FileName = match.Result ("${file}").Trim ();
175
176                         if (String.Empty != match.Result ("${line}"))
177                                 error.Line = Int32.Parse (match.Result ("${line}"));
178
179                         if (String.Empty != match.Result ("${column}"))
180                                 error.Column = Int32.Parse (match.Result ("${column}"));
181
182                         if (match.Result ("${level}").Trim () == "Warning")
183                                 error.IsWarning = true;
184
185                         error.ErrorNumber = match.Result ("${number}");
186                         error.ErrorText = match.Result ("${message}");
187                         
188                         return error;
189                 }
190
191                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
192                 {
193                         return temp_files.AddExtension (extension, keepFile);
194                 }
195
196                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
197                 {
198                         return temp_files.AddExtension (extension);
199                 }
200
201                 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
202                 {
203                         
204                         if (options == null) {
205                                 throw new ArgumentNullException ("options");
206                         }
207
208                         if (fileNames == null) {
209                                 throw new ArgumentNullException ("fileNames");
210                         }
211
212                         CompilerResults results = new CompilerResults (options.TempFiles);
213                         Process vbnc = new Process ();
214
215                         string vbnc_output = "";
216                         string[] vbnc_output_lines;
217                         // FIXME: these lines had better be platform independent.
218                         if (Path.DirectorySeparatorChar == '\\') {
219                                 vbnc.StartInfo.FileName = MonoToolsLocator.Mono;
220                                 vbnc.StartInfo.Arguments = MonoToolsLocator.VBCompiler + ' ' + BuildArgs (options, fileNames);
221                         } else {
222                                 vbnc.StartInfo.FileName = MonoToolsLocator.VBCompiler;
223                                 vbnc.StartInfo.Arguments = BuildArgs (options, fileNames);
224                         }
225                         //Console.WriteLine (vbnc.StartInfo.Arguments);
226                         vbnc.StartInfo.CreateNoWindow = true;
227                         vbnc.StartInfo.UseShellExecute = false;
228                         vbnc.StartInfo.RedirectStandardOutput = true;
229                         try {
230                                 vbnc.Start ();
231                         } catch (Exception e) {
232                                 Win32Exception exc = e as Win32Exception;
233                                 if (exc != null) {
234                                         throw new SystemException (String.Format ("Error running {0}: {1}", vbnc.StartInfo.FileName,
235                                                                                         Win32Exception.GetErrorMessage (exc.NativeErrorCode)));
236                                 }
237                                 throw;
238                         }
239
240                         try {
241                                 vbnc_output = vbnc.StandardOutput.ReadToEnd ();
242                                 vbnc.WaitForExit ();
243                         } finally {
244                                 results.NativeCompilerReturnValue = vbnc.ExitCode;
245                                 vbnc.Close ();
246                         }
247
248                         bool loadIt = true;
249                         if (results.NativeCompilerReturnValue == 1) {
250                                 loadIt = false;
251                                 vbnc_output_lines = vbnc_output.Split (Environment.NewLine.ToCharArray ());
252                                 foreach (string error_line in vbnc_output_lines) {
253                                         CompilerError error = CreateErrorFromString (error_line);
254                                         if (null != error) {
255                                                 results.Errors.Add (error);
256                                         }
257                                 }
258                         }
259                         
260                         if ((loadIt == false && !results.Errors.HasErrors) // Failed, but no errors? Probably couldn't parse the compiler output correctly. 
261                             || (results.NativeCompilerReturnValue != 0 && results.NativeCompilerReturnValue != 1)) // Neither success (0), nor failure (1), so it crashed. 
262                         {
263                                 // Show the entire output as one big error message.
264                                 loadIt = false;
265                                 CompilerError error = new CompilerError (string.Empty, 0, 0, "VBNC_CRASH", vbnc_output);
266                                 results.Errors.Add (error);
267                         };
268
269                         if (loadIt) {
270                                 if (options.GenerateInMemory) {
271                                         using (FileStream fs = File.OpenRead (options.OutputAssembly)) {
272                                                 byte[] buffer = new byte[fs.Length];
273                                                 fs.Read (buffer, 0, buffer.Length);
274                                                 results.CompiledAssembly = Assembly.Load (buffer, null);
275                                                 fs.Close ();
276                                         }
277                                 } else {
278                                         results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
279                                         results.PathToAssembly = options.OutputAssembly;
280                                 }
281                         } else {
282                                 results.CompiledAssembly = null;
283                         }
284
285                         return results;
286                 }
287
288                 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
289                 {
290                         if (options == null) {
291                                 throw new ArgumentNullException ("options");
292                         }
293
294                         if (ea == null) {
295                                 throw new ArgumentNullException ("ea");
296                         }
297
298                         string[] fileNames = new string[ea.Length];
299                         StringCollection assemblies = options.ReferencedAssemblies;
300
301                         for (int i = 0; i < ea.Length; i++) {
302                                 CodeCompileUnit compileUnit = ea[i];
303                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
304                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
305                                 StreamWriter s = new StreamWriter (f);
306                                 if (compileUnit.ReferencedAssemblies != null) {
307                                         foreach (string str in compileUnit.ReferencedAssemblies) {
308                                                 if (!assemblies.Contains (str))
309                                                         assemblies.Add (str);
310                                         }
311                                 }
312
313                                 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
314                                 s.Close ();
315                                 f.Close ();
316                         }
317                         return CompileAssemblyFromFileBatch (options, fileNames);
318                 }
319
320                 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
321                 {
322                         if (options == null) {
323                                 throw new ArgumentNullException ("options");
324                         }
325
326                         if (sources == null) {
327                                 throw new ArgumentNullException ("sources");
328                         }
329
330                         string[] fileNames = new string[sources.Length];
331
332                         for (int i = 0; i < sources.Length; i++) {
333                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
334                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
335                                 using (StreamWriter s = new StreamWriter (f)) {
336                                         s.Write (sources[i]);
337                                         s.Close ();
338                                 }
339                                 f.Close ();
340                         }
341                         return CompileFromFileBatch (options, fileNames);
342                 }
343         }
344 }
345