2005-06-05 Peter Bartok <pbartok@novell.com>
[mono.git] / mcs / class / System / Microsoft.VisualBasic / VBCodeCompiler.cs
1 //
2 // Microsoft VisualBasic VBCodeCompiler Class implementation
3 //
4 // Authors:
5 //      Jochen Wezel (jwezel@compumaster.de)
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //
8 // (c) 2003 Jochen Wezel (http://www.compumaster.de)
9 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
10 //
11 // Modifications:
12 // 2003-11-28 JW: create reference to Microsoft.VisualBasic if not explicitly done
13
14 //
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:
22 // 
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
25 // 
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.
33 //
34
35 namespace Microsoft.VisualBasic
36 {
37         using System;
38         using System.CodeDom;
39         using System.CodeDom.Compiler;
40         using System.IO;
41         using System.Text;
42         using System.Reflection;
43         using System.Collections;
44         using System.Collections.Specialized;
45         using System.Diagnostics;
46         using System.Text.RegularExpressions;
47
48         internal class VBCodeCompiler: VBCodeGenerator, ICodeCompiler
49         {
50                 static string windowsMonoPath;
51                 static string windowsMbasPath;
52                 static VBCodeCompiler ()
53                 {
54                         if (Path.DirectorySeparatorChar == '\\') {
55                                 // FIXME: right now we use "fixed" version 1.0
56                                 // mcs at any time.
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)),
64                                         "bin\\mono.bat");
65                                 if (!File.Exists (windowsMonoPath))
66                                         windowsMonoPath = Path.Combine (
67                                                 Path.GetDirectoryName (
68                                                         Path.GetDirectoryName (p)),
69                                                 "bin\\mono.exe");
70                                 windowsMbasPath =
71                                         Path.Combine (p, "1.0\\mbas.exe");
72                         }
73                 }
74
75                 //
76                 // Constructors
77                 //
78                 public VBCodeCompiler()
79                 {
80                 }
81
82                 //
83                 // Methods
84                 //
85                 [MonoTODO]
86                 public CompilerResults CompileAssemblyFromDom (CompilerParameters options,CodeCompileUnit e)
87                 {
88                         return CompileAssemblyFromDomBatch (options, new CodeCompileUnit []{e});
89                 }
90
91                 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options,
92                                                                     CodeCompileUnit [] ea)
93                 {
94                         string [] fileNames = new string [ea.Length];
95                         int i = 0;
96                         if (options == null)
97                         options = new CompilerParameters ();
98
99                         StringCollection assemblies = options.ReferencedAssemblies;
100
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);
109                                         }
110                                 }
111
112                                 ((ICodeGenerator)this).GenerateCodeFromCompileUnit (e, s, new CodeGeneratorOptions());
113                                 s.Close();
114                                 f.Close();
115                                 i++;
116                         }
117                         return CompileAssemblyFromFileBatch (options, fileNames);
118                 }
119
120                 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
121                 {
122                         return CompileAssemblyFromFileBatch (options, new string []{fileName});
123                 }
124
125                 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options,
126                                                                      string [] fileNames)
127                 {
128                         if (null == options)
129                                 throw new ArgumentNullException ("options");
130
131                         if (null == fileNames)
132                                 throw new ArgumentNullException ("fileNames");
133
134                         CompilerResults results = new CompilerResults (options.TempFiles);
135                         Process mbas = new Process ();
136
137                         string mbas_output;
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);
143                         }
144                         else {
145                                 mbas.StartInfo.FileName = "mbas";
146                                 mbas.StartInfo.Arguments = BuildArgs (options,fileNames);
147                         }
148                         mbas.StartInfo.CreateNoWindow = true;
149                         mbas.StartInfo.UseShellExecute = false;
150                         mbas.StartInfo.RedirectStandardOutput = true;
151                         try {
152                                 mbas.Start();
153                                 mbas_output = mbas.StandardOutput.ReadToEnd ();
154                                 mbas.WaitForExit();
155                         } finally {
156                                 results.NativeCompilerReturnValue = mbas.ExitCode;
157                                 mbas.Close ();
158                         }
159
160                         mbas_output_lines = mbas_output.Split(Environment.NewLine.ToCharArray());
161                         bool loadIt=true;
162                         foreach (string error_line in mbas_output_lines) {
163                                 CompilerError error = CreateErrorFromString (error_line);
164                                 if (null != error) {
165                                         results.Errors.Add (error);
166                                         if (!error.IsWarning)
167                                                 loadIt = false;
168                                 }
169                         }
170
171                         if (loadIt) {
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);
177                                                 fs.Close();
178                                         }
179                                 } else {
180                                         results.CompiledAssembly = Assembly.LoadFrom(options.OutputAssembly);
181                                         results.PathToAssembly = options.OutputAssembly;
182                                 }
183                         } else {
184                                 results.CompiledAssembly = null;
185                         }
186   
187                         return results;
188                 }
189
190                 public CompilerResults CompileAssemblyFromSource (CompilerParameters options,
191                                                                   string source)
192                 {
193                         return CompileAssemblyFromSourceBatch (options, new string [] {source});
194                 }
195
196                 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options,
197                                                                         string [] sources)
198                 {
199                         string [] fileNames = new string [sources.Length];
200                         int i = 0;
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);
205                                 s.Write (source);
206                                 s.Close ();
207                                 f.Close ();
208                                 i++;
209                         }
210                         return CompileAssemblyFromFileBatch(options,fileNames);
211                 }
212
213                 static string BuildArgs (CompilerParameters options, string [] fileNames)
214                 {
215                         StringBuilder args = new StringBuilder ();
216                         args.AppendFormat ("/quiet ");
217                         if (options.GenerateExecutable)
218                                 args.AppendFormat("/target:exe ");
219                         else
220                                 args.AppendFormat("/target:library ");
221
222                         /* Disabled. It causes problems now. -- Gonzalo
223                         if (options.IncludeDebugInformation)
224                                 args.AppendFormat("/debug ");
225                         */
226
227                         if (options.TreatWarningsAsErrors)
228                                 args.AppendFormat ("/warnaserror ");
229
230                         if (options.WarningLevel != -1)
231                                 args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
232
233                         if (options.OutputAssembly == null) {
234                                 string ext = (options.GenerateExecutable ? "exe" : "dll");
235                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext);
236                         }
237
238                         args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
239
240                         bool Reference2MSVBFound;
241                         Reference2MSVBFound = false;
242                         if (null != options.ReferencedAssemblies) 
243                         {
244                                 foreach (string import in options.ReferencedAssemblies)
245                                 {
246                                         if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
247                                                 Reference2MSVBFound = true;
248                                         args.AppendFormat ("/r:\"{0}\" ", import);
249                                 }
250                         }
251                         // add standard import to Microsoft.VisualBasic if missing
252                         if (Reference2MSVBFound == false)
253                                 args.AppendFormat ("/r:\"{0}\" ", "Microsoft.VisualBasic");
254
255                         args.AppendFormat(" -- "); // makes mbas not try to process filenames as options
256
257                         foreach (string source in fileNames)
258                                 args.AppendFormat("\"{0}\" ",source);
259
260                         return args.ToString();
261                 }
262
263                 static CompilerError CreateErrorFromString (string error_string)
264                 {
265                         // When IncludeDebugInformation is true, prevents the debug symbols stats from braeking this.
266                         if (error_string.StartsWith ("WROTE SYMFILE") || error_string.StartsWith ("OffsetTable"))
267                                 return null;
268
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);
273
274                         Match match = reg.Match (error_string);
275                         if (!match.Success)
276                                 return null;
277
278                         if (String.Empty != match.Result("${file}"))
279                                 error.FileName = match.Result ("${file}");
280
281                         if (String.Empty != match.Result ("${line}"))
282                                 error.Line = Int32.Parse (match.Result ("${line}"));
283
284                         if (String.Empty != match.Result( "${column}"))
285                                 error.Column = Int32.Parse (match.Result ("${column}"));
286
287                         if (match.Result ("${level}") =="warning")
288                                 error.IsWarning = true;
289
290                         error.ErrorNumber = match.Result ("${number}");
291                         error.ErrorText = match.Result ("${message}");
292                         return error;
293                 }
294
295                 static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
296                 {
297                         return temp_files.AddExtension (extension);
298                 }
299         }
300 }
301