Switch to compiler-tester
[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                                 // FIXME: right now we use "fixed" version 1.0
56                                 // mcs at any time.
57                                 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
58                                 MethodInfo get_gac = gac.GetGetMethod (true);
59                                 string p = Path.GetDirectoryName (
60                                         (string) get_gac.Invoke (null, null));
61                                 windowsMonoPath = Path.Combine (
62                                         Path.GetDirectoryName (
63                                                 Path.GetDirectoryName (p)),
64                                         "bin\\mono.bat");
65                                 if (!File.Exists (windowsMonoPath))
66                                         windowsMonoPath = Path.Combine (
67                                                 Path.GetDirectoryName (
68                                                         Path.GetDirectoryName (p)),
69                                                 "bin\\mono.exe");
70                                 windowsMbasPath =
71                                         Path.Combine (p, "1.0\\mbas.exe");
72                         }
73                 }
74
75                 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
76                 {
77                         return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
78                 }
79
80                 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
81                 {
82                         if (options == null) {
83                                 throw new ArgumentNullException ("options");
84                         }
85
86                         try {
87                                 return CompileFromDomBatch (options, ea);
88                         } finally {
89                                 options.TempFiles.Delete ();
90                         }
91                 }
92
93                 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
94                 {
95                         return CompileAssemblyFromFileBatch (options, new string[] { fileName });
96                 }
97
98                 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
99                 {
100                         if (options == null) {
101                                 throw new ArgumentNullException ("options");
102                         }
103
104                         try {
105                                 return CompileFromFileBatch (options, fileNames);
106                         } finally {
107                                 options.TempFiles.Delete ();
108                         }
109                 }
110
111                 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
112                 {
113                         return CompileAssemblyFromSourceBatch (options, new string[] { source });
114                 }
115
116                 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
117                 {
118                         if (options == null) {
119                                 throw new ArgumentNullException ("options");
120                         }
121
122                         try {
123                                 return CompileFromSourceBatch (options, sources);
124                         } finally {
125                                 options.TempFiles.Delete ();
126                         }
127                 }
128
129                 static string BuildArgs (CompilerParameters options, string[] fileNames)
130                 {
131                         StringBuilder args = new StringBuilder ();
132                         args.AppendFormat ("/quiet ");
133                         if (options.GenerateExecutable)
134                                 args.AppendFormat ("/target:exe ");
135                         else
136                                 args.AppendFormat ("/target:library ");
137
138                         /* Disabled. It causes problems now. -- Gonzalo
139                         if (options.IncludeDebugInformation)
140                                 args.AppendFormat("/debug ");
141                         */
142
143                         if (options.TreatWarningsAsErrors)
144                                 args.AppendFormat ("/warnaserror ");
145
146                         if (options.WarningLevel != -1)
147                                 args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
148
149                         if (options.OutputAssembly == null) {
150                                 string ext = (options.GenerateExecutable ? "exe" : "dll");
151                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext, !options.GenerateInMemory);
152                         }
153
154                         args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
155
156                         bool Reference2MSVBFound;
157                         Reference2MSVBFound = false;
158                         if (null != options.ReferencedAssemblies) {
159                                 foreach (string import in options.ReferencedAssemblies) {
160                                         if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
161                                                 Reference2MSVBFound = true;
162                                         args.AppendFormat ("/r:\"{0}\" ", import);
163                                 }
164                         }
165                         // add standard import to Microsoft.VisualBasic if missing
166                         if (!Reference2MSVBFound)
167                                 args.AppendFormat ("/r:\"{0}\" ", "Microsoft.VisualBasic");
168
169                         args.AppendFormat (" -- "); // makes mbas not try to process filenames as options
170
171                         foreach (string source in fileNames)
172                                 args.AppendFormat ("\"{0}\" ", source);
173
174                         return args.ToString ();
175                 }
176
177                 static CompilerError CreateErrorFromString (string error_string)
178                 {
179                         // When IncludeDebugInformation is true, prevents the debug symbols stats from braeking this.
180                         if (error_string.StartsWith ("WROTE SYMFILE") || error_string.StartsWith ("OffsetTable"))
181                                 return null;
182
183                         CompilerError error = new CompilerError ();
184                         Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)\s+)*" +
185                                                 @"(?<level>error|warning)\s*(?<number>.*):\s(?<message>.*)",
186                                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
187
188                         Match match = reg.Match (error_string);
189                         if (!match.Success)
190                                 return null;
191
192                         if (String.Empty != match.Result ("${file}"))
193                                 error.FileName = match.Result ("${file}");
194
195                         if (String.Empty != match.Result ("${line}"))
196                                 error.Line = Int32.Parse (match.Result ("${line}"));
197
198                         if (String.Empty != match.Result ("${column}"))
199                                 error.Column = Int32.Parse (match.Result ("${column}"));
200
201                         if (match.Result ("${level}") == "warning")
202                                 error.IsWarning = true;
203
204                         error.ErrorNumber = match.Result ("${number}");
205                         error.ErrorText = match.Result ("${message}");
206                         return error;
207                 }
208
209                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
210                 {
211                         return temp_files.AddExtension (extension, keepFile);
212                 }
213
214                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
215                 {
216                         return temp_files.AddExtension (extension);
217                 }
218
219                 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
220                 {
221                         if (options == null) {
222                                 throw new ArgumentNullException ("options");
223                         }
224
225                         if (fileNames == null) {
226                                 throw new ArgumentNullException ("fileNames");
227                         }
228
229                         CompilerResults results = new CompilerResults (options.TempFiles);
230                         Process mbas = new Process ();
231
232                         string mbas_output;
233                         string[] mbas_output_lines;
234                         // FIXME: these lines had better be platform independent.
235                         if (Path.DirectorySeparatorChar == '\\') {
236                                 mbas.StartInfo.FileName = windowsMonoPath;
237                                 mbas.StartInfo.Arguments = windowsMbasPath + ' ' + BuildArgs (options, fileNames);
238                         } else {
239                                 mbas.StartInfo.FileName = "mbas";
240                                 mbas.StartInfo.Arguments = BuildArgs (options, fileNames);
241                         }
242                         mbas.StartInfo.CreateNoWindow = true;
243                         mbas.StartInfo.UseShellExecute = false;
244                         mbas.StartInfo.RedirectStandardOutput = true;
245                         try {
246                                 mbas.Start ();
247                                 mbas_output = mbas.StandardOutput.ReadToEnd ();
248                                 mbas.WaitForExit ();
249                         } finally {
250                                 results.NativeCompilerReturnValue = mbas.ExitCode;
251                                 mbas.Close ();
252                         }
253
254                         mbas_output_lines = mbas_output.Split (Environment.NewLine.ToCharArray ());
255                         bool loadIt = true;
256                         foreach (string error_line in mbas_output_lines) {
257                                 CompilerError error = CreateErrorFromString (error_line);
258                                 if (null != error) {
259                                         results.Errors.Add (error);
260                                         if (!error.IsWarning)
261                                                 loadIt = false;
262                                 }
263                         }
264
265                         if (loadIt) {
266                                 if (options.GenerateInMemory) {
267                                         using (FileStream fs = File.OpenRead (options.OutputAssembly)) {
268                                                 byte[] buffer = new byte[fs.Length];
269                                                 fs.Read (buffer, 0, buffer.Length);
270                                                 results.CompiledAssembly = Assembly.Load (buffer, null, options.Evidence);
271                                                 fs.Close ();
272                                         }
273                                 } else {
274                                         results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
275                                         results.PathToAssembly = options.OutputAssembly;
276                                 }
277                         } else {
278                                 results.CompiledAssembly = null;
279                         }
280
281                         return results;
282                 }
283
284                 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
285                 {
286                         if (options == null) {
287                                 throw new ArgumentNullException ("options");
288                         }
289
290                         if (ea == null) {
291                                 throw new ArgumentNullException ("ea");
292                         }
293
294                         string[] fileNames = new string[ea.Length];
295                         StringCollection assemblies = options.ReferencedAssemblies;
296
297                         for (int i = 0; i < ea.Length; i++) {
298                                 CodeCompileUnit compileUnit = ea[i];
299                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
300                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
301                                 StreamWriter s = new StreamWriter (f);
302                                 if (compileUnit.ReferencedAssemblies != null) {
303                                         foreach (string str in compileUnit.ReferencedAssemblies) {
304                                                 if (!assemblies.Contains (str))
305                                                         assemblies.Add (str);
306                                         }
307                                 }
308
309                                 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
310                                 s.Close ();
311                                 f.Close ();
312                         }
313                         return CompileAssemblyFromFileBatch (options, fileNames);
314                 }
315
316                 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
317                 {
318                         if (options == null) {
319                                 throw new ArgumentNullException ("options");
320                         }
321
322                         if (sources == null) {
323                                 throw new ArgumentNullException ("sources");
324                         }
325
326                         string[] fileNames = new string[sources.Length];
327
328                         for (int i = 0; i < sources.Length; i++) {
329                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
330                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
331                                 using (StreamWriter s = new StreamWriter (f)) {
332                                         s.Write (sources[i]);
333                                         s.Close ();
334                                 }
335                                 f.Close ();
336                         }
337                         return CompileFromFileBatch (options, fileNames);
338                 }
339         }
340 }
341