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;
37 using System.ComponentModel;
40 using System.Reflection;
41 using System.Collections;
42 using System.Collections.Specialized;
43 using System.Diagnostics;
44 using System.Text.RegularExpressions;
45 using System.Threading;
46 using System.Collections.Generic;
47 using System.Globalization;
49 internal class CSharpCodeCompiler : CSharpCodeGenerator, ICodeCompiler
51 static string windowsMcsPath;
52 static string windowsMonoPath;
55 StringCollection mcsOutput;
57 static CSharpCodeCompiler ()
59 if (Path.DirectorySeparatorChar == '\\') {
60 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
61 MethodInfo get_gac = gac.GetGetMethod (true);
62 string p = Path.GetDirectoryName (
63 (string) get_gac.Invoke (null, null));
64 windowsMonoPath = Path.Combine (
65 Path.GetDirectoryName (
66 Path.GetDirectoryName (p)),
68 if (!File.Exists (windowsMonoPath))
69 windowsMonoPath = Path.Combine (
70 Path.GetDirectoryName (
71 Path.GetDirectoryName (p)),
73 if (!File.Exists (windowsMonoPath))
74 windowsMonoPath = Path.Combine (
75 Path.GetDirectoryName (
76 Path.GetDirectoryName (
77 Path.GetDirectoryName (p))),
78 "mono\\mono\\mini\\mono.exe");
79 if (!File.Exists (windowsMonoPath))
80 throw new FileNotFoundException ("Windows mono path not found: " + windowsMonoPath);
82 windowsMcsPath = Path.Combine (p, "4.5\\mcs.exe");
83 if (!File.Exists (windowsMcsPath))
84 windowsMcsPath = Path.Combine(Path.GetDirectoryName (p), "lib\\build\\mcs.exe");
86 if (!File.Exists (windowsMcsPath))
87 throw new FileNotFoundException ("Windows mcs path not found: " + windowsMcsPath);
94 public CSharpCodeCompiler()
98 public CSharpCodeCompiler (IDictionary <string, string> providerOptions) :
99 base (providerOptions)
106 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
108 return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
111 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
113 if (options == null) {
114 throw new ArgumentNullException ("options");
118 return CompileFromDomBatch (options, ea);
120 options.TempFiles.Delete ();
124 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
126 return CompileAssemblyFromFileBatch (options, new string[] { fileName });
129 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
131 if (options == null) {
132 throw new ArgumentNullException ("options");
136 return CompileFromFileBatch (options, fileNames);
138 options.TempFiles.Delete ();
142 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
144 return CompileAssemblyFromSourceBatch (options, new string[] { source });
147 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
149 if (options == null) {
150 throw new ArgumentNullException ("options");
154 return CompileFromSourceBatch (options, sources);
156 options.TempFiles.Delete ();
160 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
163 throw new ArgumentNullException("options");
164 if (null == fileNames)
165 throw new ArgumentNullException("fileNames");
167 CompilerResults results=new CompilerResults(options.TempFiles);
168 Process mcs=new Process();
170 // FIXME: these lines had better be platform independent.
171 if (Path.DirectorySeparatorChar == '\\') {
172 mcs.StartInfo.FileName = windowsMonoPath;
173 mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
174 BuildArgs (options, fileNames, ProviderOptions);
176 mcs.StartInfo.FileName="mcs";
177 mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions);
180 mcsOutput = new StringCollection ();
181 mcsOutMutex = new Mutex ();
184 * !:. KLUDGE WARNING .:!
186 * When running the 2.0 test suite some assemblies will invoke mcs via
187 * CodeDOM and the new mcs process will find the MONO_PATH variable in its
188 * environment pointing to the net_2_0 library which will cause the runtime
189 * to attempt to load the 2.0 corlib into 4.0 process and thus mcs will
190 * fail. At the same time, we must not touch MONO_PATH when running outside
191 * the test suite, thus the kludge.
193 * !:. KLUDGE WARNING .:!
195 if (Environment.GetEnvironmentVariable ("MONO_TESTS_IN_PROGRESS") != null) {
196 string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
197 if (!String.IsNullOrEmpty (monoPath)) {
198 const string basePath = "/class/lib/";
199 const string profile = "net_2_0";
200 var basePathIndex = monoPath.IndexOf (basePath, StringComparison.Ordinal);
201 if (basePathIndex > 0 && basePathIndex + basePath.Length + profile.Length <= monoPath.Length) {
202 var currentProfile = monoPath.Substring (basePathIndex + basePath.Length, profile.Length);
203 if (currentProfile.Equals (profile, StringComparison.OrdinalIgnoreCase))
204 monoPath = monoPath.Replace (basePath + currentProfile, basePath + "net_4_0");
206 mcs.StartInfo.EnvironmentVariables ["MONO_PATH"] = monoPath;
211 string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
212 if (monoPath != null)
213 monoPath = String.Empty;
215 string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
216 if (privateBinPath != null && privateBinPath.Length > 0)
217 monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);
219 if (monoPath.Length > 0) {
220 StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
221 if (dict.ContainsKey ("MONO_PATH"))
222 dict ["MONO_PATH"] = monoPath;
224 dict.Add ("MONO_PATH", monoPath);
228 * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that
229 * may not handle some of the options causing compilation failure
231 mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty;
233 mcs.StartInfo.CreateNoWindow=true;
234 mcs.StartInfo.UseShellExecute=false;
235 mcs.StartInfo.RedirectStandardOutput=true;
236 mcs.StartInfo.RedirectStandardError=true;
237 mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
241 } catch (Exception e) {
242 Win32Exception exc = e as Win32Exception;
244 throw new SystemException (String.Format ("Error running {0}: {1}", mcs.StartInfo.FileName,
245 Win32Exception.W32ErrorMessage (exc.NativeErrorCode)));
251 mcs.BeginOutputReadLine ();
252 mcs.BeginErrorReadLine ();
255 results.NativeCompilerReturnValue = mcs.ExitCode;
257 mcs.CancelErrorRead ();
258 mcs.CancelOutputRead ();
262 StringCollection sc = mcsOutput;
265 foreach (string error_line in mcsOutput) {
266 CompilerError error = CreateErrorFromString (error_line);
268 results.Errors.Add (error);
269 if (!error.IsWarning)
275 sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
280 if (!File.Exists (options.OutputAssembly)) {
281 StringBuilder sb = new StringBuilder ();
282 foreach (string s in sc)
283 sb.Append (s + Environment.NewLine);
285 throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
288 if (options.GenerateInMemory) {
289 using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
290 byte[] buffer = new byte[fs.Length];
291 fs.Read(buffer, 0, buffer.Length);
292 results.CompiledAssembly = Assembly.Load(buffer, null);
296 // Avoid setting CompiledAssembly right now since the output might be a netmodule
297 results.PathToAssembly = options.OutputAssembly;
300 results.CompiledAssembly = null;
306 void McsStderrDataReceived (object sender, DataReceivedEventArgs args)
308 if (args.Data != null) {
309 mcsOutMutex.WaitOne ();
310 mcsOutput.Add (args.Data);
311 mcsOutMutex.ReleaseMutex ();
315 private static string BuildArgs(CompilerParameters options,string[] fileNames, IDictionary <string, string> providerOptions)
317 StringBuilder args=new StringBuilder();
318 if (options.GenerateExecutable)
319 args.Append("/target:exe ");
321 args.Append("/target:library ");
323 string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
324 if (privateBinPath != null && privateBinPath.Length > 0)
325 args.AppendFormat ("/lib:\"{0}\" ", privateBinPath);
327 if (options.Win32Resource != null)
328 args.AppendFormat("/win32res:\"{0}\" ",
329 options.Win32Resource);
331 if (options.IncludeDebugInformation)
332 args.Append("/debug+ /optimize- ");
334 args.Append("/debug- /optimize+ ");
336 if (options.TreatWarningsAsErrors)
337 args.Append("/warnaserror ");
339 if (options.WarningLevel >= 0)
340 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
342 if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
343 string extension = (options.GenerateExecutable ? "exe" : "dll");
344 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
345 !options.GenerateInMemory);
347 args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
349 foreach (string import in options.ReferencedAssemblies) {
350 if (import == null || import.Length == 0)
353 args.AppendFormat("/r:\"{0}\" ",import);
356 if (options.CompilerOptions != null) {
357 args.Append (options.CompilerOptions);
361 foreach (string embeddedResource in options.EmbeddedResources) {
362 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
365 foreach (string linkedResource in options.LinkedResources) {
366 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
369 if (providerOptions != null && providerOptions.Count > 0) {
372 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
379 if (langver.Length >= 1 && langver [0] == 'v')
380 langver = langver.Substring (1);
384 args.Append ("/langversion:ISO-2 ");
388 // current default, omit the switch
394 args.Append("/sdk:4.5");
396 args.Append("/sdk:4");
398 args.Append("/sdk:2");
401 args.Append (" -- ");
402 foreach (string source in fileNames)
403 args.AppendFormat("\"{0}\" ",source);
404 return args.ToString();
407 // Keep in sync with mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
408 const string ErrorRegexPattern = @"
410 (\s*(?<file>[^\(]+) # filename (optional)
411 (\((?<line>\d*)(,(?<column>\d*[\+]*))?\))? # line+column (optional)
413 (?<level>\w+) # error|warning
415 (?<number>[^:]*\d) # CS1234
420 private static CompilerError CreateErrorFromString(string error_string)
422 if (error_string.StartsWith ("BETA"))
425 if (error_string == null || error_string == "")
428 CompilerError error=new CompilerError();
429 Regex reg = new Regex (ErrorRegexPattern, RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);
430 Match match=reg.Match(error_string);
431 if (!match.Success) {
432 // We had some sort of runtime crash
433 error.ErrorText = error_string;
434 error.IsWarning = false;
435 error.ErrorNumber = "";
438 if (String.Empty != match.Result("${file}"))
439 error.FileName=match.Result("${file}");
440 if (String.Empty != match.Result("${line}"))
441 error.Line=Int32.Parse(match.Result("${line}"));
442 if (String.Empty != match.Result("${column}"))
443 error.Column=Int32.Parse(match.Result("${column}").Trim('+'));
445 string level = match.Result ("${level}");
446 if (level == "warning")
447 error.IsWarning = true;
448 else if (level != "error")
449 return null; // error CS8028 will confuse the regex.
451 error.ErrorNumber=match.Result("${number}");
452 error.ErrorText=match.Result("${message}");
456 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
458 return temp_files.AddExtension (extension, keepFile);
461 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
463 return temp_files.AddExtension (extension);
466 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
468 if (options == null) {
469 throw new ArgumentNullException ("options");
473 throw new ArgumentNullException ("ea");
476 string[] fileNames = new string[ea.Length];
477 StringCollection assemblies = options.ReferencedAssemblies;
479 for (int i = 0; i < ea.Length; i++) {
480 CodeCompileUnit compileUnit = ea[i];
481 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
482 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
483 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
484 if (compileUnit.ReferencedAssemblies != null) {
485 foreach (string str in compileUnit.ReferencedAssemblies) {
486 if (!assemblies.Contains (str))
487 assemblies.Add (str);
491 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
495 return CompileAssemblyFromFileBatch (options, fileNames);
498 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
500 if (options == null) {
501 throw new ArgumentNullException ("options");
504 if (sources == null) {
505 throw new ArgumentNullException ("sources");
508 string[] fileNames = new string[sources.Length];
510 for (int i = 0; i < sources.Length; i++) {
511 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
512 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
513 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
514 s.Write (sources[i]);
519 return CompileFromFileBatch (options, fileNames);