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;
45 internal class CSharpCodeCompiler : CSharpCodeGenerator, ICodeCompiler
47 static string windowsMcsPath;
48 static string windowsMonoPath;
50 static CSharpCodeCompiler ()
52 if (Path.DirectorySeparatorChar == '\\') {
53 // FIXME: right now we use "fixed" version 1.0
55 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
56 MethodInfo get_gac = gac.GetGetMethod (true);
57 string p = Path.GetDirectoryName (
58 (string) get_gac.Invoke (null, null));
59 windowsMonoPath = Path.Combine (
60 Path.GetDirectoryName (
61 Path.GetDirectoryName (p)),
63 if (!File.Exists (windowsMonoPath))
64 windowsMonoPath = Path.Combine (
65 Path.GetDirectoryName (
66 Path.GetDirectoryName (p)),
69 Path.Combine (p, "1.0\\mcs.exe");
76 public CSharpCodeCompiler()
84 public CompilerResults CompileAssemblyFromDom (
85 CompilerParameters options,CodeCompileUnit e)
87 return CompileAssemblyFromDomBatch(options,new CodeCompileUnit[]{e});
89 public CompilerResults CompileAssemblyFromDomBatch (
90 CompilerParameters options,CodeCompileUnit[] ea)
92 string[] fileNames=new string[ea.Length];
95 options = new CompilerParameters ();
97 StringCollection assemblies = options.ReferencedAssemblies;
99 foreach (CodeCompileUnit e in ea) {
100 fileNames [i] = GetTempFileNameWithExtension (options.TempFiles, "cs");
101 FileStream f=new FileStream(fileNames[i],FileMode.OpenOrCreate);
102 StreamWriter s=new StreamWriter(f, Encoding.UTF8);
103 if (e.ReferencedAssemblies != null) {
104 foreach (string str in e.ReferencedAssemblies) {
105 if (!assemblies.Contains (str))
106 assemblies.Add (str);
110 ((ICodeGenerator)this).GenerateCodeFromCompileUnit (e, s, new CodeGeneratorOptions());
115 return CompileAssemblyFromFileBatch (options, fileNames);
118 public CompilerResults CompileAssemblyFromFile (
119 CompilerParameters options,string fileName)
121 return CompileAssemblyFromFileBatch (options, new string []{fileName});
124 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
127 throw new ArgumentNullException("options");
128 if (null == fileNames)
129 throw new ArgumentNullException("fileNames");
131 CompilerResults results=new CompilerResults(options.TempFiles);
132 Process mcs=new Process();
135 string[] mcs_output_lines;
136 // FIXME: these lines had better be platform independent.
137 if (Path.DirectorySeparatorChar == '\\') {
138 mcs.StartInfo.FileName = windowsMonoPath;
139 mcs.StartInfo.Arguments = windowsMcsPath + ' ' + BuildArgs (options, fileNames);
142 mcs.StartInfo.FileName="mcs";
143 mcs.StartInfo.Arguments=BuildArgs(options,fileNames);
145 mcs.StartInfo.CreateNoWindow=true;
146 mcs.StartInfo.UseShellExecute=false;
147 mcs.StartInfo.RedirectStandardOutput=true;
150 mcs_output=mcs.StandardOutput.ReadToEnd();
153 results.NativeCompilerReturnValue = mcs.ExitCode;
156 mcs_output_lines=mcs_output.Split(
157 System.Environment.NewLine.ToCharArray());
159 foreach (string error_line in mcs_output_lines)
161 CompilerError error=CreateErrorFromString(error_line);
164 results.Errors.Add(error);
165 if (!error.IsWarning) loadIt=false;
169 results.CompiledAssembly=Assembly.LoadFrom(options.OutputAssembly);
171 results.CompiledAssembly=null;
175 public CompilerResults CompileAssemblyFromSource (
176 CompilerParameters options,string source)
178 return CompileAssemblyFromSourceBatch(options,new string[]{source});
180 public CompilerResults CompileAssemblyFromSourceBatch (
181 CompilerParameters options,string[] sources)
183 string[] fileNames=new string[sources.Length];
185 foreach (string source in sources) {
186 fileNames [i] = GetTempFileNameWithExtension (options.TempFiles, "cs");
187 FileStream f=new FileStream(fileNames[i],FileMode.OpenOrCreate);
188 StreamWriter s=new StreamWriter(f);
194 return CompileAssemblyFromFileBatch (options, fileNames);
196 private static string BuildArgs(
197 CompilerParameters options,string[] fileNames)
199 StringBuilder args=new StringBuilder();
200 if (options.GenerateExecutable)
201 args.AppendFormat("/target:exe ");
203 args.AppendFormat("/target:library ");
204 if (options.IncludeDebugInformation)
205 args.AppendFormat("/debug ");
206 if (options.TreatWarningsAsErrors)
207 args.AppendFormat("/warnaserror ");
209 if (options.WarningLevel != -1)
210 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
212 if (options.OutputAssembly==null)
213 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, "dll");
214 args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
215 if (null != options.ReferencedAssemblies)
217 foreach (string import in options.ReferencedAssemblies)
218 args.AppendFormat("/r:\"{0}\" ",import);
221 args.Append (" -- ");
222 foreach (string source in fileNames)
223 args.AppendFormat("\"{0}\" ",source);
224 return args.ToString();
226 private static CompilerError CreateErrorFromString(string error_string)
228 // When IncludeDebugInformation is true, prevents the debug symbols stats from braeking this.
229 if (error_string.StartsWith ("WROTE SYMFILE") || error_string.StartsWith ("OffsetTable"))
232 CompilerError error=new CompilerError();
233 Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
234 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
235 Match match=reg.Match(error_string);
236 if (!match.Success) return null;
237 if (String.Empty != match.Result("${file}"))
238 error.FileName=match.Result("${file}");
239 if (String.Empty != match.Result("${line}"))
240 error.Line=Int32.Parse(match.Result("${line}"));
241 if (String.Empty != match.Result("${column}"))
242 error.Column=Int32.Parse(match.Result("${column}"));
243 if (match.Result("${level}")=="warning")
244 error.IsWarning=true;
245 error.ErrorNumber=match.Result("${number}");
246 error.ErrorText=match.Result("${message}");
250 static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
252 return temp_files.AddExtension (extension);