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)),
66 if (!File.Exists (windowsMonoPath))
67 windowsMonoPath = Path.Combine (
68 Path.GetDirectoryName (
69 Path.GetDirectoryName (
70 Path.GetDirectoryName (p))),
71 "mono\\mono\\mini\\mono.exe");
72 if (!File.Exists (windowsMonoPath))
73 throw new FileNotFoundException ("Windows mono path not found: " + windowsMonoPath);
76 Path.Combine (p, "2.0\\gmcs.exe");
79 Path.Combine (p, "1.0\\mcs.exe");
81 if (!File.Exists (windowsMcsPath))
85 Path.GetDirectoryName (p),
86 "lib\\net_2_0\\gmcs.exe");
90 Path.GetDirectoryName (p),
91 "lib\\default\\mcs.exe");
93 if (!File.Exists (windowsMcsPath))
94 throw new FileNotFoundException ("Windows mcs path not found: " + windowsMcsPath);
101 public CSharpCodeCompiler()
108 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
110 return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
113 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
115 if (options == null) {
116 throw new ArgumentNullException ("options");
120 return CompileFromDomBatch (options, ea);
122 options.TempFiles.Delete ();
126 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
128 return CompileAssemblyFromFileBatch (options, new string[] { fileName });
131 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
133 if (options == null) {
134 throw new ArgumentNullException ("options");
138 return CompileFromFileBatch (options, fileNames);
140 options.TempFiles.Delete ();
144 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
146 return CompileAssemblyFromSourceBatch (options, new string[] { source });
149 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
151 if (options == null) {
152 throw new ArgumentNullException ("options");
156 return CompileFromSourceBatch (options, sources);
158 options.TempFiles.Delete ();
162 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
165 throw new ArgumentNullException("options");
166 if (null == fileNames)
167 throw new ArgumentNullException("fileNames");
169 CompilerResults results=new CompilerResults(options.TempFiles);
170 Process mcs=new Process();
174 string[] mcs_output_lines;
175 // FIXME: these lines had better be platform independent.
176 if (Path.DirectorySeparatorChar == '\\') {
177 mcs.StartInfo.FileName = windowsMonoPath;
178 mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " + BuildArgs (options, fileNames);
181 // FIXME: This is a temporary hack to make code genaration work in 2.0
182 mcs.StartInfo.FileName="gmcs";
184 mcs.StartInfo.FileName="mcs";
186 mcs.StartInfo.Arguments=BuildArgs(options,fileNames);
188 mcs.StartInfo.CreateNoWindow=true;
189 mcs.StartInfo.UseShellExecute=false;
190 mcs.StartInfo.RedirectStandardOutput=true;
191 mcs.StartInfo.RedirectStandardError=true;
194 // If there are a few kB in stdout, we might lock
195 mcs_output=mcs.StandardError.ReadToEnd();
196 mcs_stdout=mcs.StandardOutput.ReadToEnd ();
198 results.NativeCompilerReturnValue = mcs.ExitCode;
202 mcs_output_lines=mcs_output.Split(
203 System.Environment.NewLine.ToCharArray());
205 foreach (string error_line in mcs_output_lines)
207 CompilerError error=CreateErrorFromString(error_line);
210 results.Errors.Add(error);
211 if (!error.IsWarning) loadIt=false;
215 if (!File.Exists (options.OutputAssembly)) {
216 throw new Exception ("Compiler failed to produce the assembly. Stderr='"
217 +mcs_output+"', Stdout='"+mcs_stdout+"'");
219 if (options.GenerateInMemory) {
220 using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
221 byte[] buffer = new byte[fs.Length];
222 fs.Read(buffer, 0, buffer.Length);
223 results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
227 results.CompiledAssembly = Assembly.LoadFrom(options.OutputAssembly);
228 results.PathToAssembly = options.OutputAssembly;
231 results.CompiledAssembly = null;
237 private static string BuildArgs(CompilerParameters options,string[] fileNames)
239 StringBuilder args=new StringBuilder();
240 if (options.GenerateExecutable)
241 args.Append("/target:exe ");
243 args.Append("/target:library ");
245 if (options.Win32Resource != null)
246 args.AppendFormat("/win32res:\"{0}\" ",
247 options.Win32Resource);
249 if (options.IncludeDebugInformation)
250 args.Append("/debug+ /optimize- ");
252 args.Append("/debug- /optimize+ ");
254 if (options.TreatWarningsAsErrors)
255 args.Append("/warnaserror ");
257 if (options.WarningLevel >= 0)
258 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
260 if (options.OutputAssembly==null)
261 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, "dll", !options.GenerateInMemory);
262 args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
264 foreach (string import in options.ReferencedAssemblies) {
265 if (import == null || import.Length == 0)
268 args.AppendFormat("/r:\"{0}\" ",import);
271 if (options.CompilerOptions != null) {
272 args.Append (options.CompilerOptions);
277 foreach (string embeddedResource in options.EmbeddedResources) {
278 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
281 foreach (string linkedResource in options.LinkedResources) {
282 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
286 args.Append (" -- ");
287 foreach (string source in fileNames)
288 args.AppendFormat("\"{0}\" ",source);
289 return args.ToString();
291 private static CompilerError CreateErrorFromString(string error_string)
294 if (error_string.StartsWith ("BETA"))
297 if (error_string == null || error_string == "")
300 CompilerError error=new CompilerError();
301 Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
302 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
303 Match match=reg.Match(error_string);
304 if (!match.Success) return null;
305 if (String.Empty != match.Result("${file}"))
306 error.FileName=match.Result("${file}");
307 if (String.Empty != match.Result("${line}"))
308 error.Line=Int32.Parse(match.Result("${line}"));
309 if (String.Empty != match.Result("${column}"))
310 error.Column=Int32.Parse(match.Result("${column}"));
312 string level = match.Result ("${level}");
313 if (level == "warning")
314 error.IsWarning = true;
315 else if (level != "error")
316 return null; // error CS8028 will confuse the regex.
318 error.ErrorNumber=match.Result("${number}");
319 error.ErrorText=match.Result("${message}");
323 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
325 return temp_files.AddExtension (extension, keepFile);
328 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
330 return temp_files.AddExtension (extension);
333 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
335 if (options == null) {
336 throw new ArgumentNullException ("options");
340 throw new ArgumentNullException ("ea");
343 string[] fileNames = new string[ea.Length];
344 StringCollection assemblies = options.ReferencedAssemblies;
346 for (int i = 0; i < ea.Length; i++) {
347 CodeCompileUnit compileUnit = ea[i];
348 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
349 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
350 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
351 if (compileUnit.ReferencedAssemblies != null) {
352 foreach (string str in compileUnit.ReferencedAssemblies) {
353 if (!assemblies.Contains (str))
354 assemblies.Add (str);
358 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
362 return CompileAssemblyFromFileBatch (options, fileNames);
365 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
367 if (options == null) {
368 throw new ArgumentNullException ("options");
371 if (sources == null) {
372 throw new ArgumentNullException ("sources");
375 string[] fileNames = new string[sources.Length];
377 for (int i = 0; i < sources.Length; i++) {
378 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
379 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
380 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
381 s.Write (sources[i]);
386 return CompileFromFileBatch (options, fileNames);