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;
52 static string windowsvbncPath;
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)),
73 Path.Combine (p, "2.0\\vbnc.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 ();
133 static string BuildArgs (CompilerParameters options, string[] fileNames)
135 StringBuilder args = new StringBuilder ();
136 args.Append ("/quiet ");
137 if (options.GenerateExecutable)
138 args.Append ("/target:exe ");
140 args.Append ("/target:library ");
142 /* Disabled. It causes problems now. -- Gonzalo
143 if (options.IncludeDebugInformation)
144 args.AppendFormat("/debug ");
147 if (options.TreatWarningsAsErrors)
148 args.Append ("/warnaserror ");
150 /* Disabled. vbnc does not support warninglevels.
151 if (options.WarningLevel != -1)
152 args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
155 if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
156 string ext = (options.GenerateExecutable ? "exe" : "dll");
157 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext, !options.GenerateInMemory);
160 args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
162 bool Reference2MSVBFound;
163 Reference2MSVBFound = false;
164 if (null != options.ReferencedAssemblies) {
165 foreach (string import in options.ReferencedAssemblies) {
166 if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
167 Reference2MSVBFound = true;
168 args.AppendFormat ("/r:\"{0}\" ", import);
172 // add standard import to Microsoft.VisualBasic if missing
173 if (!Reference2MSVBFound)
174 args.Append ("/r:\"Microsoft.VisualBasic.dll\" ");
176 if (options.CompilerOptions != null) {
177 args.Append (options.CompilerOptions);
180 /* Disabled, vbnc does not support this.
181 args.Append (" -- "); // makes vbnc not try to process filenames as options
183 foreach (string source in fileNames)
184 args.AppendFormat (" \"{0}\" ", source);
186 return args.ToString ();
189 static CompilerError CreateErrorFromString (string error_string)
191 CompilerError error = new CompilerError ();
192 Regex reg = new Regex (@"^(\s*(?<file>.*)?\((?<line>\d*)(,(?<column>\d*))?\)\s+)?:\s*" +
193 @"(?<level>Error|Warning)?\s*(?<number>.*):\s(?<message>.*)",
194 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
196 Match match = reg.Match (error_string);
197 if (!match.Success) {
201 if (String.Empty != match.Result ("${file}"))
202 error.FileName = match.Result ("${file}").Trim ();
204 if (String.Empty != match.Result ("${line}"))
205 error.Line = Int32.Parse (match.Result ("${line}"));
207 if (String.Empty != match.Result ("${column}"))
208 error.Column = Int32.Parse (match.Result ("${column}"));
210 if (match.Result ("${level}").Trim () == "Warning")
211 error.IsWarning = true;
213 error.ErrorNumber = match.Result ("${number}");
214 error.ErrorText = match.Result ("${message}");
219 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
221 return temp_files.AddExtension (extension, keepFile);
225 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
227 return temp_files.AddExtension (extension);
230 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
234 throw new NotSupportedException (
235 @"Compilation of Visual Basic code is not supported for v1.0/v1.1 assemblies, please use the v2.0 assemblies.
236 - If this is a web application, use xsp2/mod_mono_server2 instead of xsp/mono_mono_server (see http://www.mono-project.com/Mod_mono#ASP.NET_2_apps_do_not_work).
237 - If this is a desktop application, use gmcs to compile your application instead of mcs.");
239 if (options == null) {
240 throw new ArgumentNullException ("options");
243 if (fileNames == null) {
244 throw new ArgumentNullException ("fileNames");
247 CompilerResults results = new CompilerResults (options.TempFiles);
248 Process vbnc = new Process ();
250 string vbnc_output = "";
251 string[] vbnc_output_lines;
252 // FIXME: these lines had better be platform independent.
253 if (Path.DirectorySeparatorChar == '\\') {
254 vbnc.StartInfo.FileName = windowsMonoPath;
255 vbnc.StartInfo.Arguments = windowsvbncPath + ' ' + BuildArgs (options, fileNames);
257 vbnc.StartInfo.FileName = "vbnc";
258 vbnc.StartInfo.Arguments = BuildArgs (options, fileNames);
260 //Console.WriteLine (vbnc.StartInfo.Arguments);
261 vbnc.StartInfo.CreateNoWindow = true;
262 vbnc.StartInfo.UseShellExecute = false;
263 vbnc.StartInfo.RedirectStandardOutput = true;
266 vbnc_output = vbnc.StandardOutput.ReadToEnd ();
269 results.NativeCompilerReturnValue = vbnc.ExitCode;
274 if (results.NativeCompilerReturnValue == 1) {
276 vbnc_output_lines = vbnc_output.Split (Environment.NewLine.ToCharArray ());
277 foreach (string error_line in vbnc_output_lines) {
278 CompilerError error = CreateErrorFromString (error_line);
280 results.Errors.Add (error);
285 if ((loadIt == false && !results.Errors.HasErrors) // Failed, but no errors? Probably couldn't parse the compiler output correctly.
286 || (results.NativeCompilerReturnValue != 0 && results.NativeCompilerReturnValue != 1)) // Neither success (0), nor failure (1), so it crashed.
288 // Show the entire output as one big error message.
290 CompilerError error = new CompilerError (string.Empty, 0, 0, "VBNC_CRASH", vbnc_output);
291 results.Errors.Add (error);
295 if (options.GenerateInMemory) {
296 using (FileStream fs = File.OpenRead (options.OutputAssembly)) {
297 byte[] buffer = new byte[fs.Length];
298 fs.Read (buffer, 0, buffer.Length);
299 results.CompiledAssembly = Assembly.Load (buffer, null, options.Evidence);
303 results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
304 results.PathToAssembly = options.OutputAssembly;
307 results.CompiledAssembly = null;
314 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
316 if (options == null) {
317 throw new ArgumentNullException ("options");
321 throw new ArgumentNullException ("ea");
324 string[] fileNames = new string[ea.Length];
325 StringCollection assemblies = options.ReferencedAssemblies;
327 for (int i = 0; i < ea.Length; i++) {
328 CodeCompileUnit compileUnit = ea[i];
329 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
330 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
331 StreamWriter s = new StreamWriter (f);
332 if (compileUnit.ReferencedAssemblies != null) {
333 foreach (string str in compileUnit.ReferencedAssemblies) {
334 if (!assemblies.Contains (str))
335 assemblies.Add (str);
339 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
343 return CompileAssemblyFromFileBatch (options, fileNames);
346 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
348 if (options == null) {
349 throw new ArgumentNullException ("options");
352 if (sources == null) {
353 throw new ArgumentNullException ("sources");
356 string[] fileNames = new string[sources.Length];
358 for (int i = 0; i < sources.Length; i++) {
359 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
360 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
361 using (StreamWriter s = new StreamWriter (f)) {
362 s.Write (sources[i]);
367 return CompileFromFileBatch (options, fileNames);