New test.
[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)
261                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, "dll", !options.GenerateInMemory);
262                         args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
263
264                         foreach (string import in options.ReferencedAssemblies) {
265                                 if (import == null || import.Length == 0)
266                                         continue;
267
268                                 args.AppendFormat("/r:\"{0}\" ",import);
269                         }
270
271                         if (options.CompilerOptions != null) {
272                                 args.Append (options.CompilerOptions);
273                                 args.Append (" ");
274                         }
275
276 #if NET_2_0
277                         foreach (string embeddedResource in options.EmbeddedResources) {
278                                 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
279                         }
280
281                         foreach (string linkedResource in options.LinkedResources) {
282                                 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
283                         }
284 #endif
285
286                         args.Append (" -- ");
287                         foreach (string source in fileNames)
288                                 args.AppendFormat("\"{0}\" ",source);
289                         return args.ToString();
290                 }
291                 private static CompilerError CreateErrorFromString(string error_string)
292                 {
293 #if NET_2_0
294                         if (error_string.StartsWith ("BETA"))
295                                 return null;
296 #endif
297                         if (error_string == null || error_string == "")
298                                 return null;
299
300                         CompilerError error=new CompilerError();
301                         Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
302                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
303                         Match match=reg.Match(error_string);
304                         if (!match.Success) return null;
305                         if (String.Empty != match.Result("${file}"))
306                                 error.FileName=match.Result("${file}");
307                         if (String.Empty != match.Result("${line}"))
308                                 error.Line=Int32.Parse(match.Result("${line}"));
309                         if (String.Empty != match.Result("${column}"))
310                                 error.Column=Int32.Parse(match.Result("${column}"));
311
312                         string level = match.Result ("${level}");
313                         if (level == "warning")
314                                 error.IsWarning = true;
315                         else if (level != "error")
316                                 return null; // error CS8028 will confuse the regex.
317
318                         error.ErrorNumber=match.Result("${number}");
319                         error.ErrorText=match.Result("${message}");
320                         return error;
321                 }
322
323                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
324                 {
325                         return temp_files.AddExtension (extension, keepFile);
326                 }
327
328                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
329                 {
330                         return temp_files.AddExtension (extension);
331                 }
332
333                 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
334                 {
335                         if (options == null) {
336                                 throw new ArgumentNullException ("options");
337                         }
338
339                         if (ea == null) {
340                                 throw new ArgumentNullException ("ea");
341                         }
342
343                         string[] fileNames = new string[ea.Length];
344                         StringCollection assemblies = options.ReferencedAssemblies;
345
346                         for (int i = 0; i < ea.Length; i++) {
347                                 CodeCompileUnit compileUnit = ea[i];
348                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
349                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
350                                 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
351                                 if (compileUnit.ReferencedAssemblies != null) {
352                                         foreach (string str in compileUnit.ReferencedAssemblies) {
353                                                 if (!assemblies.Contains (str))
354                                                         assemblies.Add (str);
355                                         }
356                                 }
357
358                                 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
359                                 s.Close ();
360                                 f.Close ();
361                         }
362                         return CompileAssemblyFromFileBatch (options, fileNames);
363                 }
364
365                 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
366                 {
367                         if (options == null) {
368                                 throw new ArgumentNullException ("options");
369                         }
370
371                         if (sources == null) {
372                                 throw new ArgumentNullException ("sources");
373                         }
374
375                         string[] fileNames = new string[sources.Length];
376
377                         for (int i = 0; i < sources.Length; i++) {
378                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
379                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
380                                 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
381                                         s.Write (sources[i]);
382                                         s.Close ();
383                                 }
384                                 f.Close ();
385                         }
386                         return CompileFromFileBatch (options, fileNames);
387                 }
388         }
389 }