ScriptCompiler.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 bs;
  11. namespace bs.Editor
  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. argumentsBuilder.Append("\"" + EditorApplication.CompilerPath + "\"");
  124. string monoDir = Path.GetDirectoryName(EditorApplication.CompilerPath);
  125. monoDir = Path.Combine(monoDir, "../");
  126. argumentsBuilder.Append(" \"" + monoDir + "\"");
  127. argumentsBuilder.Append(" -noconfig");
  128. if (!string.IsNullOrEmpty(defines))
  129. argumentsBuilder.Append(" -d:" + defines);
  130. if (assemblyFolders != null && assemblyFolders.Length > 0)
  131. {
  132. argumentsBuilder.Append(" -lib:\"");
  133. for (int i = 0; i < assemblyFolders.Length - 1; i++)
  134. argumentsBuilder.Append(assemblyFolders[i] + ",");
  135. argumentsBuilder.Append(assemblyFolders[assemblyFolders.Length - 1] + "\"");
  136. }
  137. if (assemblies != null && assemblies.Length > 0)
  138. {
  139. argumentsBuilder.Append(" -r:");
  140. for (int i = 0; i < assemblies.Length - 1; i++)
  141. argumentsBuilder.Append(assemblies[i] + ",");
  142. argumentsBuilder.Append(assemblies[assemblies.Length - 1]);
  143. }
  144. if (debugBuild)
  145. argumentsBuilder.Append(" -debug+ -o-");
  146. else
  147. argumentsBuilder.Append(" -debug- -o+");
  148. argumentsBuilder.Append(" -target:library -out:" + "\"" + outputFile + "\"");
  149. for (int i = 0; i < files.Length; i++)
  150. argumentsBuilder.Append(" \"" + files[i] + "\"");
  151. if (File.Exists(outputFile))
  152. File.Delete(outputFile);
  153. string outputDir = Path.GetDirectoryName(outputFile);
  154. if (!Directory.Exists(outputDir))
  155. Directory.CreateDirectory(outputDir);
  156. procStartInfo.Arguments = argumentsBuilder.ToString();
  157. procStartInfo.CreateNoWindow = true;
  158. procStartInfo.FileName = EditorApplication.MonoExecPath;
  159. procStartInfo.RedirectStandardError = true;
  160. procStartInfo.RedirectStandardOutput = false;
  161. procStartInfo.UseShellExecute = false;
  162. procStartInfo.WorkingDirectory = EditorApplication.ProjectPath;
  163. process = new Process();
  164. process.StartInfo = procStartInfo;
  165. process.Start();
  166. readErrorsThread = new Thread(ReadErrorStream);
  167. readErrorsThread.Start();
  168. }
  169. /// <summary>
  170. /// Worker thread method that continually checks for compiler error messages and warnings.
  171. /// </summary>
  172. private void ReadErrorStream()
  173. {
  174. while (true)
  175. {
  176. if (process == null || process.HasExited)
  177. return;
  178. string line = process.StandardError.ReadLine();
  179. if (string.IsNullOrEmpty(line))
  180. continue;
  181. CompilerMessage message;
  182. if (TryParseCompilerMessage(line, out message))
  183. {
  184. if (message.type == CompilerMessageType.Warning)
  185. {
  186. lock (warnings)
  187. warnings.Add(message);
  188. }
  189. else if (message.type == CompilerMessageType.Error)
  190. {
  191. lock (errors)
  192. errors.Add(message);
  193. }
  194. }
  195. }
  196. }
  197. /// <summary>
  198. /// Parses a compiler error or warning message into a more structured format.
  199. /// </summary>
  200. /// <param name="messageText">Text of the error or warning message.</param>
  201. /// <param name="message">Parsed structured version of the message.</param>
  202. /// <returns>True if the parsing was completed successfully, false otherwise.</returns>
  203. private bool TryParseCompilerMessage(string messageText, out CompilerMessage message)
  204. {
  205. message = new CompilerMessage();
  206. Match matchCompile = compileErrorRegex.Match(messageText);
  207. if (matchCompile.Success)
  208. {
  209. message.file = matchCompile.Groups["file"].Value;
  210. message.line = Int32.Parse(matchCompile.Groups["line"].Value);
  211. message.column = Int32.Parse(matchCompile.Groups["column"].Value);
  212. message.type = matchCompile.Groups["type"].Value == "error"
  213. ? CompilerMessageType.Error
  214. : CompilerMessageType.Warning;
  215. message.message = matchCompile.Groups["message"].Value;
  216. return true;
  217. }
  218. Match matchCompiler = compilerErrorRegex.Match(messageText);
  219. if (matchCompiler.Success)
  220. {
  221. message.file = "";
  222. message.line = 0;
  223. message.column = 0;
  224. message.type = CompilerMessageType.Error;
  225. message.message = matchCompiler.Groups["message"].Value;
  226. return true;
  227. }
  228. return false;
  229. }
  230. /// <summary>
  231. /// Checks is the compilation process done.
  232. /// </summary>
  233. public bool IsDone
  234. {
  235. get { return process.HasExited && readErrorsThread.ThreadState == System.Threading.ThreadState.Stopped; }
  236. }
  237. /// <summary>
  238. /// Checks has the compilAtion had any errors. Only valid after <see cref="IsDone"/> returns true.
  239. /// </summary>
  240. public bool HasErrors
  241. {
  242. get { return IsDone && process.ExitCode != 0; }
  243. }
  244. /// <summary>
  245. /// Returns all warning messages generated by the compiler.
  246. /// </summary>
  247. public CompilerMessage[] WarningMessages
  248. {
  249. get
  250. {
  251. lock (warnings)
  252. {
  253. return warnings.ToArray();
  254. }
  255. }
  256. }
  257. /// <summary>
  258. /// Returns all error messages generated by the compiler.
  259. /// </summary>
  260. public CompilerMessage[] ErrorMessages
  261. {
  262. get
  263. {
  264. lock (errors)
  265. {
  266. return errors.ToArray();
  267. }
  268. }
  269. }
  270. /// <summary>
  271. /// Disposes of the compiler process. Should be called when done when this object instance.
  272. /// </summary>
  273. public void Dispose()
  274. {
  275. if (process == null)
  276. return;
  277. if (!process.HasExited)
  278. {
  279. process.Kill();
  280. process.WaitForExit();
  281. }
  282. process.Dispose();
  283. }
  284. }
  285. /// <summary>
  286. /// Type of messages reported by the script compiler.
  287. /// </summary>
  288. public enum CompilerMessageType
  289. {
  290. Warning, Error
  291. }
  292. /// <summary>
  293. /// Data about a message reported by the compiler.
  294. /// </summary>
  295. public struct CompilerMessage
  296. {
  297. /// <summary>Type of the message.</summary>
  298. public CompilerMessageType type;
  299. /// <summary>Body of the message.</summary>
  300. public string message;
  301. /// <summary>Path ot the file the message is referencing.</summary>
  302. public string file;
  303. /// <summary>Line the message is referencing.</summary>
  304. public int line;
  305. /// <summary>Column the message is referencing.</summary>
  306. public int column;
  307. }
  308. /** @} */
  309. }