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