Calculator Step 4

- Main Page
- Classes
- Files

- File List
- File Members

variables.cpp
Go to the documentation of this file.
1 #include <map>
2
3 #include "calc_error.hpp"
4 #include "node.hpp"
5 #include "variables.hpp"
6
7 namespace {
8 symbol_table variables;
9 std::vector<symbol_table const*> symbol_tables;
10
11 class initializer {
12 public:
13 initializer() {
14 variables["pi"] = node(3.141592653589792);
15 variables["e"] = node(2.718281828459);
16 symbol_tables.push_back(&variables);
17 }
18 };
19 initializer init;
20 }
21
22 set_symbol_table::set_symbol_table(symbol_table const& locals)
23 {
24 symbol_tables.push_back(&locals);
25 }
26
27 set_symbol_table::~set_symbol_table()
28 {
29 symbol_tables.pop_back();
30 }
31
32 bool find_symbol(std::string const& name, node& value)
33 {
34 for (auto iter(symbol_tables.rbegin()), end(symbol_tables.rend()); iter != end; ++iter) {
35 symbol_table const& table{ **iter };
36 symbol_table::const_iterator entry{ table.find(name) };
37 if (entry != table.end()) {
38 value = entry->second;
39 return true;
40 }
41 }
42 return false;
43 }
44
45 node get_variable(std::string const& name)
46 {
47 node result{};
48 if (not find_symbol(name, result))
49 return node();
50 else if (result.get_parameters().empty())
51 return result;
52 else
53 throw function_error{name, result.get_parameters().size(), 0};
54 }
55
56 void set_variable(std::string const& name, node value)
57 {
58 variables[name] = value;
59 }
60
61 node get_function(std::string const& name)
62 {
63 node result{};
64 if (not find_symbol(name, result))
65 throw no_such_function{name};
66 else
67 return result;
68 }
69
70 void set_function(std::string const& name, node value)
71 {
72 set_variable(name, value);
73 }
get_function
node get_function(std::string const &name)
Definition: variables.cpp:61
find_symbol
bool find_symbol(std::string const &name, node &value)
Definition: variables.cpp:32
node
Definition: node.hpp:26
calc_error.hpp
set_variable
void set_variable(std::string const &name, node value)
Definition: variables.cpp:56
set_function
void set_function(std::string const &name, node value)
Definition: variables.cpp:70
function_error
Definition: calc_error.hpp:34
no_such_function
Definition: calc_error.hpp:45
set_symbol_table::~set_symbol_table
~set_symbol_table()
Definition: variables.cpp:27
node.hpp
variables.hpp
set_symbol_table::set_symbol_table
set_symbol_table(symbol_table const &symtab)
Definition: variables.cpp:22
get_variable
node get_variable(std::string const &name)
Definition: variables.cpp:45
symbol_table
std::map< std::string, node > symbol_table
Definition: variables.hpp:13