2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[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                                 // FIXME: right now we use "fixed" version 1.0
54                                 // mcs at any time.
55                                 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
56                                 MethodInfo get_gac = gac.GetGetMethod (true);
57                                 string p = Path.GetDirectoryName (
58                                         (string) get_gac.Invoke (null, null));
59                                 windowsMonoPath = Path.Combine (
60                                         Path.GetDirectoryName (
61                                                 Path.GetDirectoryName (p)),
62                                         "bin\\mono.bat");
63                                 if (!File.Exists (windowsMonoPath))
64                                         windowsMonoPath = Path.Combine (
65                                                 Path.GetDirectoryName (
66                                                         Path.GetDirectoryName (p)),
67                                                 "bin\\mono.exe");
68                                 windowsMcsPath =
69                                         Path.Combine (p, "1.0\\mcs.exe");
70                         }
71                 }
72
73                 //
74                 // Constructors
75                 //
76                 public CSharpCodeCompiler()
77                 {
78                 }
79
80                 //
81                 // Methods
82                 //
83                 [MonoTODO]
84                 public CompilerResults CompileAssemblyFromDom (
85                         CompilerParameters options,CodeCompileUnit e)
86                 {
87                         return CompileAssemblyFromDomBatch(options,new CodeCompileUnit[]{e});
88                 }
89                 public CompilerResults CompileAssemblyFromDomBatch (
90                         CompilerParameters options,CodeCompileUnit[] ea)
91                 {
92                         string[] fileNames=new string[ea.Length];
93                         int i=0;
94                         if (options == null)
95                                 options = new CompilerParameters ();
96                         
97                         StringCollection assemblies = options.ReferencedAssemblies;
98
99                         foreach (CodeCompileUnit e in ea) {
100                                 fileNames [i] = GetTempFileNameWithExtension (options.TempFiles, i.ToString () + ".cs");
101                                 FileStream f=new FileStream(fileNames[i],FileMode.OpenOrCreate);
102                                 StreamWriter s=new StreamWriter(f, Encoding.UTF8);
103                                 if (e.ReferencedAssemblies != null) {
104                                         foreach (string str in e.ReferencedAssemblies) {
105                                                 if (!assemblies.Contains (str))
106                                                         assemblies.Add (str);
107                                         }
108                                 }
109
110                                 ((ICodeGenerator)this).GenerateCodeFromCompileUnit (e, s, new CodeGeneratorOptions());
111                                 s.Close();
112                                 f.Close();
113                                 i++;
114                         }
115                         return CompileAssemblyFromFileBatch (options, fileNames);
116                 }
117                 
118                 public CompilerResults CompileAssemblyFromFile (
119                         CompilerParameters options,string fileName)
120                 {
121                         return CompileAssemblyFromFileBatch (options, new string []{fileName});
122                 }
123
124                 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
125                 {
126                         if (null == options)
127                                 throw new ArgumentNullException("options");
128                         if (null == fileNames)
129                                 throw new ArgumentNullException("fileNames");
130
131                         CompilerResults results=new CompilerResults(options.TempFiles);
132                         Process mcs=new Process();
133
134                         string mcs_output;
135                         string[] mcs_output_lines;
136                         // FIXME: these lines had better be platform independent.
137                         if (Path.DirectorySeparatorChar == '\\') {
138                                 mcs.StartInfo.FileName = windowsMonoPath;
139                                 mcs.StartInfo.Arguments = windowsMcsPath + ' ' + BuildArgs (options, fileNames);
140                         }
141                         else {
142 #if NET_2_0
143                                 // FIXME: This is a temporary hack to make code genaration work in 2.0
144                                 mcs.StartInfo.FileName="gmcs";
145 #else
146                                 mcs.StartInfo.FileName="mcs";
147 #endif
148                                 mcs.StartInfo.Arguments=BuildArgs(options,fileNames);
149                         }
150                         mcs.StartInfo.CreateNoWindow=true;
151                         mcs.StartInfo.UseShellExecute=false;
152                         mcs.StartInfo.RedirectStandardOutput=true;
153                         mcs.StartInfo.RedirectStandardError=true;
154                         try {
155                                 mcs.Start();
156                                 // If there are a few kB in stdout, we might lock
157                                 mcs_output=mcs.StandardError.ReadToEnd();
158                                 mcs.StandardOutput.ReadToEnd ();
159                                 mcs.WaitForExit();
160                         } finally {
161                                 results.NativeCompilerReturnValue = mcs.ExitCode;
162                                 mcs.Close();
163                         }
164                         mcs_output_lines=mcs_output.Split(
165                                 System.Environment.NewLine.ToCharArray());
166                         bool loadIt=true;
167                         foreach (string error_line in mcs_output_lines)
168                         {
169                                 CompilerError error=CreateErrorFromString(error_line);
170                                 if (null!=error)
171                                 {
172                                         results.Errors.Add(error);
173                                         if (!error.IsWarning) loadIt=false;
174                                 }
175                         }
176                         if (loadIt)
177                                 results.CompiledAssembly=Assembly.LoadFrom(options.OutputAssembly);
178                         else
179                                 results.CompiledAssembly=null;
180
181                         return results;
182                 }
183                 public CompilerResults CompileAssemblyFromSource (
184                         CompilerParameters options,string source)
185                 {
186                         return CompileAssemblyFromSourceBatch(options,new string[]{source});
187                 }
188                 public CompilerResults CompileAssemblyFromSourceBatch (
189                         CompilerParameters options,string[] sources)
190                 {
191                         string[] fileNames=new string[sources.Length];
192                         int i=0;
193                         foreach (string source in sources) {
194                                 fileNames [i] = GetTempFileNameWithExtension (options.TempFiles, i.ToString () + ".cs");
195                                 FileStream f=new FileStream(fileNames[i],FileMode.OpenOrCreate);
196                                 StreamWriter s=new StreamWriter(f);
197                                 s.Write(source);
198                                 s.Close();
199                                 f.Close();
200                                 i++;
201                         }
202                         return CompileAssemblyFromFileBatch (options, fileNames);
203                 }
204
205
206                 private static string BuildArgs(CompilerParameters options,string[] fileNames)
207                 {
208                         StringBuilder args=new StringBuilder();
209                         if (options.GenerateExecutable)
210                                 args.Append("/target:exe ");
211                         else
212                                 args.Append("/target:library ");
213
214                         if (options.IncludeDebugInformation)
215                                 args.Append("/debug+ /optimize- ");
216                         else
217                                 args.Append("/debug- /optimize+ ");
218
219                         if (options.TreatWarningsAsErrors)
220                                 args.Append("/warnaserror ");
221
222                         if (options.WarningLevel >= 0)
223                                 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
224
225                         if (options.OutputAssembly==null)
226                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, "dll");
227                         args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
228
229                         if (null != options.ReferencedAssemblies)
230                         {
231                                 foreach (string import in options.ReferencedAssemblies)
232                                         args.AppendFormat("/r:\"{0}\" ",import);
233                         }
234
235                         if (options.CompilerOptions != null) {
236                                 args.Append (options.CompilerOptions);
237                                 args.Append (" ");
238                         }
239                         
240                         args.Append (" -- ");
241                         foreach (string source in fileNames)
242                                 args.AppendFormat("\"{0}\" ",source);
243                         return args.ToString();
244                 }
245                 private static CompilerError CreateErrorFromString(string error_string)
246                 {
247 #if NET_2_0
248                         if (error_string.StartsWith ("BETA"))
249                                 return null;
250 #endif
251
252                         CompilerError error=new CompilerError();
253                         Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
254                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
255                         Match match=reg.Match(error_string);
256                         if (!match.Success) return null;
257                         if (String.Empty != match.Result("${file}"))
258                                 error.FileName=match.Result("${file}");
259                         if (String.Empty != match.Result("${line}"))
260                                 error.Line=Int32.Parse(match.Result("${line}"));
261                         if (String.Empty != match.Result("${column}"))
262                                 error.Column=Int32.Parse(match.Result("${column}"));
263                         if (match.Result("${level}")=="warning")
264                                 error.IsWarning=true;
265                         error.ErrorNumber=match.Result("${number}");
266                         error.ErrorText=match.Result("${message}");
267                         return error;
268                 }
269
270                 static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
271                 {
272                         return temp_files.AddExtension (extension);
273                 }
274         }
275 }