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