Merge branch 'bugfix-main-thread-root'
[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.ComponentModel;
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         using System.Threading;
46         using System.Collections.Generic;
47         
48         internal class CSharpCodeCompiler : CSharpCodeGenerator, ICodeCompiler
49         {
50                 static string windowsMcsPath;
51                 static string windowsMonoPath;
52
53                 Mutex mcsOutMutex;
54                 StringCollection mcsOutput;
55                 
56                 static CSharpCodeCompiler ()
57                 {
58                         if (Path.DirectorySeparatorChar == '\\') {
59                                 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
60                                 MethodInfo get_gac = gac.GetGetMethod (true);
61                                 string p = Path.GetDirectoryName (
62                                         (string) get_gac.Invoke (null, null));
63                                 windowsMonoPath = Path.Combine (
64                                         Path.GetDirectoryName (
65                                                 Path.GetDirectoryName (p)),
66                                         "bin\\mono.bat");
67                                 if (!File.Exists (windowsMonoPath))
68                                         windowsMonoPath = Path.Combine (
69                                                 Path.GetDirectoryName (
70                                                         Path.GetDirectoryName (p)),
71                                                 "bin\\mono.exe");
72                                 if (!File.Exists (windowsMonoPath))
73                                         windowsMonoPath = Path.Combine (
74                                                 Path.GetDirectoryName (
75                                                         Path.GetDirectoryName (
76                                                                 Path.GetDirectoryName (p))),
77                                                 "mono\\mono\\mini\\mono.exe");
78                                 if (!File.Exists (windowsMonoPath))
79                                         throw new FileNotFoundException ("Windows mono path not found: " + windowsMonoPath);
80
81                                 windowsMcsPath = Path.Combine (p, "2.0\\mcs.exe");
82                                 if (!File.Exists (windowsMcsPath))
83                                         windowsMcsPath = Path.Combine(Path.GetDirectoryName (p), "lib\\basic\\mcs.exe");
84                                 
85                                 if (!File.Exists (windowsMcsPath))
86                                         throw new FileNotFoundException ("Windows mcs path not found: " + windowsMcsPath);
87                         }
88                 }
89
90                 //
91                 // Constructors
92                 //
93                 public CSharpCodeCompiler()
94                 {
95                 }
96
97                 public CSharpCodeCompiler (IDictionary <string, string> providerOptions) :
98                         base (providerOptions)
99                 {
100                 }
101                 
102                 //
103                 // Methods
104                 //
105                 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
106                 {
107                         return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
108                 }
109
110                 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
111                 {
112                         if (options == null) {
113                                 throw new ArgumentNullException ("options");
114                         }
115
116                         try {
117                                 return CompileFromDomBatch (options, ea);
118                         } finally {
119                                 options.TempFiles.Delete ();
120                         }
121                 }
122
123                 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
124                 {
125                         return CompileAssemblyFromFileBatch (options, new string[] { fileName });
126                 }
127
128                 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
129                 {
130                         if (options == null) {
131                                 throw new ArgumentNullException ("options");
132                         }
133
134                         try {
135                                 return CompileFromFileBatch (options, fileNames);
136                         } finally {
137                                 options.TempFiles.Delete ();
138                         }
139                 }
140
141                 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
142                 {
143                         return CompileAssemblyFromSourceBatch (options, new string[] { source });
144                 }
145
146                 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
147                 {
148                         if (options == null) {
149                                 throw new ArgumentNullException ("options");
150                         }
151
152                         try {
153                                 return CompileFromSourceBatch (options, sources);
154                         } finally {
155                                 options.TempFiles.Delete ();
156                         }
157                 }
158
159                 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
160                 {
161                         if (null == options)
162                                 throw new ArgumentNullException("options");
163                         if (null == fileNames)
164                                 throw new ArgumentNullException("fileNames");
165
166                         CompilerResults results=new CompilerResults(options.TempFiles);
167                         Process mcs=new Process();
168
169                         // FIXME: these lines had better be platform independent.
170                         if (Path.DirectorySeparatorChar == '\\') {
171                                 mcs.StartInfo.FileName = windowsMonoPath;
172                                 mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
173                                         BuildArgs (options, fileNames, ProviderOptions);
174                         } else {
175                                 mcs.StartInfo.FileName="mcs";
176                                 mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions);
177                         }
178
179                         mcsOutput = new StringCollection ();
180                         mcsOutMutex = new Mutex ();
181
182                         string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
183                         if (monoPath == null)
184                                 monoPath = String.Empty;
185                         
186                         string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
187                         if (privateBinPath != null && privateBinPath.Length > 0)
188                                 monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);
189
190                         if (monoPath.Length > 0) {
191                                 StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
192                                 if (dict.ContainsKey ("MONO_PATH"))
193                                         dict ["MONO_PATH"] = monoPath;
194                                 else
195                                         dict.Add ("MONO_PATH", monoPath);
196                         }
197                         
198                         mcs.StartInfo.CreateNoWindow=true;
199                         mcs.StartInfo.UseShellExecute=false;
200                         mcs.StartInfo.RedirectStandardOutput=true;
201                         mcs.StartInfo.RedirectStandardError=true;
202                         mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
203                         
204                         try {
205                                 mcs.Start();
206                         } catch (Exception e) {
207                                 Win32Exception exc = e as Win32Exception;
208                                 if (exc != null) {
209                                         throw new SystemException (String.Format ("Error running {0}: {1}", mcs.StartInfo.FileName,
210                                                                         Win32Exception.W32ErrorMessage (exc.NativeErrorCode)));
211                                 }
212                                 throw;
213                         }
214
215                         try {
216                                 mcs.BeginOutputReadLine ();
217                                 mcs.BeginErrorReadLine ();
218                                 mcs.WaitForExit();
219                                 
220                                 results.NativeCompilerReturnValue = mcs.ExitCode;
221                         } finally {
222                                 mcs.CancelErrorRead ();
223                                 mcs.CancelOutputRead ();
224                                 mcs.Close();
225                         }
226
227                         StringCollection sc = mcsOutput;
228                        
229                         bool loadIt=true;
230                         foreach (string error_line in mcsOutput) {
231                                 CompilerError error = CreateErrorFromString (error_line);
232                                 if (error != null) {
233                                         results.Errors.Add (error);
234                                         if (!error.IsWarning)
235                                                 loadIt = false;
236                                 }
237                         }
238                         
239                         if (sc.Count > 0) {
240                                 sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
241                                 results.Output = sc;
242                         }
243
244                         if (loadIt) {
245                                 if (!File.Exists (options.OutputAssembly)) {
246                                         StringBuilder sb = new StringBuilder ();
247                                         foreach (string s in sc)
248                                                 sb.Append (s + Environment.NewLine);
249                                         
250                                         throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
251                                 }
252                                 
253                                 if (options.GenerateInMemory) {
254                                         using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
255                                                 byte[] buffer = new byte[fs.Length];
256                                                 fs.Read(buffer, 0, buffer.Length);
257                                                 results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
258                                                 fs.Close();
259                                         }
260                                 } else {
261                                         // Avoid setting CompiledAssembly right now since the output might be a netmodule
262                                         results.PathToAssembly = options.OutputAssembly;
263                                 }
264                         } else {
265                                 results.CompiledAssembly = null;
266                         }
267                         
268                         return results;
269                 }
270
271                 void McsStderrDataReceived (object sender, DataReceivedEventArgs args)
272                 {
273                         if (args.Data != null) {
274                                 mcsOutMutex.WaitOne ();
275                                 mcsOutput.Add (args.Data);
276                                 mcsOutMutex.ReleaseMutex ();
277                         }
278                 }               
279
280                 private static string BuildArgs(CompilerParameters options,string[] fileNames, IDictionary <string, string> providerOptions)
281                 {
282                         StringBuilder args=new StringBuilder();
283                         if (options.GenerateExecutable)
284                                 args.Append("/target:exe ");
285                         else
286                                 args.Append("/target:library ");
287
288                         string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
289                         if (privateBinPath != null && privateBinPath.Length > 0)
290                                 args.AppendFormat ("/lib:\"{0}\" ", privateBinPath);
291                         
292                         if (options.Win32Resource != null)
293                                 args.AppendFormat("/win32res:\"{0}\" ",
294                                         options.Win32Resource);
295
296                         if (options.IncludeDebugInformation)
297                                 args.Append("/debug+ /optimize- ");
298                         else
299                                 args.Append("/debug- /optimize+ ");
300
301                         if (options.TreatWarningsAsErrors)
302                                 args.Append("/warnaserror ");
303
304                         if (options.WarningLevel >= 0)
305                                 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
306
307                         if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
308                                 string extension = (options.GenerateExecutable ? "exe" : "dll");
309                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
310                                         !options.GenerateInMemory);
311                         }
312                         args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
313
314                         foreach (string import in options.ReferencedAssemblies) {
315                                 if (import == null || import.Length == 0)
316                                         continue;
317
318                                 args.AppendFormat("/r:\"{0}\" ",import);
319                         }
320
321                         if (options.CompilerOptions != null) {
322                                 args.Append (options.CompilerOptions);
323                                 args.Append (" ");
324                         }
325
326                         foreach (string embeddedResource in options.EmbeddedResources) {
327                                 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
328                         }
329
330                         foreach (string linkedResource in options.LinkedResources) {
331                                 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
332                         }
333                         
334                         if (providerOptions != null && providerOptions.Count > 0) {
335                                 string langver;
336
337                                 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
338 #if NET_4_0
339                                         langver = "3.5";
340 #else
341                                         langver = "2.0";
342 #endif
343
344                                 if (langver.Length >= 1 && langver [0] == 'v')
345                                         langver = langver.Substring (1);
346
347                                 switch (langver) {
348                                         case "2.0":
349                                                 args.Append ("/langversion:ISO-2 ");
350                                                 break;
351
352                                         case "3.5":
353                                                 // current default, omit the switch
354                                                 break;
355                                 }
356                         }
357                         
358 #if NET_4_0
359                         args.Append("/sdk:4");
360 #else
361                         args.Append("/sdk:2");
362 #endif
363
364                         args.Append (" -- ");
365                         foreach (string source in fileNames)
366                                 args.AppendFormat("\"{0}\" ",source);
367                         return args.ToString();
368                 }
369                 private static CompilerError CreateErrorFromString(string error_string)
370                 {
371                         if (error_string.StartsWith ("BETA"))
372                                 return null;
373
374                         if (error_string == null || error_string == "")
375                                 return null;
376
377                         CompilerError error=new CompilerError();
378                         Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
379                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
380                         Match match=reg.Match(error_string);
381                         if (!match.Success) {
382                                 // We had some sort of runtime crash
383                                 error.ErrorText = error_string;
384                                 error.IsWarning = false;
385                                 error.ErrorNumber = "";
386                                 return error;
387                         }
388                         if (String.Empty != match.Result("${file}"))
389                                 error.FileName=match.Result("${file}");
390                         if (String.Empty != match.Result("${line}"))
391                                 error.Line=Int32.Parse(match.Result("${line}"));
392                         if (String.Empty != match.Result("${column}"))
393                                 error.Column=Int32.Parse(match.Result("${column}"));
394
395                         string level = match.Result ("${level}");
396                         if (level == "warning")
397                                 error.IsWarning = true;
398                         else if (level != "error")
399                                 return null; // error CS8028 will confuse the regex.
400
401                         error.ErrorNumber=match.Result("${number}");
402                         error.ErrorText=match.Result("${message}");
403                         return error;
404                 }
405
406                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
407                 {
408                         return temp_files.AddExtension (extension, keepFile);
409                 }
410
411                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
412                 {
413                         return temp_files.AddExtension (extension);
414                 }
415
416                 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
417                 {
418                         if (options == null) {
419                                 throw new ArgumentNullException ("options");
420                         }
421
422                         if (ea == null) {
423                                 throw new ArgumentNullException ("ea");
424                         }
425
426                         string[] fileNames = new string[ea.Length];
427                         StringCollection assemblies = options.ReferencedAssemblies;
428
429                         for (int i = 0; i < ea.Length; i++) {
430                                 CodeCompileUnit compileUnit = ea[i];
431                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
432                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
433                                 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
434                                 if (compileUnit.ReferencedAssemblies != null) {
435                                         foreach (string str in compileUnit.ReferencedAssemblies) {
436                                                 if (!assemblies.Contains (str))
437                                                         assemblies.Add (str);
438                                         }
439                                 }
440
441                                 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
442                                 s.Close ();
443                                 f.Close ();
444                         }
445                         return CompileAssemblyFromFileBatch (options, fileNames);
446                 }
447
448                 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
449                 {
450                         if (options == null) {
451                                 throw new ArgumentNullException ("options");
452                         }
453
454                         if (sources == null) {
455                                 throw new ArgumentNullException ("sources");
456                         }
457
458                         string[] fileNames = new string[sources.Length];
459
460                         for (int i = 0; i < sources.Length; i++) {
461                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
462                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
463                                 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
464                                         s.Write (sources[i]);
465                                         s.Close ();
466                                 }
467                                 f.Close ();
468                         }
469                         return CompileFromFileBatch (options, fileNames);
470                 }
471         }
472 }