A bug fix for 459450
[mono.git] / mcs / class / System / Microsoft.CSharp / CSharpCodeCompiler.cs
1 //
2 // Mono.CSharp CSharpCodeCompiler Class implementation
3 //
4 // Authors:
5 //      Sean Kasun (seank@users.sf.net)
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //
8 // Copyright (c) Novell, Inc. (http://www.novell.com)
9 //
10
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 namespace Mono.CSharp
33 {
34         using System;
35         using System.CodeDom;
36         using System.CodeDom.Compiler;
37         using System.IO;
38         using System.Text;
39         using System.Reflection;
40         using System.Collections;
41         using System.Collections.Specialized;
42         using System.Diagnostics;
43         using System.Text.RegularExpressions;
44         
45 #if NET_2_0
46         using System.Threading;
47         using System.Collections.Generic;
48 #endif
49         
50         internal class CSharpCodeCompiler : CSharpCodeGenerator, ICodeCompiler
51         {
52                 static string windowsMcsPath;
53                 static string windowsMonoPath;
54
55 #if NET_2_0
56                 Mutex mcsOutMutex;
57                 StringCollection mcsOutput;
58 #endif
59                 
60                 static CSharpCodeCompiler ()
61                 {
62                         if (Path.DirectorySeparatorChar == '\\') {
63                                 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
64                                 MethodInfo get_gac = gac.GetGetMethod (true);
65                                 string p = Path.GetDirectoryName (
66                                         (string) get_gac.Invoke (null, null));
67                                 windowsMonoPath = Path.Combine (
68                                         Path.GetDirectoryName (
69                                                 Path.GetDirectoryName (p)),
70                                         "bin\\mono.bat");
71                                 if (!File.Exists (windowsMonoPath))
72                                         windowsMonoPath = Path.Combine (
73                                                 Path.GetDirectoryName (
74                                                         Path.GetDirectoryName (p)),
75                                                 "bin\\mono.exe");
76                                 if (!File.Exists (windowsMonoPath))
77                                         windowsMonoPath = Path.Combine (
78                                                 Path.GetDirectoryName (
79                                                         Path.GetDirectoryName (
80                                                                 Path.GetDirectoryName (p))),
81                                                 "mono\\mono\\mini\\mono.exe");
82                                 if (!File.Exists (windowsMonoPath))
83                                         throw new FileNotFoundException ("Windows mono path not found: " + windowsMonoPath);
84 #if NET_2_0
85                                 windowsMcsPath =
86                                         Path.Combine (p, "2.0\\gmcs.exe");
87 #else
88                                 windowsMcsPath =
89                                         Path.Combine (p, "1.0\\mcs.exe");
90 #endif
91                                 if (!File.Exists (windowsMcsPath))
92 #if NET_2_0
93                                         windowsMcsPath = 
94                                                 Path.Combine(
95                                                         Path.GetDirectoryName (p),
96                                                         "lib\\net_2_0\\gmcs.exe");
97 #else
98                                         windowsMcsPath = 
99                                                 Path.Combine(
100                                                         Path.GetDirectoryName (p),
101                                                         "lib\\default\\mcs.exe");
102 #endif
103                                 if (!File.Exists (windowsMcsPath))
104                                         throw new FileNotFoundException ("Windows mcs path not found: " + windowsMcsPath);
105                         }
106                 }
107
108                 //
109                 // Constructors
110                 //
111                 public CSharpCodeCompiler()
112                 {
113                 }
114
115 #if NET_2_0
116                 public CSharpCodeCompiler (IDictionary <string, string> providerOptions) :
117                         base (providerOptions)
118                 {
119                 }
120 #endif
121                 
122                 //
123                 // Methods
124                 //
125                 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
126                 {
127                         return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
128                 }
129
130                 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
131                 {
132                         if (options == null) {
133                                 throw new ArgumentNullException ("options");
134                         }
135
136                         try {
137                                 return CompileFromDomBatch (options, ea);
138                         } finally {
139                                 options.TempFiles.Delete ();
140                         }
141                 }
142
143                 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
144                 {
145                         return CompileAssemblyFromFileBatch (options, new string[] { fileName });
146                 }
147
148                 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
149                 {
150                         if (options == null) {
151                                 throw new ArgumentNullException ("options");
152                         }
153
154                         try {
155                                 return CompileFromFileBatch (options, fileNames);
156                         } finally {
157                                 options.TempFiles.Delete ();
158                         }
159                 }
160
161                 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
162                 {
163                         return CompileAssemblyFromSourceBatch (options, new string[] { source });
164                 }
165
166                 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
167                 {
168                         if (options == null) {
169                                 throw new ArgumentNullException ("options");
170                         }
171
172                         try {
173                                 return CompileFromSourceBatch (options, sources);
174                         } finally {
175                                 options.TempFiles.Delete ();
176                         }
177                 }
178
179                 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
180                 {
181                         if (null == options)
182                                 throw new ArgumentNullException("options");
183                         if (null == fileNames)
184                                 throw new ArgumentNullException("fileNames");
185
186                         CompilerResults results=new CompilerResults(options.TempFiles);
187                         Process mcs=new Process();
188
189 #if !NET_2_0
190                         string mcs_output;
191                         string mcs_stdout;
192                         string[] mcsOutput;
193 #endif
194                         
195                         // FIXME: these lines had better be platform independent.
196                         if (Path.DirectorySeparatorChar == '\\') {
197                                 mcs.StartInfo.FileName = windowsMonoPath;
198                                 mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
199 #if NET_2_0
200                                         BuildArgs (options, fileNames, ProviderOptions);
201 #else
202                                         BuildArgs (options, fileNames);
203 #endif
204                         } else {
205 #if NET_2_0
206                                 // FIXME: This is a temporary hack to make code genaration work in 2.0
207                                 mcs.StartInfo.FileName="gmcs";
208                                 mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions);
209 #else
210                                 mcs.StartInfo.FileName="mcs";
211                                 mcs.StartInfo.Arguments=BuildArgs(options, fileNames);
212 #endif
213                         }
214
215 #if NET_2_0
216                         mcsOutput = new StringCollection ();
217                         mcsOutMutex = new Mutex ();
218 #endif
219                         
220                         mcs.StartInfo.CreateNoWindow=true;
221                         mcs.StartInfo.UseShellExecute=false;
222                         mcs.StartInfo.RedirectStandardOutput=true;
223                         mcs.StartInfo.RedirectStandardError=true;
224 #if NET_2_0
225                         mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
226 #endif
227                         
228                         try {
229                                 mcs.Start();
230
231 #if NET_2_0
232                                 mcs.BeginOutputReadLine ();
233                                 mcs.BeginErrorReadLine ();
234 #else
235                                 // If there are a few kB in stdout, we might lock
236                                 mcs_output=mcs.StandardError.ReadToEnd();
237                                 mcs_stdout=mcs.StandardOutput.ReadToEnd ();
238 #endif
239                                 mcs.WaitForExit();
240                                 
241                                 results.NativeCompilerReturnValue = mcs.ExitCode;
242                         } finally {
243 #if NET_2_0
244                                 mcs.CancelErrorRead ();
245                                 mcs.CancelOutputRead ();
246 #endif
247
248                                 mcs.Close();
249                         }
250
251 #if NET_2_0
252                         StringCollection sc = mcsOutput;
253 #else
254                         mcsOutput = mcs_output.Split (System.Environment.NewLine.ToCharArray ());
255                         StringCollection sc = new StringCollection ();
256 #endif
257                        
258                         bool loadIt=true;
259                         foreach (string error_line in mcsOutput) {
260 #if !NET_2_0
261                                 sc.Add (error_line);
262 #endif
263                                 CompilerError error = CreateErrorFromString (error_line);
264                                 if (error != null) {
265                                         results.Errors.Add (error);
266                                         if (!error.IsWarning)
267                                                 loadIt = false;
268                                 }
269                         }
270                         
271                         if (sc.Count > 0) {
272                                 sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
273                                 results.Output = sc;
274                         }
275
276                         if (loadIt) {
277                                 if (!File.Exists (options.OutputAssembly)) {
278                                         StringBuilder sb = new StringBuilder ();
279                                         foreach (string s in sc)
280                                                 sb.Append (s + Environment.NewLine);
281                                         
282                                         throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
283                                 }
284                                 
285                                 if (options.GenerateInMemory) {
286                                         using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
287                                                 byte[] buffer = new byte[fs.Length];
288                                                 fs.Read(buffer, 0, buffer.Length);
289                                                 results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
290                                                 fs.Close();
291                                         }
292                                 } else {
293                                         // Avoid setting CompiledAssembly right now since the output might be a netmodule
294                                         results.PathToAssembly = options.OutputAssembly;
295                                 }
296                         } else {
297                                 results.CompiledAssembly = null;
298                         }
299                         
300                         return results;
301                 }
302
303 #if NET_2_0
304                 void McsStderrDataReceived (object sender, DataReceivedEventArgs args)
305                 {
306                         if (args.Data != null) {
307                                 mcsOutMutex.WaitOne ();
308                                 mcsOutput.Add (args.Data);
309                                 mcsOutMutex.ReleaseMutex ();
310                         }
311                 }               
312
313                 private static string BuildArgs(CompilerParameters options,string[] fileNames, IDictionary <string, string> providerOptions)
314 #else
315                 private static string BuildArgs(CompilerParameters options,string[] fileNames)
316 #endif
317                 {
318                         StringBuilder args=new StringBuilder();
319                         if (options.GenerateExecutable)
320                                 args.Append("/target:exe ");
321                         else
322                                 args.Append("/target:library ");
323
324                         if (options.Win32Resource != null)
325                                 args.AppendFormat("/win32res:\"{0}\" ",
326                                         options.Win32Resource);
327
328                         if (options.IncludeDebugInformation)
329                                 args.Append("/debug+ /optimize- ");
330                         else
331                                 args.Append("/debug- /optimize+ ");
332
333                         if (options.TreatWarningsAsErrors)
334                                 args.Append("/warnaserror ");
335
336                         if (options.WarningLevel >= 0)
337                                 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
338
339                         if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
340                                 string extension = (options.GenerateExecutable ? "exe" : "dll");
341                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
342                                         !options.GenerateInMemory);
343                         }
344                         args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
345
346                         foreach (string import in options.ReferencedAssemblies) {
347                                 if (import == null || import.Length == 0)
348                                         continue;
349
350                                 args.AppendFormat("/r:\"{0}\" ",import);
351                         }
352
353                         if (options.CompilerOptions != null) {
354                                 args.Append (options.CompilerOptions);
355                                 args.Append (" ");
356                         }
357
358 #if NET_2_0
359                         foreach (string embeddedResource in options.EmbeddedResources) {
360                                 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
361                         }
362
363                         foreach (string linkedResource in options.LinkedResources) {
364                                 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
365                         }
366                         
367                         if (providerOptions != null && providerOptions.Count > 0) {
368                                 string langver;
369
370                                 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
371                                         langver = "2.0";
372
373                                 if (langver.Length >= 1 && langver [0] == 'v')
374                                         langver = langver.Substring (1);
375
376                                 switch (langver) {
377                                         case "2.0":
378                                                 args.Append ("/langversion:ISO-2");
379                                                 break;
380
381                                         case "3.5":
382                                                 // current default, omit the switch
383                                                 break;
384                                 }
385                         }
386 #endif
387
388                         args.Append (" -- ");
389                         foreach (string source in fileNames)
390                                 args.AppendFormat("\"{0}\" ",source);
391                         return args.ToString();
392                 }
393                 private static CompilerError CreateErrorFromString(string error_string)
394                 {
395 #if NET_2_0
396                         if (error_string.StartsWith ("BETA"))
397                                 return null;
398 #endif
399                         if (error_string == null || error_string == "")
400                                 return null;
401
402                         CompilerError error=new CompilerError();
403                         Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
404                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
405                         Match match=reg.Match(error_string);
406                         if (!match.Success) {
407                                 // We had some sort of runtime crash
408                                 error.ErrorText = error_string;
409                                 error.IsWarning = false;
410                                 error.ErrorNumber = "";
411                                 return error;
412                         }
413                         if (String.Empty != match.Result("${file}"))
414                                 error.FileName=match.Result("${file}");
415                         if (String.Empty != match.Result("${line}"))
416                                 error.Line=Int32.Parse(match.Result("${line}"));
417                         if (String.Empty != match.Result("${column}"))
418                                 error.Column=Int32.Parse(match.Result("${column}"));
419
420                         string level = match.Result ("${level}");
421                         if (level == "warning")
422                                 error.IsWarning = true;
423                         else if (level != "error")
424                                 return null; // error CS8028 will confuse the regex.
425
426                         error.ErrorNumber=match.Result("${number}");
427                         error.ErrorText=match.Result("${message}");
428                         return error;
429                 }
430
431                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
432                 {
433                         return temp_files.AddExtension (extension, keepFile);
434                 }
435
436                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
437                 {
438                         return temp_files.AddExtension (extension);
439                 }
440
441                 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
442                 {
443                         if (options == null) {
444                                 throw new ArgumentNullException ("options");
445                         }
446
447                         if (ea == null) {
448                                 throw new ArgumentNullException ("ea");
449                         }
450
451                         string[] fileNames = new string[ea.Length];
452                         StringCollection assemblies = options.ReferencedAssemblies;
453
454                         for (int i = 0; i < ea.Length; i++) {
455                                 CodeCompileUnit compileUnit = ea[i];
456                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
457                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
458                                 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
459                                 if (compileUnit.ReferencedAssemblies != null) {
460                                         foreach (string str in compileUnit.ReferencedAssemblies) {
461                                                 if (!assemblies.Contains (str))
462                                                         assemblies.Add (str);
463                                         }
464                                 }
465
466                                 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
467                                 s.Close ();
468                                 f.Close ();
469                         }
470                         return CompileAssemblyFromFileBatch (options, fileNames);
471                 }
472
473                 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
474                 {
475                         if (options == null) {
476                                 throw new ArgumentNullException ("options");
477                         }
478
479                         if (sources == null) {
480                                 throw new ArgumentNullException ("sources");
481                         }
482
483                         string[] fileNames = new string[sources.Length];
484
485                         for (int i = 0; i < sources.Length; i++) {
486                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
487                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
488                                 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
489                                         s.Write (sources[i]);
490                                         s.Close ();
491                                 }
492                                 f.Close ();
493                         }
494                         return CompileFromFileBatch (options, fileNames);
495                 }
496         }
497 }