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.

75 lines
2.4 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 void clear_variables() = 0;
  43. virtual int32_t op_count() = 0;
  44. virtual int32_t var_count() = 0;
  45. virtual void var_clear() = 0;
  46. virtual std::optional<script_value> varname_by_idx(int32_t idx) = 0;
  47. virtual std::optional<script_value> var_by_idx(int32_t idx) = 0;
  48. virtual script_value resolve(const std::string& name) = 0;
  49. virtual std::variant<script_value, std::vector<script_error>> executeAtOnce(std::string code) = 0;
  50. virtual std::vector<script_error> prepare(std::string code) = 0;
  51. virtual std::optional<script_error> stepOnce() = 0;
  52. virtual ~UserScript() = default;
  53. };
  54. struct UserScriptLibraryParameters {
  55. bool recursive_arrays = false;
  56. int32_t array_size_limit = 1024;
  57. int32_t string_size_limit = 1024;
  58. int32_t variables_count = 1024;
  59. };
  60. std::unique_ptr<UserScript> prepare_interpreter(const std::string& code);
  61. std::unique_ptr<UserScript> register_array_lib(std::unique_ptr<UserScript> target, const UserScriptLibraryParameters&);
  62. std::unique_ptr<UserScript> register_crypto_lib(std::unique_ptr<UserScript> target, const UserScriptLibraryParameters&);
  63. std::unique_ptr<UserScript> register_utils_lib(std::unique_ptr<UserScript> target, const UserScriptLibraryParameters&);
  64. }