vm.hpp 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*=============================================================================
  2. Copyright (c) 2001-2011 Joel de Guzman
  3. Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. =============================================================================*/
  6. #if !defined(BOOST_SPIRIT_CALC8_VM_HPP)
  7. #define BOOST_SPIRIT_CALC8_VM_HPP
  8. #include <vector>
  9. namespace client
  10. {
  11. ///////////////////////////////////////////////////////////////////////////
  12. // The Virtual Machine
  13. ///////////////////////////////////////////////////////////////////////////
  14. enum byte_code
  15. {
  16. op_neg, // negate the top stack entry
  17. op_add, // add top two stack entries
  18. op_sub, // subtract top two stack entries
  19. op_mul, // multiply top two stack entries
  20. op_div, // divide top two stack entries
  21. op_not, // boolean negate the top stack entry
  22. op_eq, // compare the top two stack entries for ==
  23. op_neq, // compare the top two stack entries for !=
  24. op_lt, // compare the top two stack entries for <
  25. op_lte, // compare the top two stack entries for <=
  26. op_gt, // compare the top two stack entries for >
  27. op_gte, // compare the top two stack entries for >=
  28. op_and, // logical and top two stack entries
  29. op_or, // logical or top two stack entries
  30. op_load, // load a variable
  31. op_store, // store a variable
  32. op_int, // push constant integer into the stack
  33. op_true, // push constant 0 into the stack
  34. op_false, // push constant 1 into the stack
  35. op_jump_if, // jump to a relative position in the code if top stack
  36. // evaluates to false
  37. op_jump, // jump to a relative position in the code
  38. op_stk_adj, // adjust the stack (for args and locals)
  39. op_call, // function call
  40. op_return // return from function
  41. };
  42. class vmachine
  43. {
  44. public:
  45. vmachine(unsigned stackSize = 4096)
  46. : stack(stackSize)
  47. {
  48. }
  49. int execute(
  50. std::vector<int> const& code // the program code
  51. , std::vector<int>::const_iterator pc // program counter
  52. , std::vector<int>::iterator frame_ptr // start of arguments and locals
  53. );
  54. int execute(std::vector<int> const& code)
  55. {
  56. return execute(code, code.begin(), stack.begin());
  57. };
  58. std::vector<int> stack;
  59. };
  60. }
  61. #endif