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 (IDictionary <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 string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
221 if (monoPath == null)
222 monoPath = String.Empty;
224 string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
225 if (privateBinPath != null && privateBinPath.Length > 0)
226 monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);
228 if (monoPath.Length > 0) {
229 StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
230 if (dict.ContainsKey ("MONO_PATH"))
231 dict ["MONO_PATH"] = monoPath;
233 dict.Add ("MONO_PATH", monoPath);
236 mcs.StartInfo.CreateNoWindow=true;
237 mcs.StartInfo.UseShellExecute=false;
238 mcs.StartInfo.RedirectStandardOutput=true;
239 mcs.StartInfo.RedirectStandardError=true;
241 mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
248 mcs.BeginOutputReadLine ();
249 mcs.BeginErrorReadLine ();
251 // If there are a few kB in stdout, we might lock
252 mcs_output=mcs.StandardError.ReadToEnd();
253 mcs_stdout=mcs.StandardOutput.ReadToEnd ();
257 results.NativeCompilerReturnValue = mcs.ExitCode;
260 mcs.CancelErrorRead ();
261 mcs.CancelOutputRead ();
268 StringCollection sc = mcsOutput;
270 mcsOutput = mcs_output.Split (System.Environment.NewLine.ToCharArray ());
271 StringCollection sc = new StringCollection ();
275 foreach (string error_line in mcsOutput) {
279 CompilerError error = CreateErrorFromString (error_line);
281 results.Errors.Add (error);
282 if (!error.IsWarning)
288 sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
293 if (!File.Exists (options.OutputAssembly)) {
294 StringBuilder sb = new StringBuilder ();
295 foreach (string s in sc)
296 sb.Append (s + Environment.NewLine);
298 throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
301 if (options.GenerateInMemory) {
302 using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
303 byte[] buffer = new byte[fs.Length];
304 fs.Read(buffer, 0, buffer.Length);
305 results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
309 // Avoid setting CompiledAssembly right now since the output might be a netmodule
310 results.PathToAssembly = options.OutputAssembly;
313 results.CompiledAssembly = null;
320 void McsStderrDataReceived (object sender, DataReceivedEventArgs args)
322 if (args.Data != null) {
323 mcsOutMutex.WaitOne ();
324 mcsOutput.Add (args.Data);
325 mcsOutMutex.ReleaseMutex ();
329 private static string BuildArgs(CompilerParameters options,string[] fileNames, IDictionary <string, string> providerOptions)
331 private static string BuildArgs(CompilerParameters options,string[] fileNames)
334 StringBuilder args=new StringBuilder();
335 if (options.GenerateExecutable)
336 args.Append("/target:exe ");
338 args.Append("/target:library ");
340 string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
341 if (privateBinPath != null && privateBinPath.Length > 0)
342 args.AppendFormat ("/lib:\"{0}\" ", privateBinPath);
344 if (options.Win32Resource != null)
345 args.AppendFormat("/win32res:\"{0}\" ",
346 options.Win32Resource);
348 if (options.IncludeDebugInformation)
349 args.Append("/debug+ /optimize- ");
351 args.Append("/debug- /optimize+ ");
353 if (options.TreatWarningsAsErrors)
354 args.Append("/warnaserror ");
356 if (options.WarningLevel >= 0)
357 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
359 if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
360 string extension = (options.GenerateExecutable ? "exe" : "dll");
361 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
362 !options.GenerateInMemory);
364 args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
366 foreach (string import in options.ReferencedAssemblies) {
367 if (import == null || import.Length == 0)
370 args.AppendFormat("/r:\"{0}\" ",import);
373 if (options.CompilerOptions != null) {
374 args.Append (options.CompilerOptions);
379 foreach (string embeddedResource in options.EmbeddedResources) {
380 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
383 foreach (string linkedResource in options.LinkedResources) {
384 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
387 if (providerOptions != null && providerOptions.Count > 0) {
390 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
393 if (langver.Length >= 1 && langver [0] == 'v')
394 langver = langver.Substring (1);
398 args.Append ("/langversion:ISO-2");
402 // current default, omit the switch
408 args.Append (" -- ");
409 foreach (string source in fileNames)
410 args.AppendFormat("\"{0}\" ",source);
411 return args.ToString();
413 private static CompilerError CreateErrorFromString(string error_string)
416 if (error_string.StartsWith ("BETA"))
419 if (error_string == null || error_string == "")
422 CompilerError error=new CompilerError();
423 Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
424 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
425 Match match=reg.Match(error_string);
426 if (!match.Success) {
427 // We had some sort of runtime crash
428 error.ErrorText = error_string;
429 error.IsWarning = false;
430 error.ErrorNumber = "";
433 if (String.Empty != match.Result("${file}"))
434 error.FileName=match.Result("${file}");
435 if (String.Empty != match.Result("${line}"))
436 error.Line=Int32.Parse(match.Result("${line}"));
437 if (String.Empty != match.Result("${column}"))
438 error.Column=Int32.Parse(match.Result("${column}"));
440 string level = match.Result ("${level}");
441 if (level == "warning")
442 error.IsWarning = true;
443 else if (level != "error")
444 return null; // error CS8028 will confuse the regex.
446 error.ErrorNumber=match.Result("${number}");
447 error.ErrorText=match.Result("${message}");
451 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
453 return temp_files.AddExtension (extension, keepFile);
456 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
458 return temp_files.AddExtension (extension);
461 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
463 if (options == null) {
464 throw new ArgumentNullException ("options");
468 throw new ArgumentNullException ("ea");
471 string[] fileNames = new string[ea.Length];
472 StringCollection assemblies = options.ReferencedAssemblies;
474 for (int i = 0; i < ea.Length; i++) {
475 CodeCompileUnit compileUnit = ea[i];
476 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
477 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
478 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
479 if (compileUnit.ReferencedAssemblies != null) {
480 foreach (string str in compileUnit.ReferencedAssemblies) {
481 if (!assemblies.Contains (str))
482 assemblies.Add (str);
486 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
490 return CompileAssemblyFromFileBatch (options, fileNames);
493 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
495 if (options == null) {
496 throw new ArgumentNullException ("options");
499 if (sources == null) {
500 throw new ArgumentNullException ("sources");
503 string[] fileNames = new string[sources.Length];
505 for (int i = 0; i < sources.Length; i++) {
506 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
507 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
508 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
509 s.Write (sources[i]);
514 return CompileFromFileBatch (options, fileNames);