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