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