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.Collections.Generic;
49 internal class CSharpCodeCompiler : CSharpCodeGenerator, ICodeCompiler
51 static string windowsMcsPath;
52 static string windowsMonoPath;
54 static CSharpCodeCompiler ()
56 if (Path.DirectorySeparatorChar == '\\') {
57 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
58 MethodInfo get_gac = gac.GetGetMethod (true);
59 string p = Path.GetDirectoryName (
60 (string) get_gac.Invoke (null, null));
61 windowsMonoPath = Path.Combine (
62 Path.GetDirectoryName (
63 Path.GetDirectoryName (p)),
65 if (!File.Exists (windowsMonoPath))
66 windowsMonoPath = Path.Combine (
67 Path.GetDirectoryName (
68 Path.GetDirectoryName (p)),
70 if (!File.Exists (windowsMonoPath))
71 windowsMonoPath = Path.Combine (
72 Path.GetDirectoryName (
73 Path.GetDirectoryName (
74 Path.GetDirectoryName (p))),
75 "mono\\mono\\mini\\mono.exe");
76 if (!File.Exists (windowsMonoPath))
77 throw new FileNotFoundException ("Windows mono path not found: " + windowsMonoPath);
80 Path.Combine (p, "2.0\\gmcs.exe");
83 Path.Combine (p, "1.0\\mcs.exe");
85 if (!File.Exists (windowsMcsPath))
89 Path.GetDirectoryName (p),
90 "lib\\net_2_0\\gmcs.exe");
94 Path.GetDirectoryName (p),
95 "lib\\default\\mcs.exe");
97 if (!File.Exists (windowsMcsPath))
98 throw new FileNotFoundException ("Windows mcs path not found: " + windowsMcsPath);
105 public CSharpCodeCompiler()
110 public CSharpCodeCompiler (Dictionary <string, string> providerOptions) :
111 base (providerOptions)
119 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
121 return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
124 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
126 if (options == null) {
127 throw new ArgumentNullException ("options");
131 return CompileFromDomBatch (options, ea);
133 options.TempFiles.Delete ();
137 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
139 return CompileAssemblyFromFileBatch (options, new string[] { fileName });
142 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
144 if (options == null) {
145 throw new ArgumentNullException ("options");
149 return CompileFromFileBatch (options, fileNames);
151 options.TempFiles.Delete ();
155 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
157 return CompileAssemblyFromSourceBatch (options, new string[] { source });
160 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
162 if (options == null) {
163 throw new ArgumentNullException ("options");
167 return CompileFromSourceBatch (options, sources);
169 options.TempFiles.Delete ();
173 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
176 throw new ArgumentNullException("options");
177 if (null == fileNames)
178 throw new ArgumentNullException("fileNames");
180 CompilerResults results=new CompilerResults(options.TempFiles);
181 Process mcs=new Process();
185 string[] mcs_output_lines;
186 // FIXME: these lines had better be platform independent.
187 if (Path.DirectorySeparatorChar == '\\') {
188 mcs.StartInfo.FileName = windowsMonoPath;
189 mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
191 BuildArgs (options, fileNames, ProviderOptions);
193 BuildArgs (options, fileNames);
197 // FIXME: This is a temporary hack to make code genaration work in 2.0
198 mcs.StartInfo.FileName="gmcs";
199 mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions);
201 mcs.StartInfo.FileName="mcs";
202 mcs.StartInfo.Arguments=BuildArgs(options, fileNames);
205 mcs.StartInfo.CreateNoWindow=true;
206 mcs.StartInfo.UseShellExecute=false;
207 mcs.StartInfo.RedirectStandardOutput=true;
208 mcs.StartInfo.RedirectStandardError=true;
211 // If there are a few kB in stdout, we might lock
212 mcs_output=mcs.StandardError.ReadToEnd();
213 mcs_stdout=mcs.StandardOutput.ReadToEnd ();
215 results.NativeCompilerReturnValue = mcs.ExitCode;
219 mcs_output_lines=mcs_output.Split(
220 System.Environment.NewLine.ToCharArray());
222 foreach (string error_line in mcs_output_lines)
224 CompilerError error=CreateErrorFromString(error_line);
227 results.Errors.Add(error);
228 if (!error.IsWarning) loadIt=false;
232 if (!File.Exists (options.OutputAssembly)) {
233 throw new Exception ("Compiler failed to produce the assembly. Stderr='"
234 +mcs_output+"', Stdout='"+mcs_stdout+"'");
236 if (options.GenerateInMemory) {
237 using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
238 byte[] buffer = new byte[fs.Length];
239 fs.Read(buffer, 0, buffer.Length);
240 results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
244 results.CompiledAssembly = Assembly.LoadFrom(options.OutputAssembly);
245 results.PathToAssembly = options.OutputAssembly;
248 results.CompiledAssembly = null;
255 private static string BuildArgs(CompilerParameters options,string[] fileNames, Dictionary <string, string> providerOptions)
257 private static string BuildArgs(CompilerParameters options,string[] fileNames)
260 StringBuilder args=new StringBuilder();
261 if (options.GenerateExecutable)
262 args.Append("/target:exe ");
264 args.Append("/target:library ");
266 if (options.Win32Resource != null)
267 args.AppendFormat("/win32res:\"{0}\" ",
268 options.Win32Resource);
270 if (options.IncludeDebugInformation)
271 args.Append("/debug+ /optimize- ");
273 args.Append("/debug- /optimize+ ");
275 if (options.TreatWarningsAsErrors)
276 args.Append("/warnaserror ");
278 if (options.WarningLevel >= 0)
279 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
281 if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
282 string extension = (options.GenerateExecutable ? "exe" : "dll");
283 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
284 !options.GenerateInMemory);
286 args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
288 foreach (string import in options.ReferencedAssemblies) {
289 if (import == null || import.Length == 0)
292 args.AppendFormat("/r:\"{0}\" ",import);
295 if (options.CompilerOptions != null) {
296 args.Append (options.CompilerOptions);
301 foreach (string embeddedResource in options.EmbeddedResources) {
302 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
305 foreach (string linkedResource in options.LinkedResources) {
306 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
309 if (providerOptions != null && providerOptions.Count > 0) {
312 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
315 if (langver.Length >= 1 && langver [0] == 'v')
316 langver = langver.Substring (1);
318 // NOTE: when -langversion:linq becomes obsolete/default, the code
319 // below must be changed!
322 // current default, omit the switch
326 args.Append ("/langversion:linq");
332 args.Append (" -- ");
333 foreach (string source in fileNames)
334 args.AppendFormat("\"{0}\" ",source);
335 return args.ToString();
337 private static CompilerError CreateErrorFromString(string error_string)
340 if (error_string.StartsWith ("BETA"))
343 if (error_string == null || error_string == "")
346 CompilerError error=new CompilerError();
347 Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
348 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
349 Match match=reg.Match(error_string);
350 if (!match.Success) {
351 // We had some sort of runtime crash
352 error.ErrorText = error_string;
353 error.IsWarning = false;
354 error.ErrorNumber = "";
357 if (String.Empty != match.Result("${file}"))
358 error.FileName=match.Result("${file}");
359 if (String.Empty != match.Result("${line}"))
360 error.Line=Int32.Parse(match.Result("${line}"));
361 if (String.Empty != match.Result("${column}"))
362 error.Column=Int32.Parse(match.Result("${column}"));
364 string level = match.Result ("${level}");
365 if (level == "warning")
366 error.IsWarning = true;
367 else if (level != "error")
368 return null; // error CS8028 will confuse the regex.
370 error.ErrorNumber=match.Result("${number}");
371 error.ErrorText=match.Result("${message}");
375 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
377 return temp_files.AddExtension (extension, keepFile);
380 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
382 return temp_files.AddExtension (extension);
385 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
387 if (options == null) {
388 throw new ArgumentNullException ("options");
392 throw new ArgumentNullException ("ea");
395 string[] fileNames = new string[ea.Length];
396 StringCollection assemblies = options.ReferencedAssemblies;
398 for (int i = 0; i < ea.Length; i++) {
399 CodeCompileUnit compileUnit = ea[i];
400 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
401 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
402 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
403 if (compileUnit.ReferencedAssemblies != null) {
404 foreach (string str in compileUnit.ReferencedAssemblies) {
405 if (!assemblies.Contains (str))
406 assemblies.Add (str);
410 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
414 return CompileAssemblyFromFileBatch (options, fileNames);
417 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
419 if (options == null) {
420 throw new ArgumentNullException ("options");
423 if (sources == null) {
424 throw new ArgumentNullException ("sources");
427 string[] fileNames = new string[sources.Length];
429 for (int i = 0; i < sources.Length; i++) {
430 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
431 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
432 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
433 s.Write (sources[i]);
438 return CompileFromFileBatch (options, fileNames);