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.

JSParser.h 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #ifndef JSPARSER_H
  2. #define JSPARSER_H
  3. #include <string>
  4. #include <vector>
  5. #include <map>
  6. // for gcc & shared_ptr
  7. #include <iostream>
  8. #include <memory>
  9. // Internal JS types: String, Number, Function, Array, Object
  10. // blocks/scopes?
  11. class js_internal_storage {
  12. public:
  13. // toString
  14. // toNumber
  15. // toFunction
  16. // toArray
  17. // toObject
  18. };
  19. class js_scope {
  20. public:
  21. js_scope *parent;
  22. // what do we need children for?
  23. // a callstack only includes it's parents (in JS?)
  24. std::vector<js_scope> children;
  25. js_scope() {
  26. parent = nullptr;
  27. }
  28. std::map<std::string, std::string> variables;
  29. std::map<std::string, js_internal_storage> data;
  30. // feel like we need an instruction pointer...
  31. // esp. for loops
  32. // but how we address tokens, by index?
  33. };
  34. class js_string : public js_internal_storage {
  35. public:
  36. std::string value;
  37. };
  38. class js_number : public js_internal_storage {
  39. public:
  40. signed long value;
  41. };
  42. class js_function : public js_internal_storage {
  43. public:
  44. std::vector<std::string> tokens;
  45. js_scope *parent; // usually global
  46. js_scope local;
  47. };
  48. class js_array : public js_internal_storage {
  49. public:
  50. std::vector<js_internal_storage> value;
  51. };
  52. class js_object : public js_internal_storage {
  53. public:
  54. std::map<std::string, js_internal_storage> value;
  55. };
  56. class JavaScript {
  57. public:
  58. void clear() {
  59. tokens.clear();
  60. rootScope.parent = nullptr;
  61. rootScope.children.clear();
  62. rootScope.variables.clear();
  63. }
  64. // each token is one statement
  65. std::vector<std::string> tokens;
  66. // we're just settings the rootScope.variables
  67. std::vector<std::string> definitions; // all var declarations and their expressions
  68. std::vector<std::string> instructions; // then a list of all remaining expressions and function calls
  69. js_scope rootScope;
  70. };
  71. class JSParser {
  72. public:
  73. std::shared_ptr<JavaScript> parse(const std::string &javascript) const;
  74. std::vector<std::string> getTokens(const std::string &source) const;
  75. std::shared_ptr<JavaScript> append(std::shared_ptr<JavaScript> &destination, const std::shared_ptr<JavaScript> &source) const;
  76. };
  77. #endif