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);
158 // FIXME: This is a temporary hack to make code genaration work in 2.0
159 mcs.StartInfo.FileName="gmcs";
161 mcs.StartInfo.FileName="mcs";
163 mcs.StartInfo.Arguments=BuildArgs(options,fileNames);
165 mcs.StartInfo.CreateNoWindow=true;
166 mcs.StartInfo.UseShellExecute=false;
167 mcs.StartInfo.RedirectStandardOutput=true;
168 mcs.StartInfo.RedirectStandardError=true;
171 // If there are a few kB in stdout, we might lock
172 mcs_output=mcs.StandardError.ReadToEnd();
173 mcs.StandardOutput.ReadToEnd ();
175 results.NativeCompilerReturnValue = mcs.ExitCode;
179 mcs_output_lines=mcs_output.Split(
180 System.Environment.NewLine.ToCharArray());
182 foreach (string error_line in mcs_output_lines)
184 CompilerError error=CreateErrorFromString(error_line);
187 results.Errors.Add(error);
188 if (!error.IsWarning) loadIt=false;
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);
200 results.CompiledAssembly = Assembly.LoadFrom(options.OutputAssembly);
201 results.PathToAssembly = options.OutputAssembly;
204 results.CompiledAssembly = null;
210 private static string BuildArgs(CompilerParameters options,string[] fileNames)
212 StringBuilder args=new StringBuilder();
213 if (options.GenerateExecutable)
214 args.Append("/target:exe ");
216 args.Append("/target:library ");
218 if (options.Win32Resource != null)
219 args.AppendFormat("/win32res:\"{0}\" ",
220 options.Win32Resource);
222 if (options.IncludeDebugInformation)
223 args.Append("/debug+ /optimize- ");
225 args.Append("/debug- /optimize+ ");
227 if (options.TreatWarningsAsErrors)
228 args.Append("/warnaserror ");
230 if (options.WarningLevel >= 0)
231 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
233 if (options.OutputAssembly==null)
234 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, "dll", !options.GenerateInMemory);
235 args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
237 if (null != options.ReferencedAssemblies)
239 foreach (string import in options.ReferencedAssemblies)
240 args.AppendFormat("/r:\"{0}\" ",import);
243 if (options.CompilerOptions != null) {
244 args.Append (options.CompilerOptions);
248 args.Append (" -- ");
249 foreach (string source in fileNames)
250 args.AppendFormat("\"{0}\" ",source);
251 return args.ToString();
253 private static CompilerError CreateErrorFromString(string error_string)
256 if (error_string.StartsWith ("BETA"))
259 if (error_string == null || error_string == "")
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}"));
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.
280 error.ErrorNumber=match.Result("${number}");
281 error.ErrorText=match.Result("${message}");
285 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
287 return temp_files.AddExtension (extension, keepFile);
290 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
292 return temp_files.AddExtension (extension);
295 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
297 if (options == null) {
298 throw new ArgumentNullException ("options");
302 throw new ArgumentNullException ("ea");
305 string[] fileNames = new string[ea.Length];
306 StringCollection assemblies = options.ReferencedAssemblies;
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);
320 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
324 return CompileAssemblyFromFileBatch (options, fileNames);
327 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
329 if (options == null) {
330 throw new ArgumentNullException ("options");
333 if (sources == null) {
334 throw new ArgumentNullException ("sources");
337 string[] fileNames = new string[sources.Length];
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]);
348 return CompileFromFileBatch (options, fileNames);