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;
38 using System.ComponentModel;
41 using System.Reflection;
42 using System.Collections;
43 using System.Collections.Specialized;
44 using System.Diagnostics;
45 using System.Text.RegularExpressions;
47 namespace Microsoft.VisualBasic
49 internal class VBCodeCompiler : VBCodeGenerator, ICodeCompiler
51 static string windowsMonoPath;
52 static string windowsvbncPath;
53 static string unixVbncCommand;
55 static VBCodeCompiler ()
57 if (Path.DirectorySeparatorChar == '\\') {
58 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
59 MethodInfo get_gac = gac.GetGetMethod (true);
60 string p = Path.GetDirectoryName (
61 (string) get_gac.Invoke (null, null));
62 windowsMonoPath = Path.Combine (
63 Path.GetDirectoryName (
64 Path.GetDirectoryName (p)),
66 if (!File.Exists (windowsMonoPath))
67 windowsMonoPath = Path.Combine (
68 Path.GetDirectoryName (
69 Path.GetDirectoryName (p)),
72 Path.Combine (p, "2.0\\vbnc.exe");
74 var mscorlibPath = new Uri (typeof (object).Assembly.CodeBase).LocalPath;
75 var unixMcsPath = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "vbnc"));
76 if (File.Exists (unixMcsPath))
77 unixVbncCommand = unixMcsPath;
79 unixVbncCommand = "vbnc";
83 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
85 return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
88 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
90 if (options == null) {
91 throw new ArgumentNullException ("options");
95 return CompileFromDomBatch (options, ea);
97 options.TempFiles.Delete ();
101 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
103 return CompileAssemblyFromFileBatch (options, new string[] { fileName });
106 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
108 if (options == null) {
109 throw new ArgumentNullException ("options");
113 return CompileFromFileBatch (options, fileNames);
115 options.TempFiles.Delete ();
119 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
121 return CompileAssemblyFromSourceBatch (options, new string[] { source });
124 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
126 if (options == null) {
127 throw new ArgumentNullException ("options");
131 return CompileFromSourceBatch (options, sources);
133 options.TempFiles.Delete ();
137 static string BuildArgs (CompilerParameters options, string[] fileNames)
139 StringBuilder args = new StringBuilder ();
140 args.Append ("/quiet ");
141 if (options.GenerateExecutable)
142 args.Append ("/target:exe ");
144 args.Append ("/target:library ");
146 /* Disabled. It causes problems now. -- Gonzalo
147 if (options.IncludeDebugInformation)
148 args.AppendFormat("/debug ");
151 if (options.TreatWarningsAsErrors)
152 args.Append ("/warnaserror ");
154 /* Disabled. vbnc does not support warninglevels.
155 if (options.WarningLevel != -1)
156 args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
159 if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
160 string ext = (options.GenerateExecutable ? "exe" : "dll");
161 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext, !options.GenerateInMemory);
164 args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
166 bool Reference2MSVBFound;
167 Reference2MSVBFound = false;
168 if (null != options.ReferencedAssemblies) {
169 foreach (string import in options.ReferencedAssemblies) {
170 if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
171 Reference2MSVBFound = true;
172 args.AppendFormat ("/r:\"{0}\" ", import);
176 // add standard import to Microsoft.VisualBasic if missing
177 if (!Reference2MSVBFound)
178 args.Append ("/r:\"Microsoft.VisualBasic.dll\" ");
180 if (options.CompilerOptions != null) {
181 args.Append (options.CompilerOptions);
184 /* Disabled, vbnc does not support this.
185 args.Append (" -- "); // makes vbnc not try to process filenames as options
187 foreach (string source in fileNames)
188 args.AppendFormat (" \"{0}\" ", source);
190 return args.ToString ();
193 static CompilerError CreateErrorFromString (string error_string)
195 CompilerError error = new CompilerError ();
196 Regex reg = new Regex (@"^(\s*(?<file>.*)?\((?<line>\d*)(,(?<column>\d*))?\)\s+)?:\s*" +
197 @"(?<level>Error|Warning)?\s*(?<number>.*):\s(?<message>.*)",
198 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
200 Match match = reg.Match (error_string);
201 if (!match.Success) {
205 if (String.Empty != match.Result ("${file}"))
206 error.FileName = match.Result ("${file}").Trim ();
208 if (String.Empty != match.Result ("${line}"))
209 error.Line = Int32.Parse (match.Result ("${line}"));
211 if (String.Empty != match.Result ("${column}"))
212 error.Column = Int32.Parse (match.Result ("${column}"));
214 if (match.Result ("${level}").Trim () == "Warning")
215 error.IsWarning = true;
217 error.ErrorNumber = match.Result ("${number}");
218 error.ErrorText = match.Result ("${message}");
223 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
225 return temp_files.AddExtension (extension, keepFile);
228 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
230 return temp_files.AddExtension (extension);
233 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
236 if (options == null) {
237 throw new ArgumentNullException ("options");
240 if (fileNames == null) {
241 throw new ArgumentNullException ("fileNames");
244 CompilerResults results = new CompilerResults (options.TempFiles);
245 Process vbnc = new Process ();
247 string vbnc_output = "";
248 string[] vbnc_output_lines;
249 // FIXME: these lines had better be platform independent.
250 if (Path.DirectorySeparatorChar == '\\') {
251 vbnc.StartInfo.FileName = windowsMonoPath;
252 vbnc.StartInfo.Arguments = windowsvbncPath + ' ' + BuildArgs (options, fileNames);
254 vbnc.StartInfo.FileName = "vbnc";
255 vbnc.StartInfo.Arguments = BuildArgs (options, fileNames);
257 //Console.WriteLine (vbnc.StartInfo.Arguments);
258 vbnc.StartInfo.CreateNoWindow = true;
259 vbnc.StartInfo.UseShellExecute = false;
260 vbnc.StartInfo.RedirectStandardOutput = true;
263 } catch (Exception e) {
264 Win32Exception exc = e as Win32Exception;
266 throw new SystemException (String.Format ("Error running {0}: {1}", vbnc.StartInfo.FileName,
267 Win32Exception.W32ErrorMessage (exc.NativeErrorCode)));
273 vbnc_output = vbnc.StandardOutput.ReadToEnd ();
276 results.NativeCompilerReturnValue = vbnc.ExitCode;
281 if (results.NativeCompilerReturnValue == 1) {
283 vbnc_output_lines = vbnc_output.Split (Environment.NewLine.ToCharArray ());
284 foreach (string error_line in vbnc_output_lines) {
285 CompilerError error = CreateErrorFromString (error_line);
287 results.Errors.Add (error);
292 if ((loadIt == false && !results.Errors.HasErrors) // Failed, but no errors? Probably couldn't parse the compiler output correctly.
293 || (results.NativeCompilerReturnValue != 0 && results.NativeCompilerReturnValue != 1)) // Neither success (0), nor failure (1), so it crashed.
295 // Show the entire output as one big error message.
297 CompilerError error = new CompilerError (string.Empty, 0, 0, "VBNC_CRASH", vbnc_output);
298 results.Errors.Add (error);
302 if (options.GenerateInMemory) {
303 using (FileStream fs = File.OpenRead (options.OutputAssembly)) {
304 byte[] buffer = new byte[fs.Length];
305 fs.Read (buffer, 0, buffer.Length);
306 results.CompiledAssembly = Assembly.Load (buffer, null);
310 results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
311 results.PathToAssembly = options.OutputAssembly;
314 results.CompiledAssembly = null;
320 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
322 if (options == null) {
323 throw new ArgumentNullException ("options");
327 throw new ArgumentNullException ("ea");
330 string[] fileNames = new string[ea.Length];
331 StringCollection assemblies = options.ReferencedAssemblies;
333 for (int i = 0; i < ea.Length; i++) {
334 CodeCompileUnit compileUnit = ea[i];
335 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
336 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
337 StreamWriter s = new StreamWriter (f);
338 if (compileUnit.ReferencedAssemblies != null) {
339 foreach (string str in compileUnit.ReferencedAssemblies) {
340 if (!assemblies.Contains (str))
341 assemblies.Add (str);
345 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
349 return CompileAssemblyFromFileBatch (options, fileNames);
352 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
354 if (options == null) {
355 throw new ArgumentNullException ("options");
358 if (sources == null) {
359 throw new ArgumentNullException ("sources");
362 string[] fileNames = new string[sources.Length];
364 for (int i = 0; i < sources.Length; i++) {
365 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
366 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
367 using (StreamWriter s = new StreamWriter (f)) {
368 s.Write (sources[i]);
373 return CompileFromFileBatch (options, fileNames);