You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.8 KiB

  1. #pragma once
  2. #include <memory>
  3. #include <string>
  4. #include <variant>
  5. #include <deque>
  6. #include <vector>
  7. #include <optional>
  8. namespace scripting {
  9. struct null {};
  10. struct array;
  11. using script_value = std::variant<null, int32_t, std::string, array>;
  12. struct script_variable {
  13. std::string name;
  14. };
  15. struct code_location {
  16. std::shared_ptr<const std::string> line_contents;
  17. int32_t line_number;
  18. int32_t column_number;
  19. };
  20. struct script_error {
  21. std::shared_ptr<const code_location> location;
  22. std::string message;
  23. };
  24. struct array {
  25. std::deque<script_value> value;
  26. operator std::deque<script_value>&() {
  27. return value;
  28. }
  29. };
  30. using argument = std::variant<script_value, script_variable>;
  31. class UserScript;
  32. struct function_impl {
  33. virtual std::optional<script_value> apply(UserScript* self, std::vector<argument>, std::optional<script_error>&) = 0;
  34. virtual ~function_impl() = default;
  35. };
  36. using function = std::unique_ptr<function_impl>;
  37. class UserScript {
  38. public:
  39. virtual std::optional<std::reference_wrapper<script_value>> getValue(const std::string& name) = 0;
  40. virtual bool setValue(const std::string& name, script_value value) = 0;
  41. virtual void registerFunction(std::string name, function fn) = 0;
  42. virtual script_value resolve(const std::string& name) = 0;
  43. virtual std::variant<script_value, std::vector<script_error>> executeAtOnce(std::string code) = 0;
  44. virtual std::vector<script_error> prepare(std::string code) = 0;
  45. virtual std::optional<script_error> stepOnce() = 0;
  46. virtual ~UserScript() = default;
  47. };
  48. std::unique_ptr<UserScript> prepare_interpreter(const std::string& code);
  49. std::unique_ptr<UserScript> register_array_lib(std::unique_ptr<UserScript> target, bool recursive_arrays = false, int32_t size_limit = 1024);
  50. }