2 // Mono.CSharp CSharpCodeCompiler Class implementation
5 // Sean Kasun (seank@users.sf.net)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // Copyright (c) Novell, Inc. (http://www.novell.com)
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:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
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.
36 using System.CodeDom.Compiler;
39 using System.Reflection;
40 using System.Collections;
41 using System.Collections.Specialized;
42 using System.Diagnostics;
43 using System.Text.RegularExpressions;
45 internal class CSharpCodeCompiler : CSharpCodeGenerator, ICodeCompiler
47 static string windowsMcsPath;
48 static string windowsMonoPath;
50 static CSharpCodeCompiler ()
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)),
61 if (!File.Exists (windowsMonoPath))
62 windowsMonoPath = Path.Combine (
63 Path.GetDirectoryName (
64 Path.GetDirectoryName (p)),
68 Path.Combine (p, "2.0\\gmcs.exe");
71 Path.Combine (p, "1.0\\mcs.exe");
79 public CSharpCodeCompiler()
86 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
88 return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
91 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
93 if (options == null) {
94 throw new ArgumentNullException ("options");
98 return CompileFromDomBatch (options, ea);
100 options.TempFiles.Delete ();
104 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
106 return CompileAssemblyFromFileBatch (options, new string[] { fileName });
109 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
111 if (options == null) {
112 throw new ArgumentNullException ("options");
116 return CompileFromFileBatch (options, fileNames);
118 options.TempFiles.Delete ();
122 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
124 return CompileAssemblyFromSourceBatch (options, new string[] { source });
127 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
129 if (options == null) {
130 throw new ArgumentNullException ("options");
134 return CompileFromSourceBatch (options, sources);
136 options.TempFiles.Delete ();
140 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
143 throw new ArgumentNullException("options");
144 if (null == fileNames)
145 throw new ArgumentNullException("fileNames");
147 CompilerResults results=new CompilerResults(options.TempFiles);
148 Process mcs=new Process();
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);
159 // FIXME: This is a temporary hack to make code genaration work in 2.0
160 mcs.StartInfo.FileName="gmcs";
162 mcs.StartInfo.FileName="mcs";
164 mcs.StartInfo.Arguments=BuildArgs(options,fileNames);
166 mcs.StartInfo.CreateNoWindow=true;
167 mcs.StartInfo.UseShellExecute=false;
168 mcs.StartInfo.RedirectStandardOutput=true;
169 mcs.StartInfo.RedirectStandardError=true;
172 // If there are a few kB in stdout, we might lock
173 mcs_output=mcs.StandardError.ReadToEnd();
174 mcs.StandardOutput.ReadToEnd ();
177 results.NativeCompilerReturnValue = mcs.ExitCode;
180 mcs_output_lines=mcs_output.Split(
181 System.Environment.NewLine.ToCharArray());
183 foreach (string error_line in mcs_output_lines)
185 CompilerError error=CreateErrorFromString(error_line);
188 results.Errors.Add(error);
189 if (!error.IsWarning) loadIt=false;
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);
201 results.CompiledAssembly = Assembly.LoadFrom(options.OutputAssembly);
202 results.PathToAssembly = options.OutputAssembly;
205 results.CompiledAssembly = null;
211 private static string BuildArgs(CompilerParameters options,string[] fileNames)
213 StringBuilder args=new StringBuilder();
214 if (options.GenerateExecutable)
215 args.Append("/target:exe ");
217 args.Append("/target:library ");
219 if (options.Win32Resource != null)
220 args.AppendFormat("/win32res:\"{0}\" ",
221 options.Win32Resource);
223 if (options.IncludeDebugInformation)
224 args.Append("/debug+ /optimize- ");
226 args.Append("/debug- /optimize+ ");
228 if (options.TreatWarningsAsErrors)
229 args.Append("/warnaserror ");
231 if (options.WarningLevel >= 0)
232 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
234 if (options.OutputAssembly==null)
235 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, "dll", !options.GenerateInMemory);
236 args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
238 if (null != options.ReferencedAssemblies)
240 foreach (string import in options.ReferencedAssemblies)
241 args.AppendFormat("/r:\"{0}\" ",import);
244 if (options.CompilerOptions != null) {
245 args.Append (options.CompilerOptions);
249 args.Append (" -- ");
250 foreach (string source in fileNames)
251 args.AppendFormat("\"{0}\" ",source);
252 return args.ToString();
254 private static CompilerError CreateErrorFromString(string error_string)
257 if (error_string.StartsWith ("BETA"))
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}"));
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.
279 error.ErrorNumber=match.Result("${number}");
280 error.ErrorText=match.Result("${message}");
284 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
286 return temp_files.AddExtension (extension, keepFile);
289 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
291 return temp_files.AddExtension (extension);
294 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
296 if (options == null) {
297 throw new ArgumentNullException ("options");
301 throw new ArgumentNullException ("ea");
304 string[] fileNames = new string[ea.Length];
305 StringCollection assemblies = options.ReferencedAssemblies;
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);
319 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
323 return CompileAssemblyFromFileBatch (options, fileNames);
326 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
328 if (options == null) {
329 throw new ArgumentNullException ("options");
332 if (sources == null) {
333 throw new ArgumentNullException ("sources");
336 string[] fileNames = new string[sources.Length];
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]);
347 return CompileFromFileBatch (options, fileNames);