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 // FIXME: right now we use "fixed" version 1.0
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)),
71 Path.Combine (p, "1.0\\mbas.exe");
75 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
77 return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
80 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
82 if (options == null) {
83 throw new ArgumentNullException ("options");
87 return CompileFromDomBatch (options, ea);
89 options.TempFiles.Delete ();
93 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
95 return CompileAssemblyFromFileBatch (options, new string[] { fileName });
98 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
100 if (options == null) {
101 throw new ArgumentNullException ("options");
105 return CompileFromFileBatch (options, fileNames);
107 options.TempFiles.Delete ();
111 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
113 return CompileAssemblyFromSourceBatch (options, new string[] { source });
116 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
118 if (options == null) {
119 throw new ArgumentNullException ("options");
123 return CompileFromSourceBatch (options, sources);
125 options.TempFiles.Delete ();
129 static string BuildArgs (CompilerParameters options, string[] fileNames)
131 StringBuilder args = new StringBuilder ();
132 args.AppendFormat ("/quiet ");
133 if (options.GenerateExecutable)
134 args.AppendFormat ("/target:exe ");
136 args.AppendFormat ("/target:library ");
138 /* Disabled. It causes problems now. -- Gonzalo
139 if (options.IncludeDebugInformation)
140 args.AppendFormat("/debug ");
143 if (options.TreatWarningsAsErrors)
144 args.AppendFormat ("/warnaserror ");
146 if (options.WarningLevel != -1)
147 args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
149 if (options.OutputAssembly == null) {
150 string ext = (options.GenerateExecutable ? "exe" : "dll");
151 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext, !options.GenerateInMemory);
154 args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
156 bool Reference2MSVBFound;
157 Reference2MSVBFound = false;
158 if (null != options.ReferencedAssemblies) {
159 foreach (string import in options.ReferencedAssemblies) {
160 if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
161 Reference2MSVBFound = true;
162 args.AppendFormat ("/r:\"{0}\" ", import);
165 // add standard import to Microsoft.VisualBasic if missing
166 if (!Reference2MSVBFound)
167 args.AppendFormat ("/r:\"{0}\" ", "Microsoft.VisualBasic");
169 args.AppendFormat (" -- "); // makes mbas not try to process filenames as options
171 foreach (string source in fileNames)
172 args.AppendFormat ("\"{0}\" ", source);
174 return args.ToString ();
177 static CompilerError CreateErrorFromString (string error_string)
179 // When IncludeDebugInformation is true, prevents the debug symbols stats from braeking this.
180 if (error_string.StartsWith ("WROTE SYMFILE") || error_string.StartsWith ("OffsetTable"))
183 CompilerError error = new CompilerError ();
184 Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)\s+)*" +
185 @"(?<level>error|warning)\s*(?<number>.*):\s(?<message>.*)",
186 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
188 Match match = reg.Match (error_string);
192 if (String.Empty != match.Result ("${file}"))
193 error.FileName = match.Result ("${file}");
195 if (String.Empty != match.Result ("${line}"))
196 error.Line = Int32.Parse (match.Result ("${line}"));
198 if (String.Empty != match.Result ("${column}"))
199 error.Column = Int32.Parse (match.Result ("${column}"));
201 if (match.Result ("${level}") == "warning")
202 error.IsWarning = true;
204 error.ErrorNumber = match.Result ("${number}");
205 error.ErrorText = match.Result ("${message}");
209 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
211 return temp_files.AddExtension (extension, keepFile);
214 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
216 return temp_files.AddExtension (extension);
219 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
221 if (options == null) {
222 throw new ArgumentNullException ("options");
225 if (fileNames == null) {
226 throw new ArgumentNullException ("fileNames");
229 CompilerResults results = new CompilerResults (options.TempFiles);
230 Process mbas = new Process ();
233 string[] mbas_output_lines;
234 // FIXME: these lines had better be platform independent.
235 if (Path.DirectorySeparatorChar == '\\') {
236 mbas.StartInfo.FileName = windowsMonoPath;
237 mbas.StartInfo.Arguments = windowsMbasPath + ' ' + BuildArgs (options, fileNames);
239 mbas.StartInfo.FileName = "mbas";
240 mbas.StartInfo.Arguments = BuildArgs (options, fileNames);
242 mbas.StartInfo.CreateNoWindow = true;
243 mbas.StartInfo.UseShellExecute = false;
244 mbas.StartInfo.RedirectStandardOutput = true;
247 mbas_output = mbas.StandardOutput.ReadToEnd ();
250 results.NativeCompilerReturnValue = mbas.ExitCode;
254 mbas_output_lines = mbas_output.Split (Environment.NewLine.ToCharArray ());
256 foreach (string error_line in mbas_output_lines) {
257 CompilerError error = CreateErrorFromString (error_line);
259 results.Errors.Add (error);
260 if (!error.IsWarning)
266 if (options.GenerateInMemory) {
267 using (FileStream fs = File.OpenRead (options.OutputAssembly)) {
268 byte[] buffer = new byte[fs.Length];
269 fs.Read (buffer, 0, buffer.Length);
270 results.CompiledAssembly = Assembly.Load (buffer, null, options.Evidence);
274 results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
275 results.PathToAssembly = options.OutputAssembly;
278 results.CompiledAssembly = null;
284 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
286 if (options == null) {
287 throw new ArgumentNullException ("options");
291 throw new ArgumentNullException ("ea");
294 string[] fileNames = new string[ea.Length];
295 StringCollection assemblies = options.ReferencedAssemblies;
297 for (int i = 0; i < ea.Length; i++) {
298 CodeCompileUnit compileUnit = ea[i];
299 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
300 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
301 StreamWriter s = new StreamWriter (f);
302 if (compileUnit.ReferencedAssemblies != null) {
303 foreach (string str in compileUnit.ReferencedAssemblies) {
304 if (!assemblies.Contains (str))
305 assemblies.Add (str);
309 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
313 return CompileAssemblyFromFileBatch (options, fileNames);
316 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
318 if (options == null) {
319 throw new ArgumentNullException ("options");
322 if (sources == null) {
323 throw new ArgumentNullException ("sources");
326 string[] fileNames = new string[sources.Length];
328 for (int i = 0; i < sources.Length; i++) {
329 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
330 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
331 using (StreamWriter s = new StreamWriter (f)) {
332 s.Write (sources[i]);
337 return CompileFromFileBatch (options, fileNames);