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