for TARGET_J2EE only:
[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                         try {
210                                 mcs.Start();
211                                 // If there are a few kB in stdout, we might lock
212                                 mcs_output=mcs.StandardError.ReadToEnd();
213                                 mcs_stdout=mcs.StandardOutput.ReadToEnd ();
214                                 mcs.WaitForExit();
215                                 results.NativeCompilerReturnValue = mcs.ExitCode;
216                         } finally {
217                                 mcs.Close();
218                         }
219                         mcs_output_lines=mcs_output.Split(
220                                 System.Environment.NewLine.ToCharArray());
221                         bool loadIt=true;
222                         foreach (string error_line in mcs_output_lines)
223                         {
224                                 CompilerError error=CreateErrorFromString(error_line);
225                                 if (null!=error)
226                                 {
227                                         results.Errors.Add(error);
228                                         if (!error.IsWarning) loadIt=false;
229                                 }
230                         }
231                         if (loadIt) {
232                                 if (!File.Exists (options.OutputAssembly)) {
233                                         throw new Exception ("Compiler failed to produce the assembly. Stderr='"
234                                                 +mcs_output+"', Stdout='"+mcs_stdout+"'");
235                                 }
236                                 if (options.GenerateInMemory) {
237                                         using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
238                                                 byte[] buffer = new byte[fs.Length];
239                                                 fs.Read(buffer, 0, buffer.Length);
240                                                 results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
241                                                 fs.Close();
242                                         }
243                                 } else {
244                                         results.CompiledAssembly = Assembly.LoadFrom(options.OutputAssembly);
245                                         results.PathToAssembly = options.OutputAssembly;
246                                 }
247                         } else {
248                                 results.CompiledAssembly = null;
249                         }
250
251                         return results;
252                 }
253
254 #if NET_2_0
255                 private static string BuildArgs(CompilerParameters options,string[] fileNames, Dictionary <string, string> providerOptions)
256 #else
257                 private static string BuildArgs(CompilerParameters options,string[] fileNames)
258 #endif
259                 {
260                         StringBuilder args=new StringBuilder();
261                         if (options.GenerateExecutable)
262                                 args.Append("/target:exe ");
263                         else
264                                 args.Append("/target:library ");
265
266                         if (options.Win32Resource != null)
267                                 args.AppendFormat("/win32res:\"{0}\" ",
268                                         options.Win32Resource);
269
270                         if (options.IncludeDebugInformation)
271                                 args.Append("/debug+ /optimize- ");
272                         else
273                                 args.Append("/debug- /optimize+ ");
274
275                         if (options.TreatWarningsAsErrors)
276                                 args.Append("/warnaserror ");
277
278                         if (options.WarningLevel >= 0)
279                                 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
280
281                         if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
282                                 string extension = (options.GenerateExecutable ? "exe" : "dll");
283                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
284                                         !options.GenerateInMemory);
285                         }
286                         args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
287
288                         foreach (string import in options.ReferencedAssemblies) {
289                                 if (import == null || import.Length == 0)
290                                         continue;
291
292                                 args.AppendFormat("/r:\"{0}\" ",import);
293                         }
294
295                         if (options.CompilerOptions != null) {
296                                 args.Append (options.CompilerOptions);
297                                 args.Append (" ");
298                         }
299
300 #if NET_2_0
301                         foreach (string embeddedResource in options.EmbeddedResources) {
302                                 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
303                         }
304
305                         foreach (string linkedResource in options.LinkedResources) {
306                                 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
307                         }
308                         
309                         if (providerOptions != null && providerOptions.Count > 0) {
310                                 string langver;
311
312                                 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
313                                         langver = "2.0";
314
315                                 if (langver.Length >= 1 && langver [0] == 'v')
316                                         langver = langver.Substring (1);
317
318                                 // NOTE: when -langversion:linq becomes obsolete/default, the code
319                                 // below must be changed!
320                                 switch (langver) {
321                                         case "2.0":
322                                                 // current default, omit the switch
323                                                 break;
324
325                                         case "3.5":
326                                                 args.Append ("/langversion:linq");
327                                                 break;
328                                 }
329                         }
330 #endif
331
332                         args.Append (" -- ");
333                         foreach (string source in fileNames)
334                                 args.AppendFormat("\"{0}\" ",source);
335                         return args.ToString();
336                 }
337                 private static CompilerError CreateErrorFromString(string error_string)
338                 {
339 #if NET_2_0
340                         if (error_string.StartsWith ("BETA"))
341                                 return null;
342 #endif
343                         if (error_string == null || error_string == "")
344                                 return null;
345
346                         CompilerError error=new CompilerError();
347                         Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
348                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
349                         Match match=reg.Match(error_string);
350                         if (!match.Success) {
351                                 // We had some sort of runtime crash
352                                 error.ErrorText = error_string;
353                                 error.IsWarning = false;
354                                 error.ErrorNumber = "";
355                                 return error;
356                         }
357                         if (String.Empty != match.Result("${file}"))
358                                 error.FileName=match.Result("${file}");
359                         if (String.Empty != match.Result("${line}"))
360                                 error.Line=Int32.Parse(match.Result("${line}"));
361                         if (String.Empty != match.Result("${column}"))
362                                 error.Column=Int32.Parse(match.Result("${column}"));
363
364                         string level = match.Result ("${level}");
365                         if (level == "warning")
366                                 error.IsWarning = true;
367                         else if (level != "error")
368                                 return null; // error CS8028 will confuse the regex.
369
370                         error.ErrorNumber=match.Result("${number}");
371                         error.ErrorText=match.Result("${message}");
372                         return error;
373                 }
374
375                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
376                 {
377                         return temp_files.AddExtension (extension, keepFile);
378                 }
379
380                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
381                 {
382                         return temp_files.AddExtension (extension);
383                 }
384
385                 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
386                 {
387                         if (options == null) {
388                                 throw new ArgumentNullException ("options");
389                         }
390
391                         if (ea == null) {
392                                 throw new ArgumentNullException ("ea");
393                         }
394
395                         string[] fileNames = new string[ea.Length];
396                         StringCollection assemblies = options.ReferencedAssemblies;
397
398                         for (int i = 0; i < ea.Length; i++) {
399                                 CodeCompileUnit compileUnit = ea[i];
400                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
401                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
402                                 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
403                                 if (compileUnit.ReferencedAssemblies != null) {
404                                         foreach (string str in compileUnit.ReferencedAssemblies) {
405                                                 if (!assemblies.Contains (str))
406                                                         assemblies.Add (str);
407                                         }
408                                 }
409
410                                 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
411                                 s.Close ();
412                                 f.Close ();
413                         }
414                         return CompileAssemblyFromFileBatch (options, fileNames);
415                 }
416
417                 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
418                 {
419                         if (options == null) {
420                                 throw new ArgumentNullException ("options");
421                         }
422
423                         if (sources == null) {
424                                 throw new ArgumentNullException ("sources");
425                         }
426
427                         string[] fileNames = new string[sources.Length];
428
429                         for (int i = 0; i < sources.Length; i++) {
430                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
431                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
432                                 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
433                                         s.Write (sources[i]);
434                                         s.Close ();
435                                 }
436                                 f.Close ();
437                         }
438                         return CompileFromFileBatch (options, fileNames);
439                 }
440         }
441 }