ScriptCompiler.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading;
  10. using BansheeEngine;
  11. namespace BansheeEditor
  12. {
  13. /** @addtogroup Script
  14. * @{
  15. */
  16. /// <summary>
  17. /// Type of assemblies that may be generated by the script compiler.
  18. /// </summary>
  19. public enum ScriptAssemblyType
  20. {
  21. Game, Editor
  22. }
  23. /// <summary>
  24. /// Data required for compiling a single assembly.
  25. /// </summary>
  26. public struct CompileData
  27. {
  28. public string[] files;
  29. public string defines;
  30. }
  31. /// <summary>
  32. /// Compiles script files in the project into script assemblies.
  33. /// </summary>
  34. public static class ScriptCompiler
  35. {
  36. /// <summary>
  37. /// Starts compilation of the script files in the project for the specified assembly for the specified platform.
  38. /// </summary>
  39. /// <param name="type">Type of the assembly to compile. This determines which script files are used as input.</param>
  40. /// <param name="platform">Platform to compile the assemblies for.</param>
  41. /// <param name="debug">Determines should the assemblies contain debug information.</param>
  42. /// <param name="outputDir">Absolute path to the directory where to output the assemblies.</param>
  43. /// <returns>Compiler instance that contains the compiler process. Caller must ensure to properly dispose
  44. /// of this object when done.</returns>
  45. public static CompilerInstance CompileAsync(ScriptAssemblyType type, PlatformType platform, bool debug, string outputDir)
  46. {
  47. LibraryEntry[] scriptEntries = ProjectLibrary.Search("*", new ResourceType[] { ResourceType.ScriptCode });
  48. List<string> scriptFiles = new List<string>();
  49. for (int i = 0; i < scriptEntries.Length; i++)
  50. {
  51. if(scriptEntries[i].Type != LibraryEntryType.File)
  52. continue;
  53. FileEntry fileEntry = (FileEntry)scriptEntries[i];
  54. ScriptCodeImportOptions io = (ScriptCodeImportOptions) fileEntry.Options;
  55. if (io.EditorScript && type == ScriptAssemblyType.Editor ||
  56. !io.EditorScript && type == ScriptAssemblyType.Game)
  57. {
  58. scriptFiles.Add(Path.Combine(ProjectLibrary.ResourceFolder, scriptEntries[i].Path));
  59. }
  60. }
  61. string[] assemblyFolders;
  62. string[] assemblies;
  63. string outputFile;
  64. string builtinAssemblyPath = debug
  65. ? EditorApplication.BuiltinDebugAssemblyPath
  66. : EditorApplication.BuiltinReleaseAssemblyPath;
  67. string[] frameworkAssemblies = BuildManager.GetFrameworkAssemblies(platform);
  68. if (type == ScriptAssemblyType.Game)
  69. {
  70. assemblyFolders = new string[]
  71. {
  72. builtinAssemblyPath,
  73. EditorApplication.FrameworkAssemblyPath
  74. };
  75. assemblies = new string[frameworkAssemblies.Length + 1];
  76. assemblies[assemblies.Length - 1] = EditorApplication.EngineAssemblyName;
  77. outputFile = Path.Combine(outputDir, EditorApplication.ScriptGameAssemblyName);
  78. }
  79. else
  80. {
  81. assemblyFolders = new string[]
  82. {
  83. builtinAssemblyPath,
  84. EditorApplication.FrameworkAssemblyPath,
  85. EditorApplication.ScriptAssemblyPath
  86. };
  87. assemblies = new string[frameworkAssemblies.Length + 3];
  88. assemblies[assemblies.Length - 1] = EditorApplication.EngineAssemblyName;
  89. assemblies[assemblies.Length - 2] = EditorApplication.EditorAssemblyName;
  90. assemblies[assemblies.Length - 3] = EditorApplication.ScriptGameAssemblyName;
  91. outputFile = Path.Combine(outputDir, EditorApplication.ScriptEditorAssemblyName);
  92. }
  93. Array.Copy(frameworkAssemblies, assemblies, frameworkAssemblies.Length);
  94. string defines = BuildManager.GetDefines(platform);
  95. return new CompilerInstance(scriptFiles.ToArray(), defines, assemblyFolders, assemblies, debug, outputFile);
  96. }
  97. }
  98. /// <summary>
  99. /// Represents a started compiler process used for compiling a set of script files into an assembly.
  100. /// </summary>
  101. public class CompilerInstance
  102. {
  103. private Process process;
  104. private Thread readErrorsThread;
  105. private List<CompilerMessage> errors = new List<CompilerMessage>();
  106. private List<CompilerMessage> warnings = new List<CompilerMessage>();
  107. private Regex compileErrorRegex = new Regex(@"\s*(?<file>.*)\(\s*(?<line>\d+)\s*,\s*(?<column>\d+)\s*\)\s*:\s*(?<type>warning|error)\s+(.*):\s*(?<message>.*)");
  108. private Regex compilerErrorRegex = new Regex(@"\s*error[^:]*:\s*(?<message>.*)");
  109. /// <summary>
  110. /// Creates a new compiler process and starts compilation of the provided files.
  111. /// </summary>
  112. /// <param name="files">Absolute paths to all the C# script files to compile.</param>
  113. /// <param name="defines">A set of semi-colon separated defines to provide to the compiler.</param>
  114. /// <param name="assemblyFolders">A set of folders containing the assemblies referenced by the script files.</param>
  115. /// <param name="assemblies">Names of the assemblies containing code referenced by the script files.</param>
  116. /// <param name="debugBuild">Determines should the assembly be compiled with additional debug information.</param>
  117. /// <param name="outputFile">Absolute path to the assembly file to generate.</param>
  118. internal CompilerInstance(string[] files, string defines, string[] assemblyFolders, string[] assemblies,
  119. bool debugBuild, string outputFile)
  120. {
  121. ProcessStartInfo procStartInfo = new ProcessStartInfo();
  122. StringBuilder argumentsBuilder = new StringBuilder();
  123. if (!string.IsNullOrEmpty(defines))
  124. argumentsBuilder.Append(" -d:" + defines);
  125. if (assemblyFolders != null && assemblyFolders.Length > 0)
  126. {
  127. argumentsBuilder.Append(" -lib:\"");
  128. for (int i = 0; i < assemblyFolders.Length - 1; i++)
  129. argumentsBuilder.Append(assemblyFolders[i] + ",");
  130. argumentsBuilder.Append(assemblyFolders[assemblyFolders.Length - 1] + "\"");
  131. }
  132. if (assemblies != null && assemblies.Length > 0)
  133. {
  134. argumentsBuilder.Append(" -r:");
  135. for (int i = 0; i < assemblies.Length - 1; i++)
  136. argumentsBuilder.Append(assemblies[i] + ",");
  137. argumentsBuilder.Append(assemblies[assemblies.Length - 1]);
  138. }
  139. if (debugBuild)
  140. argumentsBuilder.Append(" -debug+ -o-");
  141. else
  142. argumentsBuilder.Append(" -debug- -o+");
  143. argumentsBuilder.Append(" -target:library -out:" + "\"" + outputFile + "\"");
  144. for (int i = 0; i < files.Length; i++)
  145. argumentsBuilder.Append(" \"" + files[i] + "\"");
  146. if (File.Exists(outputFile))
  147. File.Delete(outputFile);
  148. string outputDir = Path.GetDirectoryName(outputFile);
  149. if (!Directory.Exists(outputDir))
  150. Directory.CreateDirectory(outputDir);
  151. procStartInfo.Arguments = argumentsBuilder.ToString();
  152. procStartInfo.CreateNoWindow = true;
  153. procStartInfo.FileName = EditorApplication.CompilerPath;
  154. procStartInfo.RedirectStandardError = true;
  155. procStartInfo.RedirectStandardOutput = false;
  156. procStartInfo.UseShellExecute = false;
  157. procStartInfo.WorkingDirectory = EditorApplication.ProjectPath;
  158. process = new Process();
  159. process.StartInfo = procStartInfo;
  160. process.Start();
  161. readErrorsThread = new Thread(ReadErrorStream);
  162. readErrorsThread.Start();
  163. }
  164. /// <summary>
  165. /// Worker thread method that continually checks for compiler error messages and warnings.
  166. /// </summary>
  167. private void ReadErrorStream()
  168. {
  169. while (true)
  170. {
  171. if (process == null || process.HasExited)
  172. return;
  173. string line = process.StandardError.ReadLine();
  174. if (string.IsNullOrEmpty(line))
  175. continue;
  176. CompilerMessage message;
  177. if (TryParseCompilerMessage(line, out message))
  178. {
  179. if (message.type == CompilerMessageType.Warning)
  180. {
  181. lock (warnings)
  182. warnings.Add(message);
  183. }
  184. else if (message.type == CompilerMessageType.Error)
  185. {
  186. lock (errors)
  187. errors.Add(message);
  188. }
  189. }
  190. }
  191. }
  192. /// <summary>
  193. /// Parses a compiler error or warning message into a more structured format.
  194. /// </summary>
  195. /// <param name="messageText">Text of the error or warning message.</param>
  196. /// <param name="message">Parsed structured version of the message.</param>
  197. /// <returns>True if the parsing was completed successfully, false otherwise.</returns>
  198. private bool TryParseCompilerMessage(string messageText, out CompilerMessage message)
  199. {
  200. message = new CompilerMessage();
  201. Match matchCompile = compileErrorRegex.Match(messageText);
  202. if (matchCompile.Success)
  203. {
  204. message.file = matchCompile.Groups["file"].Value;
  205. message.line = Int32.Parse(matchCompile.Groups["line"].Value);
  206. message.column = Int32.Parse(matchCompile.Groups["column"].Value);
  207. message.type = matchCompile.Groups["type"].Value == "error"
  208. ? CompilerMessageType.Error
  209. : CompilerMessageType.Warning;
  210. message.message = matchCompile.Groups["message"].Value;
  211. return true;
  212. }
  213. Match matchCompiler = compilerErrorRegex.Match(messageText);
  214. if (matchCompiler.Success)
  215. {
  216. message.file = "";
  217. message.line = 0;
  218. message.column = 0;
  219. message.type = CompilerMessageType.Error;
  220. message.message = matchCompiler.Groups["message"].Value;
  221. return true;
  222. }
  223. return false;
  224. }
  225. /// <summary>
  226. /// Checks is the compilation process done.
  227. /// </summary>
  228. public bool IsDone
  229. {
  230. get { return process.HasExited && readErrorsThread.ThreadState == System.Threading.ThreadState.Stopped; }
  231. }
  232. /// <summary>
  233. /// Checks has the compilAtion had any errors. Only valid after <see cref="IsDone"/> returns true.
  234. /// </summary>
  235. public bool HasErrors
  236. {
  237. get { return IsDone && process.ExitCode != 0; }
  238. }
  239. /// <summary>
  240. /// Returns all warning messages generated by the compiler.
  241. /// </summary>
  242. public CompilerMessage[] WarningMessages
  243. {
  244. get
  245. {
  246. lock (warnings)
  247. {
  248. return warnings.ToArray();
  249. }
  250. }
  251. }
  252. /// <summary>
  253. /// Returns all error messages generated by the compiler.
  254. /// </summary>
  255. public CompilerMessage[] ErrorMessages
  256. {
  257. get
  258. {
  259. lock (errors)
  260. {
  261. return errors.ToArray();
  262. }
  263. }
  264. }
  265. /// <summary>
  266. /// Disposes of the compiler process. Should be called when done when this object instance.
  267. /// </summary>
  268. public void Dispose()
  269. {
  270. if (process == null)
  271. return;
  272. if (!process.HasExited)
  273. {
  274. process.Kill();
  275. process.WaitForExit();
  276. }
  277. process.Dispose();
  278. }
  279. }
  280. /// <summary>
  281. /// Type of messages reported by the script compiler.
  282. /// </summary>
  283. public enum CompilerMessageType
  284. {
  285. Warning, Error
  286. }
  287. /// <summary>
  288. /// Data about a message reported by the compiler.
  289. /// </summary>
  290. public struct CompilerMessage
  291. {
  292. /// <summary>Type of the message.</summary>
  293. public CompilerMessageType type;
  294. /// <summary>Body of the message.</summary>
  295. public string message;
  296. /// <summary>Path ot the file the message is referencing.</summary>
  297. public string file;
  298. /// <summary>Line the message is referencing.</summary>
  299. public int line;
  300. /// <summary>Column the message is referencing.</summary>
  301. public int column;
  302. }
  303. /** @} */
  304. }