ScriptCompiler.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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[] frameworkAssemblies = BuildManager.GetFrameworkAssemblies(platform);
  62. if (type == ScriptAssemblyType.Game)
  63. {
  64. assemblyFolders = new string[]
  65. {
  66. EditorApplication.BuiltinAssemblyPath,
  67. EditorApplication.FrameworkAssemblyPath
  68. };
  69. assemblies = new string[frameworkAssemblies.Length + 1];
  70. assemblies[assemblies.Length - 1] = EditorApplication.EngineAssemblyName;
  71. outputFile = Path.Combine(outputDir, EditorApplication.ScriptGameAssemblyName);
  72. }
  73. else
  74. {
  75. assemblyFolders = new string[]
  76. {
  77. EditorApplication.BuiltinAssemblyPath,
  78. EditorApplication.FrameworkAssemblyPath,
  79. EditorApplication.ScriptAssemblyPath
  80. };
  81. assemblies = new string[frameworkAssemblies.Length + 3];
  82. assemblies[assemblies.Length - 1] = EditorApplication.EngineAssemblyName;
  83. assemblies[assemblies.Length - 2] = EditorApplication.EditorAssemblyName;
  84. assemblies[assemblies.Length - 3] = EditorApplication.ScriptGameAssemblyName;
  85. outputFile = Path.Combine(outputDir, EditorApplication.ScriptEditorAssemblyName);
  86. }
  87. Array.Copy(frameworkAssemblies, assemblies, frameworkAssemblies.Length);
  88. string defines = BuildManager.GetDefines(platform);
  89. return new CompilerInstance(scriptFiles.ToArray(), defines, assemblyFolders, assemblies, debug, outputFile);
  90. }
  91. }
  92. /// <summary>
  93. /// Represents a started compiler process used for compiling a set of script files into an assembly.
  94. /// </summary>
  95. public class CompilerInstance
  96. {
  97. private Process process;
  98. private Thread readErrorsThread;
  99. private List<CompilerMessage> errors = new List<CompilerMessage>();
  100. private List<CompilerMessage> warnings = new List<CompilerMessage>();
  101. private Regex compileErrorRegex = new Regex(@"\s*(?<file>.*)\(\s*(?<line>\d+)\s*,\s*(?<column>\d+)\s*\)\s*:\s*(?<type>warning|error)\s+(.*):\s*(?<message>.*)");
  102. private Regex compilerErrorRegex = new Regex(@"\s*error[^:]*:\s*(?<message>.*)");
  103. /// <summary>
  104. /// Creates a new compiler process and starts compilation of the provided files.
  105. /// </summary>
  106. /// <param name="files">Absolute paths to all the C# script files to compile.</param>
  107. /// <param name="defines">A set of semi-colon separated defines to provide to the compiler.</param>
  108. /// <param name="assemblyFolders">A set of folders containing the assemblies referenced by the script files.</param>
  109. /// <param name="assemblies">Names of the assemblies containing code referenced by the script files.</param>
  110. /// <param name="debugBuild">Determines should the assembly be compiled with additional debug information.</param>
  111. /// <param name="outputFile">Absolute path to the assembly file to generate.</param>
  112. internal CompilerInstance(string[] files, string defines, string[] assemblyFolders, string[] assemblies,
  113. bool debugBuild, string outputFile)
  114. {
  115. ProcessStartInfo procStartInfo = new ProcessStartInfo();
  116. StringBuilder argumentsBuilder = new StringBuilder();
  117. if (!string.IsNullOrEmpty(defines))
  118. argumentsBuilder.Append(" -d:" + defines);
  119. if (assemblyFolders != null && assemblyFolders.Length > 0)
  120. {
  121. argumentsBuilder.Append(" -lib:");
  122. for (int i = 0; i < assemblyFolders.Length - 1; i++)
  123. argumentsBuilder.Append(assemblyFolders[i] + ",");
  124. argumentsBuilder.Append(assemblyFolders[assemblyFolders.Length - 1]);
  125. }
  126. if (assemblies != null && assemblies.Length > 0)
  127. {
  128. argumentsBuilder.Append(" -r:");
  129. for (int i = 0; i < assemblies.Length - 1; i++)
  130. argumentsBuilder.Append(assemblies[i] + ",");
  131. argumentsBuilder.Append(assemblies[assemblies.Length - 1]);
  132. }
  133. if (debugBuild)
  134. argumentsBuilder.Append(" -debug+ -o-");
  135. else
  136. argumentsBuilder.Append(" -debug- -o+");
  137. argumentsBuilder.Append(" -target:library -out:" + "\"" + outputFile + "\"");
  138. for (int i = 0; i < files.Length; i++)
  139. argumentsBuilder.Append(" \"" + files[i] + "\"");
  140. if (File.Exists(outputFile))
  141. File.Delete(outputFile);
  142. string outputDir = Path.GetDirectoryName(outputFile);
  143. if (!Directory.Exists(outputDir))
  144. Directory.CreateDirectory(outputDir);
  145. procStartInfo.Arguments = argumentsBuilder.ToString();
  146. procStartInfo.CreateNoWindow = true;
  147. procStartInfo.FileName = EditorApplication.CompilerPath;
  148. procStartInfo.RedirectStandardError = true;
  149. procStartInfo.RedirectStandardOutput = false;
  150. procStartInfo.UseShellExecute = false;
  151. procStartInfo.WorkingDirectory = EditorApplication.ProjectPath;
  152. process = new Process();
  153. process.StartInfo = procStartInfo;
  154. process.Start();
  155. readErrorsThread = new Thread(ReadErrorStream);
  156. readErrorsThread.Start();
  157. }
  158. /// <summary>
  159. /// Worker thread method that continually checks for compiler error messages and warnings.
  160. /// </summary>
  161. private void ReadErrorStream()
  162. {
  163. while (true)
  164. {
  165. if (process == null || process.HasExited)
  166. return;
  167. string line = process.StandardError.ReadLine();
  168. if (string.IsNullOrEmpty(line))
  169. continue;
  170. CompilerMessage message;
  171. if (TryParseCompilerMessage(line, out message))
  172. {
  173. if (message.type == CompilerMessageType.Warning)
  174. {
  175. lock (warnings)
  176. warnings.Add(message);
  177. }
  178. else if (message.type == CompilerMessageType.Error)
  179. {
  180. lock (errors)
  181. errors.Add(message);
  182. }
  183. }
  184. }
  185. }
  186. /// <summary>
  187. /// Parses a compiler error or warning message into a more structured format.
  188. /// </summary>
  189. /// <param name="messageText">Text of the error or warning message.</param>
  190. /// <param name="message">Parsed structured version of the message.</param>
  191. /// <returns>True if the parsing was completed successfully, false otherwise.</returns>
  192. private bool TryParseCompilerMessage(string messageText, out CompilerMessage message)
  193. {
  194. message = new CompilerMessage();
  195. Match matchCompile = compileErrorRegex.Match(messageText);
  196. if (matchCompile.Success)
  197. {
  198. message.file = matchCompile.Groups["file"].Value;
  199. message.line = Int32.Parse(matchCompile.Groups["line"].Value);
  200. message.column = Int32.Parse(matchCompile.Groups["column"].Value);
  201. message.type = matchCompile.Groups["type"].Value == "error"
  202. ? CompilerMessageType.Error
  203. : CompilerMessageType.Warning;
  204. message.message = matchCompile.Groups["message"].Value;
  205. return true;
  206. }
  207. Match matchCompiler = compilerErrorRegex.Match(messageText);
  208. if (matchCompiler.Success)
  209. {
  210. message.file = "";
  211. message.line = 0;
  212. message.column = 0;
  213. message.type = CompilerMessageType.Error;
  214. message.message = matchCompiler.Groups["message"].Value;
  215. return true;
  216. }
  217. return false;
  218. }
  219. /// <summary>
  220. /// Checks is the compilation process done.
  221. /// </summary>
  222. public bool IsDone
  223. {
  224. get { return process.HasExited && readErrorsThread.ThreadState == System.Threading.ThreadState.Stopped; }
  225. }
  226. /// <summary>
  227. /// Checks has the compilAtion had any errors. Only valid after <see cref="IsDone"/> returns true.
  228. /// </summary>
  229. public bool HasErrors
  230. {
  231. get { return IsDone && process.ExitCode != 0; }
  232. }
  233. /// <summary>
  234. /// Returns all warning messages generated by the compiler.
  235. /// </summary>
  236. public CompilerMessage[] WarningMessages
  237. {
  238. get
  239. {
  240. lock (warnings)
  241. {
  242. return warnings.ToArray();
  243. }
  244. }
  245. }
  246. /// <summary>
  247. /// Returns all error messages generated by the compiler.
  248. /// </summary>
  249. public CompilerMessage[] ErrorMessages
  250. {
  251. get
  252. {
  253. lock (errors)
  254. {
  255. return errors.ToArray();
  256. }
  257. }
  258. }
  259. /// <summary>
  260. /// Disposes of the compiler process. Should be called when done when this object instance.
  261. /// </summary>
  262. public void Dispose()
  263. {
  264. if (process == null)
  265. return;
  266. if (!process.HasExited)
  267. {
  268. process.Kill();
  269. process.WaitForExit();
  270. }
  271. process.Dispose();
  272. }
  273. }
  274. /// <summary>
  275. /// Type of messages reported by the script compiler.
  276. /// </summary>
  277. public enum CompilerMessageType
  278. {
  279. Warning, Error
  280. }
  281. /// <summary>
  282. /// Data about a message reported by the compiler.
  283. /// </summary>
  284. public struct CompilerMessage
  285. {
  286. /// <summary>Type of the message.</summary>
  287. public CompilerMessageType type;
  288. /// <summary>Body of the message.</summary>
  289. public string message;
  290. /// <summary>Path ot the file the message is referencing.</summary>
  291. public string file;
  292. /// <summary>Line the message is referencing.</summary>
  293. public int line;
  294. /// <summary>Column the message is referencing.</summary>
  295. public int column;
  296. }
  297. }