1/*=============================================================================
2 Copyright (c) 2001-2011 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_MINIC_VM_HPP)
8#define BOOST_SPIRIT_MINIC_VM_HPP
9
10#include <vector>
11
12namespace 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(std::vector<int> const& code)
62 {
63 return execute(code, pc: code.begin(), frame_ptr: stack.begin());
64 }
65
66 std::vector<int> const& get_stack() const { return stack; };
67 std::vector<int>& get_stack() { return stack; };
68
69 private:
70
71 int execute(
72 std::vector<int> const& code // the program code
73 , std::vector<int>::const_iterator pc // program counter
74 , std::vector<int>::iterator frame_ptr // start of arguments and locals
75 );
76
77 std::vector<int> stack;
78 };
79}
80
81#endif
82
83

source code of boost/libs/spirit/example/qi/compiler_tutorial/mini_c/vm.hpp