2 // Microsoft VisualBasic VBCodeCompiler Class implementation
5 // Jochen Wezel (jwezel@compumaster.de)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // (c) 2003 Jochen Wezel (http://www.compumaster.de)
9 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
12 // 2003-11-28 JW: create reference to Microsoft.VisualBasic if not explicitly done
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 using System.CodeDom.Compiler;
40 using System.Reflection;
41 using System.Collections;
42 using System.Collections.Specialized;
43 using System.Diagnostics;
44 using System.Text.RegularExpressions;
46 namespace Microsoft.VisualBasic
48 internal class VBCodeCompiler : VBCodeGenerator, ICodeCompiler
50 static string windowsMonoPath;
51 static string windowsMbasPath;
52 static VBCodeCompiler ()
54 if (Path.DirectorySeparatorChar == '\\') {
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)),
70 Path.Combine (p, "2.0\\mbas.exe");
73 Path.Combine (p, "1.0\\mbas.exe");
78 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
80 return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
83 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
85 if (options == null) {
86 throw new ArgumentNullException ("options");
90 return CompileFromDomBatch (options, ea);
92 options.TempFiles.Delete ();
96 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
98 return CompileAssemblyFromFileBatch (options, new string[] { fileName });
101 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
103 if (options == null) {
104 throw new ArgumentNullException ("options");
108 return CompileFromFileBatch (options, fileNames);
110 options.TempFiles.Delete ();
114 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
116 return CompileAssemblyFromSourceBatch (options, new string[] { source });
119 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
121 if (options == null) {
122 throw new ArgumentNullException ("options");
126 return CompileFromSourceBatch (options, sources);
128 options.TempFiles.Delete ();
132 static string BuildArgs (CompilerParameters options, string[] fileNames)
134 StringBuilder args = new StringBuilder ();
135 args.Append ("/quiet ");
136 if (options.GenerateExecutable)
137 args.Append ("/target:exe ");
139 args.Append ("/target:library ");
141 /* Disabled. It causes problems now. -- Gonzalo
142 if (options.IncludeDebugInformation)
143 args.AppendFormat("/debug ");
146 if (options.TreatWarningsAsErrors)
147 args.Append ("/warnaserror ");
149 if (options.WarningLevel != -1)
150 args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
152 if (options.OutputAssembly == null) {
153 string ext = (options.GenerateExecutable ? "exe" : "dll");
154 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext, !options.GenerateInMemory);
157 args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
159 bool Reference2MSVBFound;
160 Reference2MSVBFound = false;
161 if (null != options.ReferencedAssemblies) {
162 foreach (string import in options.ReferencedAssemblies) {
163 if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
164 Reference2MSVBFound = true;
165 args.AppendFormat ("/r:\"{0}\" ", import);
169 // add standard import to Microsoft.VisualBasic if missing
170 if (!Reference2MSVBFound)
171 args.Append ("/r:\"Microsoft.VisualBasic\" ");
173 if (options.CompilerOptions != null) {
174 args.Append (options.CompilerOptions);
177 args.Append (" -- "); // makes mbas not try to process filenames as options
179 foreach (string source in fileNames)
180 args.AppendFormat ("\"{0}\" ", source);
182 return args.ToString ();
185 static CompilerError CreateErrorFromString (string error_string)
187 // When IncludeDebugInformation is true, prevents the debug symbols stats from braeking this.
188 if (error_string.StartsWith ("WROTE SYMFILE") || error_string.StartsWith ("OffsetTable"))
191 CompilerError error = new CompilerError ();
192 Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)\s+)*" +
193 @"(?<level>error|warning)\s*(?<number>.*):\s(?<message>.*)",
194 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
196 Match match = reg.Match (error_string);
200 if (String.Empty != match.Result ("${file}"))
201 error.FileName = match.Result ("${file}");
203 if (String.Empty != match.Result ("${line}"))
204 error.Line = Int32.Parse (match.Result ("${line}"));
206 if (String.Empty != match.Result ("${column}"))
207 error.Column = Int32.Parse (match.Result ("${column}"));
209 if (match.Result ("${level}") == "warning")
210 error.IsWarning = true;
212 error.ErrorNumber = match.Result ("${number}");
213 error.ErrorText = match.Result ("${message}");
217 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
219 return temp_files.AddExtension (extension, keepFile);
222 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
224 return temp_files.AddExtension (extension);
227 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
229 if (options == null) {
230 throw new ArgumentNullException ("options");
233 if (fileNames == null) {
234 throw new ArgumentNullException ("fileNames");
237 CompilerResults results = new CompilerResults (options.TempFiles);
238 Process mbas = new Process ();
241 string[] mbas_output_lines;
242 // FIXME: these lines had better be platform independent.
243 if (Path.DirectorySeparatorChar == '\\') {
244 mbas.StartInfo.FileName = windowsMonoPath;
245 mbas.StartInfo.Arguments = windowsMbasPath + ' ' + BuildArgs (options, fileNames);
247 mbas.StartInfo.FileName = "mbas";
248 mbas.StartInfo.Arguments = BuildArgs (options, fileNames);
250 mbas.StartInfo.CreateNoWindow = true;
251 mbas.StartInfo.UseShellExecute = false;
252 mbas.StartInfo.RedirectStandardOutput = true;
255 mbas_output = mbas.StandardOutput.ReadToEnd ();
258 results.NativeCompilerReturnValue = mbas.ExitCode;
262 mbas_output_lines = mbas_output.Split (Environment.NewLine.ToCharArray ());
264 foreach (string error_line in mbas_output_lines) {
265 CompilerError error = CreateErrorFromString (error_line);
267 results.Errors.Add (error);
268 if (!error.IsWarning)
274 if (options.GenerateInMemory) {
275 using (FileStream fs = File.OpenRead (options.OutputAssembly)) {
276 byte[] buffer = new byte[fs.Length];
277 fs.Read (buffer, 0, buffer.Length);
278 results.CompiledAssembly = Assembly.Load (buffer, null, options.Evidence);
282 results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
283 results.PathToAssembly = options.OutputAssembly;
286 results.CompiledAssembly = null;
292 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
294 if (options == null) {
295 throw new ArgumentNullException ("options");
299 throw new ArgumentNullException ("ea");
302 string[] fileNames = new string[ea.Length];
303 StringCollection assemblies = options.ReferencedAssemblies;
305 for (int i = 0; i < ea.Length; i++) {
306 CodeCompileUnit compileUnit = ea[i];
307 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
308 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
309 StreamWriter s = new StreamWriter (f);
310 if (compileUnit.ReferencedAssemblies != null) {
311 foreach (string str in compileUnit.ReferencedAssemblies) {
312 if (!assemblies.Contains (str))
313 assemblies.Add (str);
317 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
321 return CompileAssemblyFromFileBatch (options, fileNames);
324 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
326 if (options == null) {
327 throw new ArgumentNullException ("options");
330 if (sources == null) {
331 throw new ArgumentNullException ("sources");
334 string[] fileNames = new string[sources.Length];
336 for (int i = 0; i < sources.Length; i++) {
337 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
338 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
339 using (StreamWriter s = new StreamWriter (f)) {
340 s.Write (sources[i]);
345 return CompileFromFileBatch (options, fileNames);