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;
210 string mono_inside_mdb = null;
215 mono_inside_mdb = Environment.GetEnvironmentVariable ("MONO_INSIDE_MDB");
216 if (mono_inside_mdb != null) {
217 if (mono_inside_mdb.Length == 0)
218 mono_inside_mdb = "1";
219 Environment.SetEnvironmentVariable ("MONO_INSIDE_MDB", null);
224 // If there are a few kB in stdout, we might lock
225 mcs_output=mcs.StandardError.ReadToEnd();
226 mcs_stdout=mcs.StandardOutput.ReadToEnd ();
228 results.NativeCompilerReturnValue = mcs.ExitCode;
232 if (mono_inside_mdb != null)
233 Environment.SetEnvironmentVariable ("MONO_INSIDE_MDB", mono_inside_mdb);
236 mcs_output_lines=mcs_output.Split(
237 System.Environment.NewLine.ToCharArray());
239 foreach (string error_line in mcs_output_lines)
241 CompilerError error=CreateErrorFromString(error_line);
244 results.Errors.Add(error);
245 if (!error.IsWarning) loadIt=false;
249 if (!File.Exists (options.OutputAssembly)) {
250 throw new Exception ("Compiler failed to produce the assembly. Stderr='"
251 +mcs_output+"', Stdout='"+mcs_stdout+"'");
253 if (options.GenerateInMemory) {
254 using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
255 byte[] buffer = new byte[fs.Length];
256 fs.Read(buffer, 0, buffer.Length);
257 results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
261 // Avoid setting CompiledAssembly right now since the output might be a netmodule
262 results.PathToAssembly = options.OutputAssembly;
265 results.CompiledAssembly = null;
272 private static string BuildArgs(CompilerParameters options,string[] fileNames, Dictionary <string, string> providerOptions)
274 private static string BuildArgs(CompilerParameters options,string[] fileNames)
277 StringBuilder args=new StringBuilder();
278 if (options.GenerateExecutable)
279 args.Append("/target:exe ");
281 args.Append("/target:library ");
283 if (options.Win32Resource != null)
284 args.AppendFormat("/win32res:\"{0}\" ",
285 options.Win32Resource);
287 if (options.IncludeDebugInformation)
288 args.Append("/debug+ /optimize- ");
290 args.Append("/debug- /optimize+ ");
292 if (options.TreatWarningsAsErrors)
293 args.Append("/warnaserror ");
295 if (options.WarningLevel >= 0)
296 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
298 if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
299 string extension = (options.GenerateExecutable ? "exe" : "dll");
300 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
301 !options.GenerateInMemory);
303 args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
305 foreach (string import in options.ReferencedAssemblies) {
306 if (import == null || import.Length == 0)
309 args.AppendFormat("/r:\"{0}\" ",import);
312 if (options.CompilerOptions != null) {
313 args.Append (options.CompilerOptions);
318 foreach (string embeddedResource in options.EmbeddedResources) {
319 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
322 foreach (string linkedResource in options.LinkedResources) {
323 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
326 if (providerOptions != null && providerOptions.Count > 0) {
329 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
332 if (langver.Length >= 1 && langver [0] == 'v')
333 langver = langver.Substring (1);
337 args.Append ("/langversion:ISO-2");
341 // current default, omit the switch
347 args.Append (" -- ");
348 foreach (string source in fileNames)
349 args.AppendFormat("\"{0}\" ",source);
350 return args.ToString();
352 private static CompilerError CreateErrorFromString(string error_string)
355 if (error_string.StartsWith ("BETA"))
358 if (error_string == null || error_string == "")
361 CompilerError error=new CompilerError();
362 Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
363 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
364 Match match=reg.Match(error_string);
365 if (!match.Success) {
366 // We had some sort of runtime crash
367 error.ErrorText = error_string;
368 error.IsWarning = false;
369 error.ErrorNumber = "";
372 if (String.Empty != match.Result("${file}"))
373 error.FileName=match.Result("${file}");
374 if (String.Empty != match.Result("${line}"))
375 error.Line=Int32.Parse(match.Result("${line}"));
376 if (String.Empty != match.Result("${column}"))
377 error.Column=Int32.Parse(match.Result("${column}"));
379 string level = match.Result ("${level}");
380 if (level == "warning")
381 error.IsWarning = true;
382 else if (level != "error")
383 return null; // error CS8028 will confuse the regex.
385 error.ErrorNumber=match.Result("${number}");
386 error.ErrorText=match.Result("${message}");
390 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
392 return temp_files.AddExtension (extension, keepFile);
395 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
397 return temp_files.AddExtension (extension);
400 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
402 if (options == null) {
403 throw new ArgumentNullException ("options");
407 throw new ArgumentNullException ("ea");
410 string[] fileNames = new string[ea.Length];
411 StringCollection assemblies = options.ReferencedAssemblies;
413 for (int i = 0; i < ea.Length; i++) {
414 CodeCompileUnit compileUnit = ea[i];
415 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
416 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
417 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
418 if (compileUnit.ReferencedAssemblies != null) {
419 foreach (string str in compileUnit.ReferencedAssemblies) {
420 if (!assemblies.Contains (str))
421 assemblies.Add (str);
425 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
429 return CompileAssemblyFromFileBatch (options, fileNames);
432 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
434 if (options == null) {
435 throw new ArgumentNullException ("options");
438 if (sources == null) {
439 throw new ArgumentNullException ("sources");
442 string[] fileNames = new string[sources.Length];
444 for (int i = 0; i < sources.Length; i++) {
445 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
446 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
447 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
448 s.Write (sources[i]);
453 return CompileFromFileBatch (options, fileNames);