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