PageRenderTime 56ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/danipen/mono
C# | 369 lines | 269 code | 53 blank | 47 comment | 68 complexity | 823fd61f3e917f9f8cf39d8af85a7d14 MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-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. static string windowsvbncPath;
  50. static VBCodeCompiler ()
  51. {
  52. if (Path.DirectorySeparatorChar == '\\') {
  53. PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
  54. MethodInfo get_gac = gac.GetGetMethod (true);
  55. string p = Path.GetDirectoryName (
  56. (string) get_gac.Invoke (null, null));
  57. windowsMonoPath = Path.Combine (
  58. Path.GetDirectoryName (
  59. Path.GetDirectoryName (p)),
  60. "bin\\mono.bat");
  61. if (!File.Exists (windowsMonoPath))
  62. windowsMonoPath = Path.Combine (
  63. Path.GetDirectoryName (
  64. Path.GetDirectoryName (p)),
  65. "bin\\mono.exe");
  66. windowsvbncPath =
  67. Path.Combine (p, "2.0\\vbnc.exe");
  68. }
  69. }
  70. public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
  71. {
  72. return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
  73. }
  74. public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
  75. {
  76. if (options == null) {
  77. throw new ArgumentNullException ("options");
  78. }
  79. try {
  80. return CompileFromDomBatch (options, ea);
  81. } finally {
  82. options.TempFiles.Delete ();
  83. }
  84. }
  85. public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
  86. {
  87. return CompileAssemblyFromFileBatch (options, new string[] { fileName });
  88. }
  89. public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
  90. {
  91. if (options == null) {
  92. throw new ArgumentNullException ("options");
  93. }
  94. try {
  95. return CompileFromFileBatch (options, fileNames);
  96. } finally {
  97. options.TempFiles.Delete ();
  98. }
  99. }
  100. public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
  101. {
  102. return CompileAssemblyFromSourceBatch (options, new string[] { source });
  103. }
  104. public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
  105. {
  106. if (options == null) {
  107. throw new ArgumentNullException ("options");
  108. }
  109. try {
  110. return CompileFromSourceBatch (options, sources);
  111. } finally {
  112. options.TempFiles.Delete ();
  113. }
  114. }
  115. static string BuildArgs (CompilerParameters options, string[] fileNames)
  116. {
  117. StringBuilder args = new StringBuilder ();
  118. args.Append ("/quiet ");
  119. if (options.GenerateExecutable)
  120. args.Append ("/target:exe ");
  121. else
  122. args.Append ("/target:library ");
  123. /* Disabled. It causes problems now. -- Gonzalo
  124. if (options.IncludeDebugInformation)
  125. args.AppendFormat("/debug ");
  126. */
  127. if (options.TreatWarningsAsErrors)
  128. args.Append ("/warnaserror ");
  129. /* Disabled. vbnc does not support warninglevels.
  130. if (options.WarningLevel != -1)
  131. args.AppendFormat ("/wlevel:{0} ", options.WarningLevel);
  132. */
  133. if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
  134. string ext = (options.GenerateExecutable ? "exe" : "dll");
  135. options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, ext, !options.GenerateInMemory);
  136. }
  137. args.AppendFormat ("/out:\"{0}\" ", options.OutputAssembly);
  138. bool Reference2MSVBFound;
  139. Reference2MSVBFound = false;
  140. if (null != options.ReferencedAssemblies) {
  141. foreach (string import in options.ReferencedAssemblies) {
  142. if (string.Compare (import, "Microsoft.VisualBasic", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
  143. Reference2MSVBFound = true;
  144. args.AppendFormat ("/r:\"{0}\" ", import);
  145. }
  146. }
  147. // add standard import to Microsoft.VisualBasic if missing
  148. if (!Reference2MSVBFound)
  149. args.Append ("/r:\"Microsoft.VisualBasic.dll\" ");
  150. if (options.CompilerOptions != null) {
  151. args.Append (options.CompilerOptions);
  152. args.Append (" ");
  153. }
  154. /* Disabled, vbnc does not support this.
  155. args.Append (" -- "); // makes vbnc not try to process filenames as options
  156. */
  157. foreach (string source in fileNames)
  158. args.AppendFormat (" \"{0}\" ", source);
  159. return args.ToString ();
  160. }
  161. static CompilerError CreateErrorFromString (string error_string)
  162. {
  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);
  167. Match match = reg.Match (error_string);
  168. if (!match.Success) {
  169. return null;
  170. }
  171. if (String.Empty != match.Result ("${file}"))
  172. error.FileName = match.Result ("${file}").Trim ();
  173. if (String.Empty != match.Result ("${line}"))
  174. error.Line = Int32.Parse (match.Result ("${line}"));
  175. if (String.Empty != match.Result ("${column}"))
  176. error.Column = Int32.Parse (match.Result ("${column}"));
  177. if (match.Result ("${level}").Trim () == "Warning")
  178. error.IsWarning = true;
  179. error.ErrorNumber = match.Result ("${number}");
  180. error.ErrorText = match.Result ("${message}");
  181. return error;
  182. }
  183. private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
  184. {
  185. return temp_files.AddExtension (extension, keepFile);
  186. }
  187. private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
  188. {
  189. return temp_files.AddExtension (extension);
  190. }
  191. private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
  192. {
  193. if (options == null) {
  194. throw new ArgumentNullException ("options");
  195. }
  196. if (fileNames == null) {
  197. throw new ArgumentNullException ("fileNames");
  198. }
  199. CompilerResults results = new CompilerResults (options.TempFiles);
  200. Process vbnc = new Process ();
  201. string vbnc_output = "";
  202. string[] vbnc_output_lines;
  203. // FIXME: these lines had better be platform independent.
  204. if (Path.DirectorySeparatorChar == '\\') {
  205. vbnc.StartInfo.FileName = windowsMonoPath;
  206. vbnc.StartInfo.Arguments = windowsvbncPath + ' ' + BuildArgs (options, fileNames);
  207. } else {
  208. vbnc.StartInfo.FileName = "vbnc";
  209. vbnc.StartInfo.Arguments = BuildArgs (options, fileNames);
  210. }
  211. //Console.WriteLine (vbnc.StartInfo.Arguments);
  212. vbnc.StartInfo.CreateNoWindow = true;
  213. vbnc.StartInfo.UseShellExecute = false;
  214. vbnc.StartInfo.RedirectStandardOutput = true;
  215. try {
  216. vbnc.Start ();
  217. } catch (Exception e) {
  218. Win32Exception exc = e as Win32Exception;
  219. if (exc != null) {
  220. throw new SystemException (String.Format ("Error running {0}: {1}", vbnc.StartInfo.FileName,
  221. Win32Exception.W32ErrorMessage (exc.NativeErrorCode)));
  222. }
  223. throw;
  224. }
  225. try {
  226. vbnc_output = vbnc.StandardOutput.ReadToEnd ();
  227. vbnc.WaitForExit ();
  228. } finally {
  229. results.NativeCompilerReturnValue = vbnc.ExitCode;
  230. vbnc.Close ();
  231. }
  232. bool loadIt = true;
  233. if (results.NativeCompilerReturnValue == 1) {
  234. loadIt = false;
  235. vbnc_output_lines = vbnc_output.Split (Environment.NewLine.ToCharArray ());
  236. foreach (string error_line in vbnc_output_lines) {
  237. CompilerError error = CreateErrorFromString (error_line);
  238. if (null != error) {
  239. results.Errors.Add (error);
  240. }
  241. }
  242. }
  243. if ((loadIt == false && !results.Errors.HasErrors) // Failed, but no errors? Probably couldn't parse the compiler output correctly.
  244. || (results.NativeCompilerReturnValue != 0 && results.NativeCompilerReturnValue != 1)) // Neither success (0), nor failure (1), so it crashed.
  245. {
  246. // Show the entire output as one big error message.
  247. loadIt = false;
  248. CompilerError error = new CompilerError (string.Empty, 0, 0, "VBNC_CRASH", vbnc_output);
  249. results.Errors.Add (error);
  250. };
  251. if (loadIt) {
  252. if (options.GenerateInMemory) {
  253. using (FileStream fs = File.OpenRead (options.OutputAssembly)) {
  254. byte[] buffer = new byte[fs.Length];
  255. fs.Read (buffer, 0, buffer.Length);
  256. results.CompiledAssembly = Assembly.Load (buffer, null);
  257. fs.Close ();
  258. }
  259. } else {
  260. results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
  261. results.PathToAssembly = options.OutputAssembly;
  262. }
  263. } else {
  264. results.CompiledAssembly = null;
  265. }
  266. return results;
  267. }
  268. private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
  269. {
  270. if (options == null) {
  271. throw new ArgumentNullException ("options");
  272. }
  273. if (ea == null) {
  274. throw new ArgumentNullException ("ea");
  275. }
  276. string[] fileNames = new string[ea.Length];
  277. StringCollection assemblies = options.ReferencedAssemblies;
  278. for (int i = 0; i < ea.Length; i++) {
  279. CodeCompileUnit compileUnit = ea[i];
  280. fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
  281. FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
  282. StreamWriter s = new StreamWriter (f);
  283. if (compileUnit.ReferencedAssemblies != null) {
  284. foreach (string str in compileUnit.ReferencedAssemblies) {
  285. if (!assemblies.Contains (str))
  286. assemblies.Add (str);
  287. }
  288. }
  289. ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
  290. s.Close ();
  291. f.Close ();
  292. }
  293. return CompileAssemblyFromFileBatch (options, fileNames);
  294. }
  295. private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
  296. {
  297. if (options == null) {
  298. throw new ArgumentNullException ("options");
  299. }
  300. if (sources == null) {
  301. throw new ArgumentNullException ("sources");
  302. }
  303. string[] fileNames = new string[sources.Length];
  304. for (int i = 0; i < sources.Length; i++) {
  305. fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".vb");
  306. FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
  307. using (StreamWriter s = new StreamWriter (f)) {
  308. s.Write (sources[i]);
  309. s.Close ();
  310. }
  311. f.Close ();
  312. }
  313. return CompileFromFileBatch (options, fileNames);
  314. }
  315. }
  316. }