PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/mcs/class/System/Microsoft.VisualBasic/VBCodeCompiler.cs

https://bitbucket.org/puffnfresh/mono-dependency-analysis
C# | 382 lines | 282 code | 53 blank | 47 comment | 68 complexity | e015c4596860b50be943d704bc6ffba4 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0, Unlicense, Apache-2.0, LGPL-2.0
  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. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System;
  34. using System.CodeDom;
  35. using System.CodeDom.Compiler;
  36. using System.ComponentModel;
  37. using System.IO;
  38. using System.Text;
  39. using System.Reflection;
  40. using System.Collections;
  41. using System.Collections.Specialized;
  42. using System.Diagnostics;
  43. using System.Text.RegularExpressions;
  44. namespace Microsoft.VisualBasic
  45. {
  46. internal class VBCodeCompiler : VBCodeGenerator, ICodeCompiler
  47. {
  48. static string windowsMonoPath;
  49. #if NET_2_0
  50. static string windowsvbncPath;
  51. #endif
  52. static VBCodeCompiler ()
  53. {
  54. if (Path.DirectorySeparatorChar == '\\') {
  55. PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
  56. MethodInfo get_gac = gac.GetGetMethod (true);
  57. string p = Path.GetDirectoryName (
  58. (string) get_gac.Invoke (null, null));
  59. windowsMonoPath = Path.Combine (
  60. Path.GetDirectoryName (
  61. Path.GetDirectoryName (p)),
  62. "bin\\mono.bat");
  63. if (!File.Exists (windowsMonoPath))
  64. windowsMonoPath = Path.Combine (
  65. Path.GetDirectoryName (
  66. Path.GetDirectoryName (p)),
  67. "bin\\mono.exe");
  68. #if NET_2_0
  69. windowsvbncPath =
  70. Path.Combine (p, "2.0\\vbnc.exe");
  71. #endif
  72. }
  73. }
  74. public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
  75. {
  76. return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
  77. }
  78. public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
  79. {
  80. if (options == null) {
  81. throw new ArgumentNullException ("options");
  82. }
  83. try {
  84. return CompileFromDomBatch (options, ea);
  85. } finally {
  86. options.TempFiles.Delete ();
  87. }
  88. }
  89. public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
  90. {
  91. return CompileAssemblyFromFileBatch (options, new string[] { fileName });
  92. }
  93. public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
  94. {
  95. if (options == null) {
  96. throw new ArgumentNullException ("options");
  97. }
  98. try {
  99. return CompileFromFileBatch (options, fileNames);
  100. } finally {
  101. options.TempFiles.Delete ();
  102. }
  103. }
  104. public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
  105. {
  106. return CompileAssemblyFromSourceBatch (options, new string[] { source });
  107. }
  108. public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
  109. {
  110. if (options == null) {
  111. throw new ArgumentNullException ("options");
  112. }
  113. try {
  114. return CompileFromSourceBatch (options, sources);
  115. } finally {
  116. options.TempFiles.Delete ();
  117. }
  118. }
  119. #if NET_2_0
  120. static string BuildArgs (CompilerParameters options, string[] fileNames)
  121. {
  122. StringBuilder args = new StringBuilder ();
  123. args.Append ("/quiet ");
  124. if (options.GenerateExecutable)
  125. args.Append ("/target:exe ");
  126. else
  127. args.Append ("/target:library ");
  128. /* Disabled. It causes problems now. -- Gonzalo
  129. if (options.IncludeDebugInformation)
  130. args.AppendFormat("/debug ");
  131. */
  132. if (options.TreatWarningsAsErrors)
  133. args.Append ("/warnaserror ");
  134. /* Disabled. vbnc does not support warninglevels.
  135. if (options.WarningLevel != -1)
  136. args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
  137. */
  138. if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
  139. string ext = (options.GenerateExecutable ? "exe" : "dll");
  140. options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext, !options.GenerateInMemory);
  141. }
  142. args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
  143. bool Reference2MSVBFound;
  144. Reference2MSVBFound = false;
  145. if (null != options.ReferencedAssemblies) {
  146. foreach (string import in options.ReferencedAssemblies) {
  147. if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
  148. Reference2MSVBFound = true;
  149. args.AppendFormat ("/r:\"{0}\" ", import);
  150. }
  151. }
  152. // add standard import to Microsoft.VisualBasic if missing
  153. if (!Reference2MSVBFound)
  154. args.Append ("/r:\"Microsoft.VisualBasic.dll\" ");
  155. if (options.CompilerOptions != null) {
  156. args.Append (options.CompilerOptions);
  157. args.Append (" ");
  158. }
  159. /* Disabled, vbnc does not support this.
  160. args.Append (" -- "); // makes vbnc not try to process filenames as options
  161. */
  162. foreach (string source in fileNames)
  163. args.AppendFormat (" \"{0}\" ", source);
  164. return args.ToString ();
  165. }
  166. static CompilerError CreateErrorFromString (string error_string)
  167. {
  168. CompilerError error = new CompilerError ();
  169. Regex reg = new Regex (@"^(\s*(?<file>.*)?\((?<line>\d*)(,(?<column>\d*))?\)\s+)?:\s*" +
  170. @"(?<level>Error|Warning)?\s*(?<number>.*):\s(?<message>.*)",
  171. RegexOptions.Compiled | RegexOptions.ExplicitCapture);
  172. Match match = reg.Match (error_string);
  173. if (!match.Success) {
  174. return null;
  175. }
  176. if (String.Empty != match.Result ("${file}"))
  177. error.FileName = match.Result ("${file}").Trim ();
  178. if (String.Empty != match.Result ("${line}"))
  179. error.Line = Int32.Parse (match.Result ("${line}"));
  180. if (String.Empty != match.Result ("${column}"))
  181. error.Column = Int32.Parse (match.Result ("${column}"));
  182. if (match.Result ("${level}").Trim () == "Warning")
  183. error.IsWarning = true;
  184. error.ErrorNumber = match.Result ("${number}");
  185. error.ErrorText = match.Result ("${message}");
  186. return error;
  187. }
  188. private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
  189. {
  190. return temp_files.AddExtension (extension, keepFile);
  191. }
  192. #endif
  193. private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
  194. {
  195. return temp_files.AddExtension (extension);
  196. }
  197. private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
  198. {
  199. #if !NET_2_0
  200. throw new NotSupportedException (
  201. @"Compilation of Visual Basic code is not supported for v1.0/v1.1 assemblies, please use the v2.0 assemblies.
  202. - 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).
  203. - If this is a desktop application, use gmcs to compile your application instead of mcs.");
  204. #else
  205. if (options == null) {
  206. throw new ArgumentNullException ("options");
  207. }
  208. if (fileNames == null) {
  209. throw new ArgumentNullException ("fileNames");
  210. }
  211. CompilerResults results = new CompilerResults (options.TempFiles);
  212. Process vbnc = new Process ();
  213. string vbnc_output = "";
  214. string[] vbnc_output_lines;
  215. // FIXME: these lines had better be platform independent.
  216. if (Path.DirectorySeparatorChar == '\\') {
  217. vbnc.StartInfo.FileName = windowsMonoPath;
  218. vbnc.StartInfo.Arguments = windowsvbncPath + ' ' + BuildArgs (options, fileNames);
  219. } else {
  220. vbnc.StartInfo.FileName = "vbnc";
  221. vbnc.StartInfo.Arguments = BuildArgs (options, fileNames);
  222. }
  223. //Console.WriteLine (vbnc.StartInfo.Arguments);
  224. vbnc.StartInfo.CreateNoWindow = true;
  225. vbnc.StartInfo.UseShellExecute = false;
  226. vbnc.StartInfo.RedirectStandardOutput = true;
  227. try {
  228. vbnc.Start ();
  229. } catch (Exception e) {
  230. Win32Exception exc = e as Win32Exception;
  231. if (exc != null) {
  232. throw new SystemException (String.Format ("Error running {0}: {1}", vbnc.StartInfo.FileName,
  233. Win32Exception.W32ErrorMessage (exc.NativeErrorCode)));
  234. }
  235. throw;
  236. }
  237. try {
  238. vbnc_output = vbnc.StandardOutput.ReadToEnd ();
  239. vbnc.WaitForExit ();
  240. } finally {
  241. results.NativeCompilerReturnValue = vbnc.ExitCode;
  242. vbnc.Close ();
  243. }
  244. bool loadIt = true;
  245. if (results.NativeCompilerReturnValue == 1) {
  246. loadIt = false;
  247. vbnc_output_lines = vbnc_output.Split (Environment.NewLine.ToCharArray ());
  248. foreach (string error_line in vbnc_output_lines) {
  249. CompilerError error = CreateErrorFromString (error_line);
  250. if (null != error) {
  251. results.Errors.Add (error);
  252. }
  253. }
  254. }
  255. if ((loadIt == false && !results.Errors.HasErrors) // Failed, but no errors? Probably couldn't parse the compiler output correctly.
  256. || (results.NativeCompilerReturnValue != 0 && results.NativeCompilerReturnValue != 1)) // Neither success (0), nor failure (1), so it crashed.
  257. {
  258. // Show the entire output as one big error message.
  259. loadIt = false;
  260. CompilerError error = new CompilerError (string.Empty, 0, 0, "VBNC_CRASH", vbnc_output);
  261. results.Errors.Add (error);
  262. };
  263. if (loadIt) {
  264. if (options.GenerateInMemory) {
  265. using (FileStream fs = File.OpenRead (options.OutputAssembly)) {
  266. byte[] buffer = new byte[fs.Length];
  267. fs.Read (buffer, 0, buffer.Length);
  268. results.CompiledAssembly = Assembly.Load (buffer, null, options.Evidence);
  269. fs.Close ();
  270. }
  271. } else {
  272. results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
  273. results.PathToAssembly = options.OutputAssembly;
  274. }
  275. } else {
  276. results.CompiledAssembly = null;
  277. }
  278. return results;
  279. #endif
  280. }
  281. private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
  282. {
  283. if (options == null) {
  284. throw new ArgumentNullException ("options");
  285. }
  286. if (ea == null) {
  287. throw new ArgumentNullException ("ea");
  288. }
  289. string[] fileNames = new string[ea.Length];
  290. StringCollection assemblies = options.ReferencedAssemblies;
  291. for (int i = 0; i < ea.Length; i++) {
  292. CodeCompileUnit compileUnit = ea[i];
  293. fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
  294. FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
  295. StreamWriter s = new StreamWriter (f);
  296. if (compileUnit.ReferencedAssemblies != null) {
  297. foreach (string str in compileUnit.ReferencedAssemblies) {
  298. if (!assemblies.Contains (str))
  299. assemblies.Add (str);
  300. }
  301. }
  302. ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
  303. s.Close ();
  304. f.Close ();
  305. }
  306. return CompileAssemblyFromFileBatch (options, fileNames);
  307. }
  308. private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
  309. {
  310. if (options == null) {
  311. throw new ArgumentNullException ("options");
  312. }
  313. if (sources == null) {
  314. throw new ArgumentNullException ("sources");
  315. }
  316. string[] fileNames = new string[sources.Length];
  317. for (int i = 0; i < sources.Length; i++) {
  318. fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
  319. FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
  320. using (StreamWriter s = new StreamWriter (f)) {
  321. s.Write (sources[i]);
  322. s.Close ();
  323. }
  324. f.Close ();
  325. }
  326. return CompileFromFileBatch (options, fileNames);
  327. }
  328. }
  329. }