ScriptCompiler.cs 13 KB

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