2008-06-05 Atsushi Enomoto <atsushi@ximian.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 (Dictionary <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                         mcsOutMutex.WaitOne ();
307                         mcsOutput.Add (args.Data);
308                         mcsOutMutex.ReleaseMutex ();
309                 }               
310
311                 private static string BuildArgs(CompilerParameters options,string[] fileNames, Dictionary <string, string> providerOptions)
312 #else
313                 private static string BuildArgs(CompilerParameters options,string[] fileNames)
314 #endif
315                 {
316                         StringBuilder args=new StringBuilder();
317                         if (options.GenerateExecutable)
318                                 args.Append("/target:exe ");
319                         else
320                                 args.Append("/target:library ");
321
322                         if (options.Win32Resource != null)
323                                 args.AppendFormat("/win32res:\"{0}\" ",
324                                         options.Win32Resource);
325
326                         if (options.IncludeDebugInformation)
327                                 args.Append("/debug+ /optimize- ");
328                         else
329                                 args.Append("/debug- /optimize+ ");
330
331                         if (options.TreatWarningsAsErrors)
332                                 args.Append("/warnaserror ");
333
334                         if (options.WarningLevel >= 0)
335                                 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
336
337                         if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
338                                 string extension = (options.GenerateExecutable ? "exe" : "dll");
339                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
340                                         !options.GenerateInMemory);
341                         }
342                         args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
343
344                         foreach (string import in options.ReferencedAssemblies) {
345                                 if (import == null || import.Length == 0)
346                                         continue;
347
348                                 args.AppendFormat("/r:\"{0}\" ",import);
349                         }
350
351                         if (options.CompilerOptions != null) {
352                                 args.Append (options.CompilerOptions);
353                                 args.Append (" ");
354                         }
355
356 #if NET_2_0
357                         foreach (string embeddedResource in options.EmbeddedResources) {
358                                 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
359                         }
360
361                         foreach (string linkedResource in options.LinkedResources) {
362                                 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
363                         }
364                         
365                         if (providerOptions != null && providerOptions.Count > 0) {
366                                 string langver;
367
368                                 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
369                                         langver = "2.0";
370
371                                 if (langver.Length >= 1 && langver [0] == 'v')
372                                         langver = langver.Substring (1);
373
374                                 switch (langver) {
375                                         case "2.0":
376                                                 args.Append ("/langversion:ISO-2");
377                                                 break;
378
379                                         case "3.5":
380                                                 // current default, omit the switch
381                                                 break;
382                                 }
383                         }
384 #endif
385
386                         args.Append (" -- ");
387                         foreach (string source in fileNames)
388                                 args.AppendFormat("\"{0}\" ",source);
389                         return args.ToString();
390                 }
391                 private static CompilerError CreateErrorFromString(string error_string)
392                 {
393 #if NET_2_0
394                         if (error_string.StartsWith ("BETA"))
395                                 return null;
396 #endif
397                         if (error_string == null || error_string == "")
398                                 return null;
399
400                         CompilerError error=new CompilerError();
401                         Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
402                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
403                         Match match=reg.Match(error_string);
404                         if (!match.Success) {
405                                 // We had some sort of runtime crash
406                                 error.ErrorText = error_string;
407                                 error.IsWarning = false;
408                                 error.ErrorNumber = "";
409                                 return error;
410                         }
411                         if (String.Empty != match.Result("${file}"))
412                                 error.FileName=match.Result("${file}");
413                         if (String.Empty != match.Result("${line}"))
414                                 error.Line=Int32.Parse(match.Result("${line}"));
415                         if (String.Empty != match.Result("${column}"))
416                                 error.Column=Int32.Parse(match.Result("${column}"));
417
418                         string level = match.Result ("${level}");
419                         if (level == "warning")
420                                 error.IsWarning = true;
421                         else if (level != "error")
422                                 return null; // error CS8028 will confuse the regex.
423
424                         error.ErrorNumber=match.Result("${number}");
425                         error.ErrorText=match.Result("${message}");
426                         return error;
427                 }
428
429                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
430                 {
431                         return temp_files.AddExtension (extension, keepFile);
432                 }
433
434                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
435                 {
436                         return temp_files.AddExtension (extension);
437                 }
438
439                 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
440                 {
441                         if (options == null) {
442                                 throw new ArgumentNullException ("options");
443                         }
444
445                         if (ea == null) {
446                                 throw new ArgumentNullException ("ea");
447                         }
448
449                         string[] fileNames = new string[ea.Length];
450                         StringCollection assemblies = options.ReferencedAssemblies;
451
452                         for (int i = 0; i < ea.Length; i++) {
453                                 CodeCompileUnit compileUnit = ea[i];
454                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
455                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
456                                 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
457                                 if (compileUnit.ReferencedAssemblies != null) {
458                                         foreach (string str in compileUnit.ReferencedAssemblies) {
459                                                 if (!assemblies.Contains (str))
460                                                         assemblies.Add (str);
461                                         }
462                                 }
463
464                                 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
465                                 s.Close ();
466                                 f.Close ();
467                         }
468                         return CompileAssemblyFromFileBatch (options, fileNames);
469                 }
470
471                 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
472                 {
473                         if (options == null) {
474                                 throw new ArgumentNullException ("options");
475                         }
476
477                         if (sources == null) {
478                                 throw new ArgumentNullException ("sources");
479                         }
480
481                         string[] fileNames = new string[sources.Length];
482
483                         for (int i = 0; i < sources.Length; i++) {
484                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
485                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
486                                 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
487                                         s.Write (sources[i]);
488                                         s.Close ();
489                                 }
490                                 f.Close ();
491                         }
492                         return CompileFromFileBatch (options, fileNames);
493                 }
494         }
495 }