Merge pull request #4169 from evincarofautumn/fix-xmm-scanning-mac-x86
[mono.git] / mcs / class / System / Microsoft.VisualBasic / VBCodeGenerator.cs
1 //
2 // VBCodeGenerator.cs:
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 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System;
33 using System.CodeDom;
34 using System.CodeDom.Compiler;
35 using System.ComponentModel;
36 using System.IO;
37 using System.Text;
38 using System.Reflection;
39 using System.Collections;
40 using System.Collections.Specialized;
41 using System.Diagnostics;
42 using System.Text.RegularExpressions;
43
44 namespace Microsoft.VisualBasic
45 {
46         partial class VBCodeGenerator
47         {
48                 protected override CompilerResults FromFileBatch(CompilerParameters options, string[] fileNames)
49                 {
50                         if (options == null)
51                                 throw new ArgumentNullException(nameof(options));
52
53                         if (fileNames == null)
54                                 throw new ArgumentNullException(nameof(fileNames));
55
56                         CompilerResults results = new CompilerResults (options.TempFiles);
57                         Process vbnc = new Process ();
58
59                         string vbnc_output = "";
60                         string[] vbnc_output_lines;
61                         // FIXME: these lines had better be platform independent.
62                         if (Path.DirectorySeparatorChar == '\\') {
63                                 vbnc.StartInfo.FileName = MonoToolsLocator.Mono;
64                                 vbnc.StartInfo.Arguments = MonoToolsLocator.VBCompiler + ' ' + BuildArgs (options, fileNames);
65                         } else {
66                                 vbnc.StartInfo.FileName = MonoToolsLocator.VBCompiler;
67                                 vbnc.StartInfo.Arguments = BuildArgs (options, fileNames);
68                         }
69                         //Console.WriteLine (vbnc.StartInfo.Arguments);
70                         vbnc.StartInfo.CreateNoWindow = true;
71                         vbnc.StartInfo.UseShellExecute = false;
72                         vbnc.StartInfo.RedirectStandardOutput = true;
73                         try {
74                                 vbnc.Start ();
75                         } catch (Exception e) {
76                                 Win32Exception exc = e as Win32Exception;
77                                 if (exc != null) {
78                                         throw new SystemException (String.Format ("Error running {0}: {1}", vbnc.StartInfo.FileName,
79                                                                                         Win32Exception.GetErrorMessage (exc.NativeErrorCode)));
80                                 }
81                                 throw;
82                         }
83
84                         try {
85                                 vbnc_output = vbnc.StandardOutput.ReadToEnd ();
86                                 vbnc.WaitForExit ();
87                         } finally {
88                                 results.NativeCompilerReturnValue = vbnc.ExitCode;
89                                 vbnc.Close ();
90                         }
91
92                         bool loadIt = true;
93                         if (results.NativeCompilerReturnValue == 1) {
94                                 loadIt = false;
95                                 vbnc_output_lines = vbnc_output.Split (Environment.NewLine.ToCharArray ());
96                                 foreach (string error_line in vbnc_output_lines) {
97                                         CompilerError error = CreateErrorFromString (error_line);
98                                         if (null != error) {
99                                                 results.Errors.Add (error);
100                                         }
101                                 }
102                         }
103                         
104                         if ((loadIt == false && !results.Errors.HasErrors) // Failed, but no errors? Probably couldn't parse the compiler output correctly. 
105                                 || (results.NativeCompilerReturnValue != 0 && results.NativeCompilerReturnValue != 1)) // Neither success (0), nor failure (1), so it crashed. 
106                         {
107                                 // Show the entire output as one big error message.
108                                 loadIt = false;
109                                 CompilerError error = new CompilerError (string.Empty, 0, 0, "VBNC_CRASH", vbnc_output);
110                                 results.Errors.Add (error);
111                         };
112
113                         if (loadIt) {
114                                 if (options.GenerateInMemory) {
115                                         using (FileStream fs = File.OpenRead (options.OutputAssembly)) {
116                                                 byte[] buffer = new byte[fs.Length];
117                                                 fs.Read (buffer, 0, buffer.Length);
118                                                 results.CompiledAssembly = Assembly.Load (buffer, null);
119                                                 fs.Close ();
120                                         }
121                                 } else {
122                                         results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
123                                         results.PathToAssembly = options.OutputAssembly;
124                                 }
125                         } else {
126                                 results.CompiledAssembly = null;
127                         }
128
129                         return results;
130                 }
131
132                 static string BuildArgs (CompilerParameters options, string[] fileNames)
133                 {
134                         StringBuilder args = new StringBuilder ();
135                         args.Append ("/quiet ");
136                         if (options.GenerateExecutable)
137                                 args.Append ("/target:exe ");
138                         else
139                                 args.Append ("/target:library ");
140
141                         /* Disabled. It causes problems now. -- Gonzalo
142                         if (options.IncludeDebugInformation)
143                                 args.AppendFormat("/debug ");
144                         */
145
146                         if (options.TreatWarningsAsErrors)
147                                 args.Append ("/warnaserror ");
148
149                         /* Disabled. vbnc does not support warninglevels.
150                         if (options.WarningLevel != -1)
151                                 args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
152                         */
153
154                         if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
155                                 string ext = (options.GenerateExecutable ? "exe" : "dll");
156                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext, !options.GenerateInMemory);
157                         }
158
159                         args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
160
161                         bool Reference2MSVBFound;
162                         Reference2MSVBFound = false;
163                         if (null != options.ReferencedAssemblies) {
164                                 foreach (string import in options.ReferencedAssemblies) {
165                                         if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
166                                                 Reference2MSVBFound = true;
167                                         args.AppendFormat ("/r:\"{0}\" ", import);
168                                 }
169                         }
170                         
171                         // add standard import to Microsoft.VisualBasic if missing
172                         if (!Reference2MSVBFound)
173                                 args.Append ("/r:\"Microsoft.VisualBasic.dll\" ");
174
175                         if (options.CompilerOptions != null) {
176                                 args.Append (options.CompilerOptions);
177                                 args.Append (" ");
178                         }
179                         /* Disabled, vbnc does not support this.
180                         args.Append (" -- "); // makes vbnc not try to process filenames as options
181                         */
182                         foreach (string source in fileNames)
183                                 args.AppendFormat (" \"{0}\" ", source);
184
185                         return args.ToString ();
186                 }
187
188                 static CompilerError CreateErrorFromString (string error_string)
189                 {
190                         CompilerError error = new CompilerError ();
191                         Regex reg = new Regex (@"^(\s*(?<file>.*)?\((?<line>\d*)(,(?<column>\d*))?\)\s+)?:\s*" +
192                                                 @"(?<level>Error|Warning)?\s*(?<number>.*):\s(?<message>.*)",
193                                                 RegexOptions.Compiled | RegexOptions.ExplicitCapture);
194
195                         Match match = reg.Match (error_string);
196                         if (!match.Success) {
197                                 return null;
198                         }
199
200                         if (String.Empty != match.Result ("${file}"))
201                                 error.FileName = match.Result ("${file}").Trim ();
202
203                         if (String.Empty != match.Result ("${line}"))
204                                 error.Line = Int32.Parse (match.Result ("${line}"));
205
206                         if (String.Empty != match.Result ("${column}"))
207                                 error.Column = Int32.Parse (match.Result ("${column}"));
208
209                         if (match.Result ("${level}").Trim () == "Warning")
210                                 error.IsWarning = true;
211
212                         error.ErrorNumber = match.Result ("${number}");
213                         error.ErrorText = match.Result ("${message}");
214                         
215                         return error;
216                 }
217
218                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
219                 {
220                         return temp_files.AddExtension (extension, keepFile);
221                 }
222         }
223 }