2004-07-09 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[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, "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                                 mcs.StartInfo.FileName="mcs";
143                                 mcs.StartInfo.Arguments=BuildArgs(options,fileNames);
144                         }
145                         mcs.StartInfo.CreateNoWindow=true;
146                         mcs.StartInfo.UseShellExecute=false;
147                         mcs.StartInfo.RedirectStandardOutput=true;
148                         try {
149                                 mcs.Start();
150                                 mcs_output=mcs.StandardOutput.ReadToEnd();
151                                 mcs.WaitForExit();
152                         } finally {
153                                 results.NativeCompilerReturnValue = mcs.ExitCode;
154                                 mcs.Close();
155                         }
156                         mcs_output_lines=mcs_output.Split(
157                                 System.Environment.NewLine.ToCharArray());
158                         bool loadIt=true;
159                         foreach (string error_line in mcs_output_lines)
160                         {
161                                 CompilerError error=CreateErrorFromString(error_line);
162                                 if (null!=error)
163                                 {
164                                         results.Errors.Add(error);
165                                         if (!error.IsWarning) loadIt=false;
166                                 }
167                         }
168                         if (loadIt)
169                                 results.CompiledAssembly=Assembly.LoadFrom(options.OutputAssembly);
170                         else
171                                 results.CompiledAssembly=null;
172
173                         return results;
174                 }
175                 public CompilerResults CompileAssemblyFromSource (
176                         CompilerParameters options,string source)
177                 {
178                         return CompileAssemblyFromSourceBatch(options,new string[]{source});
179                 }
180                 public CompilerResults CompileAssemblyFromSourceBatch (
181                         CompilerParameters options,string[] sources)
182                 {
183                         string[] fileNames=new string[sources.Length];
184                         int i=0;
185                         foreach (string source in sources) {
186                                 fileNames [i] = GetTempFileNameWithExtension (options.TempFiles, "cs");
187                                 FileStream f=new FileStream(fileNames[i],FileMode.OpenOrCreate);
188                                 StreamWriter s=new StreamWriter(f);
189                                 s.Write(source);
190                                 s.Close();
191                                 f.Close();
192                                 i++;
193                         }
194                         return CompileAssemblyFromFileBatch (options, fileNames);
195                 }
196                 private static string BuildArgs(
197                         CompilerParameters options,string[] fileNames)
198                 {
199                         StringBuilder args=new StringBuilder();
200                         if (options.GenerateExecutable)
201                                 args.AppendFormat("/target:exe ");
202                         else
203                                 args.AppendFormat("/target:library ");
204                         if (options.IncludeDebugInformation)
205                                 args.AppendFormat("/debug ");
206                         if (options.TreatWarningsAsErrors)
207                                 args.AppendFormat("/warnaserror ");
208
209                         if (options.WarningLevel != -1)
210                                 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
211
212                         if (options.OutputAssembly==null)
213                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, "dll");
214                         args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
215                         if (null != options.ReferencedAssemblies)
216                         {
217                                 foreach (string import in options.ReferencedAssemblies)
218                                         args.AppendFormat("/r:\"{0}\" ",import);
219                         }
220                         
221                         args.Append (" -- ");
222                         foreach (string source in fileNames)
223                                 args.AppendFormat("\"{0}\" ",source);
224                         return args.ToString();
225                 }
226                 private static CompilerError CreateErrorFromString(string error_string)
227                 {
228                         // When IncludeDebugInformation is true, prevents the debug symbols stats from braeking this.
229                         if (error_string.StartsWith ("WROTE SYMFILE") || error_string.StartsWith ("OffsetTable"))
230                                 return null;
231
232                         CompilerError error=new CompilerError();
233                         Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
234                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
235                         Match match=reg.Match(error_string);
236                         if (!match.Success) return null;
237                         if (String.Empty != match.Result("${file}"))
238                                 error.FileName=match.Result("${file}");
239                         if (String.Empty != match.Result("${line}"))
240                                 error.Line=Int32.Parse(match.Result("${line}"));
241                         if (String.Empty != match.Result("${column}"))
242                                 error.Column=Int32.Parse(match.Result("${column}"));
243                         if (match.Result("${level}")=="warning")
244                                 error.IsWarning=true;
245                         error.ErrorNumber=match.Result("${number}");
246                         error.ErrorText=match.Result("${message}");
247                         return error;
248                 }
249
250                 static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
251                 {
252                         return temp_files.AddExtension (extension);
253                 }
254         }
255 }