* CodeGeneratorFromExpressionTest.cs: Added test for
[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                         } else {
157 #if NET_2_0
158                                 // FIXME: This is a temporary hack to make code genaration work in 2.0
159                                 mcs.StartInfo.FileName="gmcs";
160 #else
161                                 mcs.StartInfo.FileName="mcs";
162 #endif
163                                 mcs.StartInfo.Arguments=BuildArgs(options,fileNames);
164                         }
165                         mcs.StartInfo.CreateNoWindow=true;
166                         mcs.StartInfo.UseShellExecute=false;
167                         mcs.StartInfo.RedirectStandardOutput=true;
168                         mcs.StartInfo.RedirectStandardError=true;
169                         try {
170                                 mcs.Start();
171                                 // If there are a few kB in stdout, we might lock
172                                 mcs_output=mcs.StandardError.ReadToEnd();
173                                 mcs.StandardOutput.ReadToEnd ();
174                                 mcs.WaitForExit();
175                                 results.NativeCompilerReturnValue = mcs.ExitCode;
176                         } finally {
177                                 mcs.Close();
178                         }
179                         mcs_output_lines=mcs_output.Split(
180                                 System.Environment.NewLine.ToCharArray());
181                         bool loadIt=true;
182                         foreach (string error_line in mcs_output_lines)
183                         {
184                                 CompilerError error=CreateErrorFromString(error_line);
185                                 if (null!=error)
186                                 {
187                                         results.Errors.Add(error);
188                                         if (!error.IsWarning) loadIt=false;
189                                 }
190                         }
191                         if (loadIt) {
192                                 if (options.GenerateInMemory) {
193                                         using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
194                                                 byte[] buffer = new byte[fs.Length];
195                                                 fs.Read(buffer, 0, buffer.Length);
196                                                 results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
197                                                 fs.Close();
198                                         }
199                                 } else {
200                                         results.CompiledAssembly = Assembly.LoadFrom(options.OutputAssembly);
201                                         results.PathToAssembly = options.OutputAssembly;
202                                 }
203                         } else {
204                                 results.CompiledAssembly = null;
205                         }
206
207                         return results;
208                 }
209
210                 private static string BuildArgs(CompilerParameters options,string[] fileNames)
211                 {
212                         StringBuilder args=new StringBuilder();
213                         if (options.GenerateExecutable)
214                                 args.Append("/target:exe ");
215                         else
216                                 args.Append("/target:library ");
217
218                         if (options.Win32Resource != null)
219                                 args.AppendFormat("/win32res:\"{0}\" ",
220                                         options.Win32Resource);
221
222                         if (options.IncludeDebugInformation)
223                                 args.Append("/debug+ /optimize- ");
224                         else
225                                 args.Append("/debug- /optimize+ ");
226
227                         if (options.TreatWarningsAsErrors)
228                                 args.Append("/warnaserror ");
229
230                         if (options.WarningLevel >= 0)
231                                 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
232
233                         if (options.OutputAssembly==null)
234                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, "dll", !options.GenerateInMemory);
235                         args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
236
237                         if (null != options.ReferencedAssemblies)
238                         {
239                                 foreach (string import in options.ReferencedAssemblies)
240                                         args.AppendFormat("/r:\"{0}\" ",import);
241                         }
242
243                         if (options.CompilerOptions != null) {
244                                 args.Append (options.CompilerOptions);
245                                 args.Append (" ");
246                         }
247                         
248                         args.Append (" -- ");
249                         foreach (string source in fileNames)
250                                 args.AppendFormat("\"{0}\" ",source);
251                         return args.ToString();
252                 }
253                 private static CompilerError CreateErrorFromString(string error_string)
254                 {
255 #if NET_2_0
256                         if (error_string.StartsWith ("BETA"))
257                                 return null;
258 #endif
259                         if (error_string == null || error_string == "")
260                                 return null;
261
262                         CompilerError error=new CompilerError();
263                         Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
264                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
265                         Match match=reg.Match(error_string);
266                         if (!match.Success) return null;
267                         if (String.Empty != match.Result("${file}"))
268                                 error.FileName=match.Result("${file}");
269                         if (String.Empty != match.Result("${line}"))
270                                 error.Line=Int32.Parse(match.Result("${line}"));
271                         if (String.Empty != match.Result("${column}"))
272                                 error.Column=Int32.Parse(match.Result("${column}"));
273
274                         string level = match.Result ("${level}");
275                         if (level == "warning")
276                                 error.IsWarning = true;
277                         else if (level != "error")
278                                 return null; // error CS8028 will confuse the regex.
279
280                         error.ErrorNumber=match.Result("${number}");
281                         error.ErrorText=match.Result("${message}");
282                         return error;
283                 }
284
285                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
286                 {
287                         return temp_files.AddExtension (extension, keepFile);
288                 }
289
290                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
291                 {
292                         return temp_files.AddExtension (extension);
293                 }
294
295                 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
296                 {
297                         if (options == null) {
298                                 throw new ArgumentNullException ("options");
299                         }
300
301                         if (ea == null) {
302                                 throw new ArgumentNullException ("ea");
303                         }
304
305                         string[] fileNames = new string[ea.Length];
306                         StringCollection assemblies = options.ReferencedAssemblies;
307
308                         for (int i = 0; i < ea.Length; i++) {
309                                 CodeCompileUnit compileUnit = ea[i];
310                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
311                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
312                                 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
313                                 if (compileUnit.ReferencedAssemblies != null) {
314                                         foreach (string str in compileUnit.ReferencedAssemblies) {
315                                                 if (!assemblies.Contains (str))
316                                                         assemblies.Add (str);
317                                         }
318                                 }
319
320                                 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
321                                 s.Close ();
322                                 f.Close ();
323                         }
324                         return CompileAssemblyFromFileBatch (options, fileNames);
325                 }
326
327                 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
328                 {
329                         if (options == null) {
330                                 throw new ArgumentNullException ("options");
331                         }
332
333                         if (sources == null) {
334                                 throw new ArgumentNullException ("sources");
335                         }
336
337                         string[] fileNames = new string[sources.Length];
338
339                         for (int i = 0; i < sources.Length; i++) {
340                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
341                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
342                                 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
343                                         s.Write (sources[i]);
344                                         s.Close ();
345                                 }
346                                 f.Close ();
347                         }
348                         return CompileFromFileBatch (options, fileNames);
349                 }
350         }
351 }