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.
35 namespace Microsoft.VisualBasic
39 using System.CodeDom.Compiler;
42 using System.Reflection;
43 using System.Collections;
44 using System.Collections.Specialized;
45 using System.Diagnostics;
46 using System.Text.RegularExpressions;
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");
78 public VBCodeCompiler()
86 public CompilerResults CompileAssemblyFromDom (CompilerParameters options,CodeCompileUnit e)
88 return CompileAssemblyFromDomBatch (options, new CodeCompileUnit []{e});
91 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options,
92 CodeCompileUnit [] ea)
94 string [] fileNames = new string [ea.Length];
97 options = new CompilerParameters ();
99 StringCollection assemblies = options.ReferencedAssemblies;
101 foreach (CodeCompileUnit e in ea) {
102 fileNames [i] = GetTempFileNameWithExtension (options.TempFiles, "vb");
103 FileStream f = new FileStream (fileNames [i], FileMode.OpenOrCreate);
104 StreamWriter s = new StreamWriter (f);
105 if (e.ReferencedAssemblies != null) {
106 foreach (string str in e.ReferencedAssemblies) {
107 if (!assemblies.Contains (str))
108 assemblies.Add (str);
112 ((ICodeGenerator)this).GenerateCodeFromCompileUnit (e, s, new CodeGeneratorOptions());
117 return CompileAssemblyFromFileBatch (options, fileNames);
120 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
122 return CompileAssemblyFromFileBatch (options, new string []{fileName});
125 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options,
129 throw new ArgumentNullException ("options");
131 if (null == fileNames)
132 throw new ArgumentNullException ("fileNames");
134 CompilerResults results = new CompilerResults (options.TempFiles);
135 Process mbas = new Process ();
138 string [] mbas_output_lines;
139 // FIXME: these lines had better be platform independent.
140 if (Path.DirectorySeparatorChar == '\\') {
141 mbas.StartInfo.FileName = windowsMonoPath;
142 mbas.StartInfo.Arguments = windowsMbasPath + ' ' + BuildArgs (options, fileNames);
145 mbas.StartInfo.FileName = "mbas";
146 mbas.StartInfo.Arguments = BuildArgs (options,fileNames);
148 mbas.StartInfo.CreateNoWindow = true;
149 mbas.StartInfo.UseShellExecute = false;
150 mbas.StartInfo.RedirectStandardOutput = true;
153 mbas_output = mbas.StandardOutput.ReadToEnd ();
156 results.NativeCompilerReturnValue = mbas.ExitCode;
160 mbas_output_lines = mbas_output.Split(Environment.NewLine.ToCharArray());
162 foreach (string error_line in mbas_output_lines) {
163 CompilerError error = CreateErrorFromString (error_line);
165 results.Errors.Add (error);
166 if (!error.IsWarning)
172 if (options.GenerateInMemory) {
173 using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
174 byte[] buffer = new byte[fs.Length];
175 fs.Read(buffer, 0, buffer.Length);
176 results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
180 results.CompiledAssembly = Assembly.LoadFrom(options.OutputAssembly);
181 results.PathToAssembly = options.OutputAssembly;
184 results.CompiledAssembly = null;
190 public CompilerResults CompileAssemblyFromSource (CompilerParameters options,
193 return CompileAssemblyFromSourceBatch (options, new string [] {source});
196 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options,
199 string [] fileNames = new string [sources.Length];
201 foreach (string source in sources) {
202 fileNames [i] = GetTempFileNameWithExtension (options.TempFiles, "vb");
203 FileStream f = new FileStream (fileNames [i], FileMode.OpenOrCreate);
204 StreamWriter s = new StreamWriter (f);
210 return CompileAssemblyFromFileBatch(options,fileNames);
213 static string BuildArgs (CompilerParameters options, string [] fileNames)
215 StringBuilder args = new StringBuilder ();
216 args.AppendFormat ("/quiet ");
217 if (options.GenerateExecutable)
218 args.AppendFormat("/target:exe ");
220 args.AppendFormat("/target:library ");
222 /* Disabled. It causes problems now. -- Gonzalo
223 if (options.IncludeDebugInformation)
224 args.AppendFormat("/debug ");
227 if (options.TreatWarningsAsErrors)
228 args.AppendFormat ("/warnaserror ");
230 if (options.WarningLevel != -1)
231 args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
233 if (options.OutputAssembly == null) {
234 string ext = (options.GenerateExecutable ? "exe" : "dll");
235 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext);
238 args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
240 bool Reference2MSVBFound;
241 Reference2MSVBFound = false;
242 if (null != options.ReferencedAssemblies)
244 foreach (string import in options.ReferencedAssemblies)
246 if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
247 Reference2MSVBFound = true;
248 args.AppendFormat ("/r:\"{0}\" ", import);
251 // add standard import to Microsoft.VisualBasic if missing
252 if (Reference2MSVBFound == false)
253 args.AppendFormat ("/r:\"{0}\" ", "Microsoft.VisualBasic");
255 args.AppendFormat(" -- "); // makes mbas not try to process filenames as options
257 foreach (string source in fileNames)
258 args.AppendFormat("\"{0}\" ",source);
260 return args.ToString();
263 static CompilerError CreateErrorFromString (string error_string)
265 // When IncludeDebugInformation is true, prevents the debug symbols stats from braeking this.
266 if (error_string.StartsWith ("WROTE SYMFILE") || error_string.StartsWith ("OffsetTable"))
269 CompilerError error = new CompilerError ();
270 Regex reg = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)\s+)*" +
271 @"(?<level>error|warning)\s*(?<number>.*):\s(?<message>.*)",
272 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
274 Match match = reg.Match (error_string);
278 if (String.Empty != match.Result("${file}"))
279 error.FileName = match.Result ("${file}");
281 if (String.Empty != match.Result ("${line}"))
282 error.Line = Int32.Parse (match.Result ("${line}"));
284 if (String.Empty != match.Result( "${column}"))
285 error.Column = Int32.Parse (match.Result ("${column}"));
287 if (match.Result ("${level}") =="warning")
288 error.IsWarning = true;
290 error.ErrorNumber = match.Result ("${number}");
291 error.ErrorText = match.Result ("${message}");
295 static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
297 return temp_files.AddExtension (extension);