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;
46 using System.Threading;
47 using System.Collections.Generic;
50 internal class CSharpCodeCompiler : CSharpCodeGenerator, ICodeCompiler
52 static string windowsMcsPath;
53 static string windowsMonoPath;
57 StringCollection mcsOutput;
60 static CSharpCodeCompiler ()
62 if (Path.DirectorySeparatorChar == '\\') {
63 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
64 MethodInfo get_gac = gac.GetGetMethod (true);
65 string p = Path.GetDirectoryName (
66 (string) get_gac.Invoke (null, null));
67 windowsMonoPath = Path.Combine (
68 Path.GetDirectoryName (
69 Path.GetDirectoryName (p)),
71 if (!File.Exists (windowsMonoPath))
72 windowsMonoPath = Path.Combine (
73 Path.GetDirectoryName (
74 Path.GetDirectoryName (p)),
76 if (!File.Exists (windowsMonoPath))
77 windowsMonoPath = Path.Combine (
78 Path.GetDirectoryName (
79 Path.GetDirectoryName (
80 Path.GetDirectoryName (p))),
81 "mono\\mono\\mini\\mono.exe");
82 if (!File.Exists (windowsMonoPath))
83 throw new FileNotFoundException ("Windows mono path not found: " + windowsMonoPath);
86 Path.Combine (p, "2.0\\gmcs.exe");
89 Path.Combine (p, "1.0\\mcs.exe");
91 if (!File.Exists (windowsMcsPath))
95 Path.GetDirectoryName (p),
96 "lib\\net_2_0\\gmcs.exe");
100 Path.GetDirectoryName (p),
101 "lib\\default\\mcs.exe");
103 if (!File.Exists (windowsMcsPath))
104 throw new FileNotFoundException ("Windows mcs path not found: " + windowsMcsPath);
111 public CSharpCodeCompiler()
116 public CSharpCodeCompiler (Dictionary <string, string> providerOptions) :
117 base (providerOptions)
125 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
127 return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
130 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
132 if (options == null) {
133 throw new ArgumentNullException ("options");
137 return CompileFromDomBatch (options, ea);
139 options.TempFiles.Delete ();
143 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
145 return CompileAssemblyFromFileBatch (options, new string[] { fileName });
148 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
150 if (options == null) {
151 throw new ArgumentNullException ("options");
155 return CompileFromFileBatch (options, fileNames);
157 options.TempFiles.Delete ();
161 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
163 return CompileAssemblyFromSourceBatch (options, new string[] { source });
166 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
168 if (options == null) {
169 throw new ArgumentNullException ("options");
173 return CompileFromSourceBatch (options, sources);
175 options.TempFiles.Delete ();
179 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
182 throw new ArgumentNullException("options");
183 if (null == fileNames)
184 throw new ArgumentNullException("fileNames");
186 CompilerResults results=new CompilerResults(options.TempFiles);
187 Process mcs=new Process();
195 // FIXME: these lines had better be platform independent.
196 if (Path.DirectorySeparatorChar == '\\') {
197 mcs.StartInfo.FileName = windowsMonoPath;
198 mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
200 BuildArgs (options, fileNames, ProviderOptions);
202 BuildArgs (options, fileNames);
206 // FIXME: This is a temporary hack to make code genaration work in 2.0
207 mcs.StartInfo.FileName="gmcs";
208 mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions);
210 mcs.StartInfo.FileName="mcs";
211 mcs.StartInfo.Arguments=BuildArgs(options, fileNames);
216 mcsOutput = new StringCollection ();
217 mcsOutMutex = new Mutex ();
220 mcs.StartInfo.CreateNoWindow=true;
221 mcs.StartInfo.UseShellExecute=false;
222 mcs.StartInfo.RedirectStandardOutput=true;
223 mcs.StartInfo.RedirectStandardError=true;
225 mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
232 mcs.BeginOutputReadLine ();
233 mcs.BeginErrorReadLine ();
235 // If there are a few kB in stdout, we might lock
236 mcs_output=mcs.StandardError.ReadToEnd();
237 mcs_stdout=mcs.StandardOutput.ReadToEnd ();
241 results.NativeCompilerReturnValue = mcs.ExitCode;
244 mcs.CancelErrorRead ();
245 mcs.CancelOutputRead ();
252 StringCollection sc = mcsOutput;
254 mcsOutput = mcs_output.Split (System.Environment.NewLine.ToCharArray ());
255 StringCollection sc = new StringCollection ();
259 foreach (string error_line in mcsOutput) {
263 CompilerError error = CreateErrorFromString (error_line);
265 results.Errors.Add (error);
266 if (!error.IsWarning)
272 sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
277 if (!File.Exists (options.OutputAssembly)) {
278 StringBuilder sb = new StringBuilder ();
279 foreach (string s in sc)
280 sb.Append (s + Environment.NewLine);
282 throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
285 if (options.GenerateInMemory) {
286 using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
287 byte[] buffer = new byte[fs.Length];
288 fs.Read(buffer, 0, buffer.Length);
289 results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
293 // Avoid setting CompiledAssembly right now since the output might be a netmodule
294 results.PathToAssembly = options.OutputAssembly;
297 results.CompiledAssembly = null;
304 void McsStderrDataReceived (object sender, DataReceivedEventArgs args)
306 mcsOutMutex.WaitOne ();
307 mcsOutput.Add (args.Data);
308 mcsOutMutex.ReleaseMutex ();
311 private static string BuildArgs(CompilerParameters options,string[] fileNames, Dictionary <string, string> providerOptions)
313 private static string BuildArgs(CompilerParameters options,string[] fileNames)
316 StringBuilder args=new StringBuilder();
317 if (options.GenerateExecutable)
318 args.Append("/target:exe ");
320 args.Append("/target:library ");
322 if (options.Win32Resource != null)
323 args.AppendFormat("/win32res:\"{0}\" ",
324 options.Win32Resource);
326 if (options.IncludeDebugInformation)
327 args.Append("/debug+ /optimize- ");
329 args.Append("/debug- /optimize+ ");
331 if (options.TreatWarningsAsErrors)
332 args.Append("/warnaserror ");
334 if (options.WarningLevel >= 0)
335 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
337 if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
338 string extension = (options.GenerateExecutable ? "exe" : "dll");
339 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
340 !options.GenerateInMemory);
342 args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
344 foreach (string import in options.ReferencedAssemblies) {
345 if (import == null || import.Length == 0)
348 args.AppendFormat("/r:\"{0}\" ",import);
351 if (options.CompilerOptions != null) {
352 args.Append (options.CompilerOptions);
357 foreach (string embeddedResource in options.EmbeddedResources) {
358 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
361 foreach (string linkedResource in options.LinkedResources) {
362 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
365 if (providerOptions != null && providerOptions.Count > 0) {
368 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
371 if (langver.Length >= 1 && langver [0] == 'v')
372 langver = langver.Substring (1);
376 args.Append ("/langversion:ISO-2");
380 // current default, omit the switch
386 args.Append (" -- ");
387 foreach (string source in fileNames)
388 args.AppendFormat("\"{0}\" ",source);
389 return args.ToString();
391 private static CompilerError CreateErrorFromString(string error_string)
394 if (error_string.StartsWith ("BETA"))
397 if (error_string == null || error_string == "")
400 CompilerError error=new CompilerError();
401 Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
402 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
403 Match match=reg.Match(error_string);
404 if (!match.Success) {
405 // We had some sort of runtime crash
406 error.ErrorText = error_string;
407 error.IsWarning = false;
408 error.ErrorNumber = "";
411 if (String.Empty != match.Result("${file}"))
412 error.FileName=match.Result("${file}");
413 if (String.Empty != match.Result("${line}"))
414 error.Line=Int32.Parse(match.Result("${line}"));
415 if (String.Empty != match.Result("${column}"))
416 error.Column=Int32.Parse(match.Result("${column}"));
418 string level = match.Result ("${level}");
419 if (level == "warning")
420 error.IsWarning = true;
421 else if (level != "error")
422 return null; // error CS8028 will confuse the regex.
424 error.ErrorNumber=match.Result("${number}");
425 error.ErrorText=match.Result("${message}");
429 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
431 return temp_files.AddExtension (extension, keepFile);
434 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
436 return temp_files.AddExtension (extension);
439 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
441 if (options == null) {
442 throw new ArgumentNullException ("options");
446 throw new ArgumentNullException ("ea");
449 string[] fileNames = new string[ea.Length];
450 StringCollection assemblies = options.ReferencedAssemblies;
452 for (int i = 0; i < ea.Length; i++) {
453 CodeCompileUnit compileUnit = ea[i];
454 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
455 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
456 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
457 if (compileUnit.ReferencedAssemblies != null) {
458 foreach (string str in compileUnit.ReferencedAssemblies) {
459 if (!assemblies.Contains (str))
460 assemblies.Add (str);
464 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
468 return CompileAssemblyFromFileBatch (options, fileNames);
471 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
473 if (options == null) {
474 throw new ArgumentNullException ("options");
477 if (sources == null) {
478 throw new ArgumentNullException ("sources");
481 string[] fileNames = new string[sources.Length];
483 for (int i = 0; i < sources.Length; i++) {
484 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
485 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
486 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
487 s.Write (sources[i]);
492 return CompileFromFileBatch (options, fileNames);