2009-04-17 Marek Habersack <mhabersack@novell.com>
[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                         string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
221                         if (monoPath == null)
222                                 monoPath = String.Empty;
223                         
224                         string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
225                         if (privateBinPath != null && privateBinPath.Length > 0)
226                                 monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);
227
228                         if (monoPath.Length > 0) {
229                                 StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
230                                 if (dict.ContainsKey ("MONO_PATH"))
231                                         dict ["MONO_PATH"] = monoPath;
232                                 else
233                                         dict.Add ("MONO_PATH", monoPath);
234                         }
235                         
236                         mcs.StartInfo.CreateNoWindow=true;
237                         mcs.StartInfo.UseShellExecute=false;
238                         mcs.StartInfo.RedirectStandardOutput=true;
239                         mcs.StartInfo.RedirectStandardError=true;
240 #if NET_2_0
241                         mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
242 #endif
243                         
244                         try {
245                                 mcs.Start();
246
247 #if NET_2_0
248                                 mcs.BeginOutputReadLine ();
249                                 mcs.BeginErrorReadLine ();
250 #else
251                                 // If there are a few kB in stdout, we might lock
252                                 mcs_output=mcs.StandardError.ReadToEnd();
253                                 mcs_stdout=mcs.StandardOutput.ReadToEnd ();
254 #endif
255                                 mcs.WaitForExit();
256                                 
257                                 results.NativeCompilerReturnValue = mcs.ExitCode;
258                         } finally {
259 #if NET_2_0
260                                 mcs.CancelErrorRead ();
261                                 mcs.CancelOutputRead ();
262 #endif
263
264                                 mcs.Close();
265                         }
266
267 #if NET_2_0
268                         StringCollection sc = mcsOutput;
269 #else
270                         mcsOutput = mcs_output.Split (System.Environment.NewLine.ToCharArray ());
271                         StringCollection sc = new StringCollection ();
272 #endif
273                        
274                         bool loadIt=true;
275                         foreach (string error_line in mcsOutput) {
276 #if !NET_2_0
277                                 sc.Add (error_line);
278 #endif
279                                 CompilerError error = CreateErrorFromString (error_line);
280                                 if (error != null) {
281                                         results.Errors.Add (error);
282                                         if (!error.IsWarning)
283                                                 loadIt = false;
284                                 }
285                         }
286                         
287                         if (sc.Count > 0) {
288                                 sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
289                                 results.Output = sc;
290                         }
291
292                         if (loadIt) {
293                                 if (!File.Exists (options.OutputAssembly)) {
294                                         StringBuilder sb = new StringBuilder ();
295                                         foreach (string s in sc)
296                                                 sb.Append (s + Environment.NewLine);
297                                         
298                                         throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
299                                 }
300                                 
301                                 if (options.GenerateInMemory) {
302                                         using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
303                                                 byte[] buffer = new byte[fs.Length];
304                                                 fs.Read(buffer, 0, buffer.Length);
305                                                 results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
306                                                 fs.Close();
307                                         }
308                                 } else {
309                                         // Avoid setting CompiledAssembly right now since the output might be a netmodule
310                                         results.PathToAssembly = options.OutputAssembly;
311                                 }
312                         } else {
313                                 results.CompiledAssembly = null;
314                         }
315                         
316                         return results;
317                 }
318
319 #if NET_2_0
320                 void McsStderrDataReceived (object sender, DataReceivedEventArgs args)
321                 {
322                         if (args.Data != null) {
323                                 mcsOutMutex.WaitOne ();
324                                 mcsOutput.Add (args.Data);
325                                 mcsOutMutex.ReleaseMutex ();
326                         }
327                 }               
328
329                 private static string BuildArgs(CompilerParameters options,string[] fileNames, IDictionary <string, string> providerOptions)
330 #else
331                 private static string BuildArgs(CompilerParameters options,string[] fileNames)
332 #endif
333                 {
334                         StringBuilder args=new StringBuilder();
335                         if (options.GenerateExecutable)
336                                 args.Append("/target:exe ");
337                         else
338                                 args.Append("/target:library ");
339
340                         string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
341                         if (privateBinPath != null && privateBinPath.Length > 0)
342                                 args.AppendFormat ("/lib:\"{0}\" ", privateBinPath);
343                         
344                         if (options.Win32Resource != null)
345                                 args.AppendFormat("/win32res:\"{0}\" ",
346                                         options.Win32Resource);
347
348                         if (options.IncludeDebugInformation)
349                                 args.Append("/debug+ /optimize- ");
350                         else
351                                 args.Append("/debug- /optimize+ ");
352
353                         if (options.TreatWarningsAsErrors)
354                                 args.Append("/warnaserror ");
355
356                         if (options.WarningLevel >= 0)
357                                 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
358
359                         if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
360                                 string extension = (options.GenerateExecutable ? "exe" : "dll");
361                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
362                                         !options.GenerateInMemory);
363                         }
364                         args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
365
366                         foreach (string import in options.ReferencedAssemblies) {
367                                 if (import == null || import.Length == 0)
368                                         continue;
369
370                                 args.AppendFormat("/r:\"{0}\" ",import);
371                         }
372
373                         if (options.CompilerOptions != null) {
374                                 args.Append (options.CompilerOptions);
375                                 args.Append (" ");
376                         }
377
378 #if NET_2_0
379                         foreach (string embeddedResource in options.EmbeddedResources) {
380                                 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
381                         }
382
383                         foreach (string linkedResource in options.LinkedResources) {
384                                 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
385                         }
386                         
387                         if (providerOptions != null && providerOptions.Count > 0) {
388                                 string langver;
389
390                                 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
391                                         langver = "2.0";
392
393                                 if (langver.Length >= 1 && langver [0] == 'v')
394                                         langver = langver.Substring (1);
395
396                                 switch (langver) {
397                                         case "2.0":
398                                                 args.Append ("/langversion:ISO-2");
399                                                 break;
400
401                                         case "3.5":
402                                                 // current default, omit the switch
403                                                 break;
404                                 }
405                         }
406 #endif
407
408                         args.Append (" -- ");
409                         foreach (string source in fileNames)
410                                 args.AppendFormat("\"{0}\" ",source);
411                         return args.ToString();
412                 }
413                 private static CompilerError CreateErrorFromString(string error_string)
414                 {
415 #if NET_2_0
416                         if (error_string.StartsWith ("BETA"))
417                                 return null;
418 #endif
419                         if (error_string == null || error_string == "")
420                                 return null;
421
422                         CompilerError error=new CompilerError();
423                         Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
424                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
425                         Match match=reg.Match(error_string);
426                         if (!match.Success) {
427                                 // We had some sort of runtime crash
428                                 error.ErrorText = error_string;
429                                 error.IsWarning = false;
430                                 error.ErrorNumber = "";
431                                 return error;
432                         }
433                         if (String.Empty != match.Result("${file}"))
434                                 error.FileName=match.Result("${file}");
435                         if (String.Empty != match.Result("${line}"))
436                                 error.Line=Int32.Parse(match.Result("${line}"));
437                         if (String.Empty != match.Result("${column}"))
438                                 error.Column=Int32.Parse(match.Result("${column}"));
439
440                         string level = match.Result ("${level}");
441                         if (level == "warning")
442                                 error.IsWarning = true;
443                         else if (level != "error")
444                                 return null; // error CS8028 will confuse the regex.
445
446                         error.ErrorNumber=match.Result("${number}");
447                         error.ErrorText=match.Result("${message}");
448                         return error;
449                 }
450
451                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
452                 {
453                         return temp_files.AddExtension (extension, keepFile);
454                 }
455
456                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
457                 {
458                         return temp_files.AddExtension (extension);
459                 }
460
461                 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
462                 {
463                         if (options == null) {
464                                 throw new ArgumentNullException ("options");
465                         }
466
467                         if (ea == null) {
468                                 throw new ArgumentNullException ("ea");
469                         }
470
471                         string[] fileNames = new string[ea.Length];
472                         StringCollection assemblies = options.ReferencedAssemblies;
473
474                         for (int i = 0; i < ea.Length; i++) {
475                                 CodeCompileUnit compileUnit = ea[i];
476                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
477                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
478                                 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
479                                 if (compileUnit.ReferencedAssemblies != null) {
480                                         foreach (string str in compileUnit.ReferencedAssemblies) {
481                                                 if (!assemblies.Contains (str))
482                                                         assemblies.Add (str);
483                                         }
484                                 }
485
486                                 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
487                                 s.Close ();
488                                 f.Close ();
489                         }
490                         return CompileAssemblyFromFileBatch (options, fileNames);
491                 }
492
493                 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
494                 {
495                         if (options == null) {
496                                 throw new ArgumentNullException ("options");
497                         }
498
499                         if (sources == null) {
500                                 throw new ArgumentNullException ("sources");
501                         }
502
503                         string[] fileNames = new string[sources.Length];
504
505                         for (int i = 0; i < sources.Length; i++) {
506                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
507                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
508                                 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
509                                         s.Write (sources[i]);
510                                         s.Close ();
511                                 }
512                                 f.Close ();
513                         }
514                         return CompileFromFileBatch (options, fileNames);
515                 }
516         }
517 }