2
0

lua_resource.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright (c) 2012-2018 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/dbartolini/crown/blob/master/LICENSE
  4. */
  5. #include "config.h"
  6. #include "core/containers/array.h"
  7. #include "core/filesystem/file.h"
  8. #include "core/memory/temp_allocator.h"
  9. #include "core/process.h"
  10. #include "core/strings/dynamic_string.h"
  11. #include "core/strings/string_stream.h"
  12. #include "resource/compile_options.h"
  13. #include "resource/lua_resource.h"
  14. #if CROWN_DEBUG
  15. #define LUAJIT_FLAGS "-bg" // Keep debug info
  16. #else
  17. #define LUAJIT_FLAGS "-b"
  18. #endif // CROWN_DEBUG
  19. namespace crown
  20. {
  21. namespace lua_resource_internal
  22. {
  23. s32 compile(CompileOptions& opts)
  24. {
  25. TempAllocator1024 ta;
  26. DynamicString luasrc(ta);
  27. DynamicString luabin(ta);
  28. opts.get_absolute_path(opts.source_path(), luasrc);
  29. opts.get_temporary_path("lua", luabin);
  30. const char* argv[] =
  31. {
  32. EXE_PATH("luajit"),
  33. LUAJIT_FLAGS,
  34. luasrc.c_str(),
  35. luabin.c_str(),
  36. NULL
  37. };
  38. Process pr;
  39. s32 sc = pr.spawn(argv, ProcessFlags::STDOUT_PIPE | ProcessFlags::STDERR_MERGE);
  40. DATA_COMPILER_ASSERT(sc == 0
  41. , opts
  42. , "Failed to spawn `%s`"
  43. , argv[0]
  44. );
  45. StringStream output(ta);
  46. // Read error messages if any
  47. {
  48. char err[512];
  49. while (pr.fgets(err, sizeof(err)) != NULL)
  50. output << err;
  51. }
  52. s32 ec = pr.wait();
  53. DATA_COMPILER_ASSERT(ec == 0
  54. , opts
  55. , "Failed to compile lua:\n%s"
  56. , string_stream::c_str(output)
  57. );
  58. Buffer blob = opts.read_temporary(luabin.c_str());
  59. opts.delete_file(luabin.c_str());
  60. LuaResource lr;
  61. lr.version = RESOURCE_VERSION_SCRIPT;
  62. lr.size = array::size(blob);
  63. opts.write(lr.version);
  64. opts.write(lr.size);
  65. opts.write(blob);
  66. return 0;
  67. }
  68. } // namespace lua_resource_internal
  69. namespace lua_resource
  70. {
  71. const char* program(const LuaResource* lr)
  72. {
  73. return (char*)&lr[1];
  74. }
  75. } // namespace lua_resource
  76. } // namespace crown