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;
53 static string unixMcsCommand;
56 StringCollection mcsOutput;
58 static CSharpCodeCompiler ()
60 if (Path.DirectorySeparatorChar == '\\') {
61 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
62 MethodInfo get_gac = gac.GetGetMethod (true);
63 string p = Path.GetDirectoryName (
64 (string) get_gac.Invoke (null, null));
65 windowsMonoPath = Path.Combine (
66 Path.GetDirectoryName (
67 Path.GetDirectoryName (p)),
69 if (!File.Exists (windowsMonoPath))
70 windowsMonoPath = Path.Combine (
71 Path.GetDirectoryName (
72 Path.GetDirectoryName (p)),
74 if (!File.Exists (windowsMonoPath))
75 windowsMonoPath = Path.Combine (
76 Path.GetDirectoryName (
77 Path.GetDirectoryName (
78 Path.GetDirectoryName (p))),
79 "mono\\mono\\mini\\mono.exe");
80 if (!File.Exists (windowsMonoPath))
81 throw new FileNotFoundException ("Windows mono path not found: " + windowsMonoPath);
83 windowsMcsPath = Path.Combine (p, "4.5\\mcs.exe");
84 if (!File.Exists (windowsMcsPath))
85 windowsMcsPath = Path.Combine(Path.GetDirectoryName (p), "lib\\build\\mcs.exe");
87 if (!File.Exists (windowsMcsPath))
88 throw new FileNotFoundException ("Windows mcs path not found: " + windowsMcsPath);
90 var mscorlibPath = new Uri (typeof (object).Assembly.CodeBase).LocalPath;
91 var unixMcsPath = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "mcs"));
92 if (File.Exists (unixMcsPath))
93 unixMcsCommand = unixMcsPath;
95 unixMcsCommand = "mcs";
102 public CSharpCodeCompiler()
106 public CSharpCodeCompiler (IDictionary <string, string> providerOptions) :
107 base (providerOptions)
114 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
116 return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
119 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
121 if (options == null) {
122 throw new ArgumentNullException ("options");
126 return CompileFromDomBatch (options, ea);
128 options.TempFiles.Delete ();
132 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
134 return CompileAssemblyFromFileBatch (options, new string[] { fileName });
137 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
139 if (options == null) {
140 throw new ArgumentNullException ("options");
144 return CompileFromFileBatch (options, fileNames);
146 options.TempFiles.Delete ();
150 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
152 return CompileAssemblyFromSourceBatch (options, new string[] { source });
155 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
157 if (options == null) {
158 throw new ArgumentNullException ("options");
162 return CompileFromSourceBatch (options, sources);
164 options.TempFiles.Delete ();
168 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
171 throw new ArgumentNullException("options");
172 if (null == fileNames)
173 throw new ArgumentNullException("fileNames");
175 CompilerResults results=new CompilerResults(options.TempFiles);
176 Process mcs=new Process();
178 // FIXME: these lines had better be platform independent.
179 if (Path.DirectorySeparatorChar == '\\') {
180 mcs.StartInfo.FileName = windowsMonoPath;
181 mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
182 BuildArgs (options, fileNames, ProviderOptions);
184 mcs.StartInfo.FileName=unixMcsCommand;
185 mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions);
188 mcsOutput = new StringCollection ();
189 mcsOutMutex = new Mutex ();
191 string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
192 if (monoPath != null)
193 monoPath = String.Empty;
195 string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
196 if (privateBinPath != null && privateBinPath.Length > 0)
197 monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);
199 if (monoPath.Length > 0) {
200 StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
201 if (dict.ContainsKey ("MONO_PATH"))
202 dict ["MONO_PATH"] = monoPath;
204 dict.Add ("MONO_PATH", monoPath);
208 * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that
209 * may not handle some of the options causing compilation failure
211 mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty;
213 mcs.StartInfo.CreateNoWindow=true;
214 mcs.StartInfo.UseShellExecute=false;
215 mcs.StartInfo.RedirectStandardOutput=true;
216 mcs.StartInfo.RedirectStandardError=true;
217 mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
221 } catch (Exception e) {
222 Win32Exception exc = e as Win32Exception;
224 throw new SystemException (String.Format ("Error running {0}: {1}", mcs.StartInfo.FileName,
225 Win32Exception.W32ErrorMessage (exc.NativeErrorCode)));
231 mcs.BeginOutputReadLine ();
232 mcs.BeginErrorReadLine ();
235 results.NativeCompilerReturnValue = mcs.ExitCode;
237 mcs.CancelErrorRead ();
238 mcs.CancelOutputRead ();
242 StringCollection sc = mcsOutput;
245 foreach (string error_line in mcsOutput) {
246 CompilerError error = CreateErrorFromString (error_line);
248 results.Errors.Add (error);
249 if (!error.IsWarning)
255 sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
260 if (!File.Exists (options.OutputAssembly)) {
261 StringBuilder sb = new StringBuilder ();
262 foreach (string s in sc)
263 sb.Append (s + Environment.NewLine);
265 throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
268 if (options.GenerateInMemory) {
269 using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
270 byte[] buffer = new byte[fs.Length];
271 fs.Read(buffer, 0, buffer.Length);
272 results.CompiledAssembly = Assembly.Load(buffer, null);
276 // Avoid setting CompiledAssembly right now since the output might be a netmodule
277 results.PathToAssembly = options.OutputAssembly;
280 results.CompiledAssembly = null;
286 void McsStderrDataReceived (object sender, DataReceivedEventArgs args)
288 if (args.Data != null) {
289 mcsOutMutex.WaitOne ();
290 mcsOutput.Add (args.Data);
291 mcsOutMutex.ReleaseMutex ();
295 private static string BuildArgs(CompilerParameters options,string[] fileNames, IDictionary <string, string> providerOptions)
297 StringBuilder args=new StringBuilder();
298 if (options.GenerateExecutable)
299 args.Append("/target:exe ");
301 args.Append("/target:library ");
303 string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
304 if (privateBinPath != null && privateBinPath.Length > 0)
305 args.AppendFormat ("/lib:\"{0}\" ", privateBinPath);
307 if (options.Win32Resource != null)
308 args.AppendFormat("/win32res:\"{0}\" ",
309 options.Win32Resource);
311 if (options.IncludeDebugInformation)
312 args.Append("/debug+ /optimize- ");
314 args.Append("/debug- /optimize+ ");
316 if (options.TreatWarningsAsErrors)
317 args.Append("/warnaserror ");
319 if (options.WarningLevel >= 0)
320 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
322 if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
323 string extension = (options.GenerateExecutable ? "exe" : "dll");
324 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
325 !options.GenerateInMemory);
327 args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
329 foreach (string import in options.ReferencedAssemblies) {
330 if (import == null || import.Length == 0)
333 args.AppendFormat("/r:\"{0}\" ",import);
336 if (options.CompilerOptions != null) {
337 args.Append (options.CompilerOptions);
341 foreach (string embeddedResource in options.EmbeddedResources) {
342 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
345 foreach (string linkedResource in options.LinkedResources) {
346 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
349 if (providerOptions != null && providerOptions.Count > 0) {
352 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
355 if (langver.Length >= 1 && langver [0] == 'v')
356 langver = langver.Substring (1);
360 args.Append ("/langversion:ISO-2 ");
364 // current default, omit the switch
369 args.Append (" -- ");
370 foreach (string source in fileNames)
371 args.AppendFormat("\"{0}\" ",source);
372 return args.ToString();
375 // Keep in sync with mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
376 const string ErrorRegexPattern = @"
378 (\s*(?<file>[^\(]+) # filename (optional)
379 (\((?<line>\d*)(,(?<column>\d*[\+]*))?\))? # line+column (optional)
381 (?<level>\w+) # error|warning
383 (?<number>[^:]*\d) # CS1234
388 static readonly Regex RelatedSymbolsRegex = new Regex(
390 \(Location\ of\ the\ symbol\ related\ to\ previous\ (warning|error)\)
392 RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);
394 private static CompilerError CreateErrorFromString(string error_string)
396 if (error_string.StartsWith ("BETA"))
399 if (error_string == null || error_string == "")
402 CompilerError error=new CompilerError();
403 Regex reg = new Regex (ErrorRegexPattern, RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);
404 Match match=reg.Match(error_string);
405 if (!match.Success) {
406 match = RelatedSymbolsRegex.Match (error_string);
407 if (!match.Success) {
408 // We had some sort of runtime crash
409 error.ErrorText = error_string;
410 error.IsWarning = false;
411 error.ErrorNumber = "";
414 // This line is a continuation of previous warning of error
418 if (String.Empty != match.Result("${file}"))
419 error.FileName=match.Result("${file}");
420 if (String.Empty != match.Result("${line}"))
421 error.Line=Int32.Parse(match.Result("${line}"));
422 if (String.Empty != match.Result("${column}"))
423 error.Column=Int32.Parse(match.Result("${column}").Trim('+'));
425 string level = match.Result ("${level}");
426 if (level == "warning")
427 error.IsWarning = true;
428 else if (level != "error")
429 return null; // error CS8028 will confuse the regex.
431 error.ErrorNumber=match.Result("${number}");
432 error.ErrorText=match.Result("${message}");
436 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
438 return temp_files.AddExtension (extension, keepFile);
441 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
443 return temp_files.AddExtension (extension);
446 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
448 if (options == null) {
449 throw new ArgumentNullException ("options");
453 throw new ArgumentNullException ("ea");
456 string[] fileNames = new string[ea.Length];
457 StringCollection assemblies = options.ReferencedAssemblies;
459 for (int i = 0; i < ea.Length; i++) {
460 CodeCompileUnit compileUnit = ea[i];
461 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
462 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
463 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
464 if (compileUnit.ReferencedAssemblies != null) {
465 foreach (string str in compileUnit.ReferencedAssemblies) {
466 if (!assemblies.Contains (str))
467 assemblies.Add (str);
471 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
475 return CompileAssemblyFromFileBatch (options, fileNames);
478 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
480 if (options == null) {
481 throw new ArgumentNullException ("options");
484 if (sources == null) {
485 throw new ArgumentNullException ("sources");
488 string[] fileNames = new string[sources.Length];
490 for (int i = 0; i < sources.Length; i++) {
491 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
492 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
493 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
494 s.Write (sources[i]);
499 return CompileFromFileBatch (options, fileNames);