lua_resource.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright (c) 2012-2020 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.inl"
  7. #include "core/filesystem/file.h"
  8. #include "core/memory/temp_allocator.inl"
  9. #include "core/process.h"
  10. #include "core/strings/dynamic_string.inl"
  11. #include "core/strings/string_stream.inl"
  12. #include "resource/compile_options.inl"
  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
  22. {
  23. const char* program(const LuaResource* lr)
  24. {
  25. return (char*)&lr[1];
  26. }
  27. } // namespace lua_resource
  28. #if CROWN_CAN_COMPILE
  29. namespace lua_resource_internal
  30. {
  31. s32 compile(CompileOptions& opts)
  32. {
  33. TempAllocator1024 ta;
  34. DynamicString lua_src(ta);
  35. DynamicString lua_out(ta);
  36. opts.absolute_path(lua_src, opts.source_path());
  37. opts.temporary_path(lua_out, "lua");
  38. const char* argv[] =
  39. {
  40. EXE_PATH("luajit"),
  41. LUAJIT_FLAGS,
  42. lua_src.c_str(),
  43. lua_out.c_str(),
  44. NULL
  45. };
  46. Process pr;
  47. s32 sc = pr.spawn(argv, ProcessFlags::STDOUT_PIPE | ProcessFlags::STDERR_MERGE);
  48. DATA_COMPILER_ASSERT(sc == 0
  49. , opts
  50. , "Failed to spawn `%s`"
  51. , argv[0]
  52. );
  53. StringStream output(ta);
  54. // Read error messages if any
  55. {
  56. char err[512];
  57. while (pr.fgets(err, sizeof(err)) != NULL)
  58. output << err;
  59. }
  60. s32 ec = pr.wait();
  61. DATA_COMPILER_ASSERT(ec == 0
  62. , opts
  63. , "Failed to compile lua:\n%s"
  64. , string_stream::c_str(output)
  65. );
  66. Buffer blob = opts.read_temporary(lua_out.c_str());
  67. opts.delete_file(lua_out.c_str());
  68. LuaResource lr;
  69. lr.version = RESOURCE_HEADER(RESOURCE_VERSION_SCRIPT);
  70. lr.size = array::size(blob);
  71. opts.write(lr.version);
  72. opts.write(lr.size);
  73. opts.write(blob);
  74. return 0;
  75. }
  76. } // namespace lua_resource_internal
  77. #endif // CROWN_CAN_COMPILE
  78. } // namespace crown