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 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
53 return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
56 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
58 if (options == null) {
59 throw new ArgumentNullException ("options");
63 return CompileFromDomBatch (options, ea);
65 options.TempFiles.Delete ();
69 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
71 return CompileAssemblyFromFileBatch (options, new string[] { fileName });
74 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
76 if (options == null) {
77 throw new ArgumentNullException ("options");
81 return CompileFromFileBatch (options, fileNames);
83 options.TempFiles.Delete ();
87 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
89 return CompileAssemblyFromSourceBatch (options, new string[] { source });
92 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
94 if (options == null) {
95 throw new ArgumentNullException ("options");
99 return CompileFromSourceBatch (options, sources);
101 options.TempFiles.Delete ();
105 static string BuildArgs (CompilerParameters options, string[] fileNames)
107 StringBuilder args = new StringBuilder ();
108 args.Append ("/quiet ");
109 if (options.GenerateExecutable)
110 args.Append ("/target:exe ");
112 args.Append ("/target:library ");
114 /* Disabled. It causes problems now. -- Gonzalo
115 if (options.IncludeDebugInformation)
116 args.AppendFormat("/debug ");
119 if (options.TreatWarningsAsErrors)
120 args.Append ("/warnaserror ");
122 /* Disabled. vbnc does not support warninglevels.
123 if (options.WarningLevel != -1)
124 args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
127 if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
128 string ext = (options.GenerateExecutable ? "exe" : "dll");
129 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext, !options.GenerateInMemory);
132 args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
134 bool Reference2MSVBFound;
135 Reference2MSVBFound = false;
136 if (null != options.ReferencedAssemblies) {
137 foreach (string import in options.ReferencedAssemblies) {
138 if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
139 Reference2MSVBFound = true;
140 args.AppendFormat ("/r:\"{0}\" ", import);
144 // add standard import to Microsoft.VisualBasic if missing
145 if (!Reference2MSVBFound)
146 args.Append ("/r:\"Microsoft.VisualBasic.dll\" ");
148 if (options.CompilerOptions != null) {
149 args.Append (options.CompilerOptions);
152 /* Disabled, vbnc does not support this.
153 args.Append (" -- "); // makes vbnc not try to process filenames as options
155 foreach (string source in fileNames)
156 args.AppendFormat (" \"{0}\" ", source);
158 return args.ToString ();
161 static CompilerError CreateErrorFromString (string error_string)
163 CompilerError error = new CompilerError ();
164 Regex reg = new Regex (@"^(\s*(?<file>.*)?\((?<line>\d*)(,(?<column>\d*))?\)\s+)?:\s*" +
165 @"(?<level>Error|Warning)?\s*(?<number>.*):\s(?<message>.*)",
166 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
168 Match match = reg.Match (error_string);
169 if (!match.Success) {
173 if (String.Empty != match.Result ("${file}"))
174 error.FileName = match.Result ("${file}").Trim ();
176 if (String.Empty != match.Result ("${line}"))
177 error.Line = Int32.Parse (match.Result ("${line}"));
179 if (String.Empty != match.Result ("${column}"))
180 error.Column = Int32.Parse (match.Result ("${column}"));
182 if (match.Result ("${level}").Trim () == "Warning")
183 error.IsWarning = true;
185 error.ErrorNumber = match.Result ("${number}");
186 error.ErrorText = match.Result ("${message}");
191 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
193 return temp_files.AddExtension (extension, keepFile);
196 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
198 return temp_files.AddExtension (extension);
201 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
204 if (options == null) {
205 throw new ArgumentNullException ("options");
208 if (fileNames == null) {
209 throw new ArgumentNullException ("fileNames");
212 CompilerResults results = new CompilerResults (options.TempFiles);
213 Process vbnc = new Process ();
215 string vbnc_output = "";
216 string[] vbnc_output_lines;
217 // FIXME: these lines had better be platform independent.
218 if (Path.DirectorySeparatorChar == '\\') {
219 vbnc.StartInfo.FileName = MonoToolsLocator.Mono;
220 vbnc.StartInfo.Arguments = MonoToolsLocator.VBCompiler + ' ' + BuildArgs (options, fileNames);
222 vbnc.StartInfo.FileName = MonoToolsLocator.VBCompiler;
223 vbnc.StartInfo.Arguments = BuildArgs (options, fileNames);
225 //Console.WriteLine (vbnc.StartInfo.Arguments);
226 vbnc.StartInfo.CreateNoWindow = true;
227 vbnc.StartInfo.UseShellExecute = false;
228 vbnc.StartInfo.RedirectStandardOutput = true;
231 } catch (Exception e) {
232 Win32Exception exc = e as Win32Exception;
234 throw new SystemException (String.Format ("Error running {0}: {1}", vbnc.StartInfo.FileName,
235 Win32Exception.GetErrorMessage (exc.NativeErrorCode)));
241 vbnc_output = vbnc.StandardOutput.ReadToEnd ();
244 results.NativeCompilerReturnValue = vbnc.ExitCode;
249 if (results.NativeCompilerReturnValue == 1) {
251 vbnc_output_lines = vbnc_output.Split (Environment.NewLine.ToCharArray ());
252 foreach (string error_line in vbnc_output_lines) {
253 CompilerError error = CreateErrorFromString (error_line);
255 results.Errors.Add (error);
260 if ((loadIt == false && !results.Errors.HasErrors) // Failed, but no errors? Probably couldn't parse the compiler output correctly.
261 || (results.NativeCompilerReturnValue != 0 && results.NativeCompilerReturnValue != 1)) // Neither success (0), nor failure (1), so it crashed.
263 // Show the entire output as one big error message.
265 CompilerError error = new CompilerError (string.Empty, 0, 0, "VBNC_CRASH", vbnc_output);
266 results.Errors.Add (error);
270 if (options.GenerateInMemory) {
271 using (FileStream fs = File.OpenRead (options.OutputAssembly)) {
272 byte[] buffer = new byte[fs.Length];
273 fs.Read (buffer, 0, buffer.Length);
274 results.CompiledAssembly = Assembly.Load (buffer, null);
278 results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
279 results.PathToAssembly = options.OutputAssembly;
282 results.CompiledAssembly = null;
288 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
290 if (options == null) {
291 throw new ArgumentNullException ("options");
295 throw new ArgumentNullException ("ea");
298 string[] fileNames = new string[ea.Length];
299 StringCollection assemblies = options.ReferencedAssemblies;
301 for (int i = 0; i < ea.Length; i++) {
302 CodeCompileUnit compileUnit = ea[i];
303 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
304 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
305 StreamWriter s = new StreamWriter (f);
306 if (compileUnit.ReferencedAssemblies != null) {
307 foreach (string str in compileUnit.ReferencedAssemblies) {
308 if (!assemblies.Contains (str))
309 assemblies.Add (str);
313 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
317 return CompileAssemblyFromFileBatch (options, fileNames);
320 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
322 if (options == null) {
323 throw new ArgumentNullException ("options");
326 if (sources == null) {
327 throw new ArgumentNullException ("sources");
330 string[] fileNames = new string[sources.Length];
332 for (int i = 0; i < sources.Length; i++) {
333 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
334 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
335 using (StreamWriter s = new StreamWriter (f)) {
336 s.Write (sources[i]);
341 return CompileFromFileBatch (options, fileNames);