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 ();
183 string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
184 if (monoPath != null)
185 monoPath = String.Empty;
187 string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
188 if (privateBinPath != null && privateBinPath.Length > 0)
189 monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);
191 if (monoPath.Length > 0) {
192 StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
193 if (dict.ContainsKey ("MONO_PATH"))
194 dict ["MONO_PATH"] = monoPath;
196 dict.Add ("MONO_PATH", monoPath);
200 * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that
201 * may not handle some of the options causing compilation failure
203 mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty;
205 mcs.StartInfo.CreateNoWindow=true;
206 mcs.StartInfo.UseShellExecute=false;
207 mcs.StartInfo.RedirectStandardOutput=true;
208 mcs.StartInfo.RedirectStandardError=true;
209 mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
213 } catch (Exception e) {
214 Win32Exception exc = e as Win32Exception;
216 throw new SystemException (String.Format ("Error running {0}: {1}", mcs.StartInfo.FileName,
217 Win32Exception.W32ErrorMessage (exc.NativeErrorCode)));
223 mcs.BeginOutputReadLine ();
224 mcs.BeginErrorReadLine ();
227 results.NativeCompilerReturnValue = mcs.ExitCode;
229 mcs.CancelErrorRead ();
230 mcs.CancelOutputRead ();
234 StringCollection sc = mcsOutput;
237 foreach (string error_line in mcsOutput) {
238 CompilerError error = CreateErrorFromString (error_line);
240 results.Errors.Add (error);
241 if (!error.IsWarning)
247 sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
252 if (!File.Exists (options.OutputAssembly)) {
253 StringBuilder sb = new StringBuilder ();
254 foreach (string s in sc)
255 sb.Append (s + Environment.NewLine);
257 throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
260 if (options.GenerateInMemory) {
261 using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
262 byte[] buffer = new byte[fs.Length];
263 fs.Read(buffer, 0, buffer.Length);
264 results.CompiledAssembly = Assembly.Load(buffer, null);
268 // Avoid setting CompiledAssembly right now since the output might be a netmodule
269 results.PathToAssembly = options.OutputAssembly;
272 results.CompiledAssembly = null;
278 void McsStderrDataReceived (object sender, DataReceivedEventArgs args)
280 if (args.Data != null) {
281 mcsOutMutex.WaitOne ();
282 mcsOutput.Add (args.Data);
283 mcsOutMutex.ReleaseMutex ();
287 private static string BuildArgs(CompilerParameters options,string[] fileNames, IDictionary <string, string> providerOptions)
289 StringBuilder args=new StringBuilder();
290 if (options.GenerateExecutable)
291 args.Append("/target:exe ");
293 args.Append("/target:library ");
295 string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
296 if (privateBinPath != null && privateBinPath.Length > 0)
297 args.AppendFormat ("/lib:\"{0}\" ", privateBinPath);
299 if (options.Win32Resource != null)
300 args.AppendFormat("/win32res:\"{0}\" ",
301 options.Win32Resource);
303 if (options.IncludeDebugInformation)
304 args.Append("/debug+ /optimize- ");
306 args.Append("/debug- /optimize+ ");
308 if (options.TreatWarningsAsErrors)
309 args.Append("/warnaserror ");
311 if (options.WarningLevel >= 0)
312 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
314 if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
315 string extension = (options.GenerateExecutable ? "exe" : "dll");
316 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
317 !options.GenerateInMemory);
319 args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
321 foreach (string import in options.ReferencedAssemblies) {
322 if (import == null || import.Length == 0)
325 args.AppendFormat("/r:\"{0}\" ",import);
328 if (options.CompilerOptions != null) {
329 args.Append (options.CompilerOptions);
333 foreach (string embeddedResource in options.EmbeddedResources) {
334 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
337 foreach (string linkedResource in options.LinkedResources) {
338 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
341 if (providerOptions != null && providerOptions.Count > 0) {
344 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
347 if (langver.Length >= 1 && langver [0] == 'v')
348 langver = langver.Substring (1);
352 args.Append ("/langversion:ISO-2 ");
356 // current default, omit the switch
361 args.Append("/sdk:4.5");
363 args.Append (" -- ");
364 foreach (string source in fileNames)
365 args.AppendFormat("\"{0}\" ",source);
366 return args.ToString();
369 // Keep in sync with mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
370 const string ErrorRegexPattern = @"
372 (\s*(?<file>[^\(]+) # filename (optional)
373 (\((?<line>\d*)(,(?<column>\d*[\+]*))?\))? # line+column (optional)
375 (?<level>\w+) # error|warning
377 (?<number>[^:]*\d) # CS1234
382 private static CompilerError CreateErrorFromString(string error_string)
384 if (error_string.StartsWith ("BETA"))
387 if (error_string == null || error_string == "")
390 CompilerError error=new CompilerError();
391 Regex reg = new Regex (ErrorRegexPattern, RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);
392 Match match=reg.Match(error_string);
393 if (!match.Success) {
394 // We had some sort of runtime crash
395 error.ErrorText = error_string;
396 error.IsWarning = false;
397 error.ErrorNumber = "";
400 if (String.Empty != match.Result("${file}"))
401 error.FileName=match.Result("${file}");
402 if (String.Empty != match.Result("${line}"))
403 error.Line=Int32.Parse(match.Result("${line}"));
404 if (String.Empty != match.Result("${column}"))
405 error.Column=Int32.Parse(match.Result("${column}").Trim('+'));
407 string level = match.Result ("${level}");
408 if (level == "warning")
409 error.IsWarning = true;
410 else if (level != "error")
411 return null; // error CS8028 will confuse the regex.
413 error.ErrorNumber=match.Result("${number}");
414 error.ErrorText=match.Result("${message}");
418 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
420 return temp_files.AddExtension (extension, keepFile);
423 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
425 return temp_files.AddExtension (extension);
428 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
430 if (options == null) {
431 throw new ArgumentNullException ("options");
435 throw new ArgumentNullException ("ea");
438 string[] fileNames = new string[ea.Length];
439 StringCollection assemblies = options.ReferencedAssemblies;
441 for (int i = 0; i < ea.Length; i++) {
442 CodeCompileUnit compileUnit = ea[i];
443 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
444 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
445 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
446 if (compileUnit.ReferencedAssemblies != null) {
447 foreach (string str in compileUnit.ReferencedAssemblies) {
448 if (!assemblies.Contains (str))
449 assemblies.Add (str);
453 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
457 return CompileAssemblyFromFileBatch (options, fileNames);
460 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
462 if (options == null) {
463 throw new ArgumentNullException ("options");
466 if (sources == null) {
467 throw new ArgumentNullException ("sources");
470 string[] fileNames = new string[sources.Length];
472 for (int i = 0; i < sources.Length; i++) {
473 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
474 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
475 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
476 s.Write (sources[i]);
481 return CompileFromFileBatch (options, fileNames);