Calculator  Step 5
node.cpp
Go to the documentation of this file.
1 #include <istream>
2 #include <stdexcept>
3 
4 #include "calc_error.hpp"
5 #include "node.hpp"
6 #include "node_impl.hpp"
7 
8 std::shared_ptr<node_impl> node::make_binary_operator(node left, char op, node right)
9 {
10  if (op == '+')
11  return std::make_shared<node_add>(left, right);
12  else if (op == '-')
13  return std::make_shared<node_subtract>(left, right);
14  else if (op == '*')
15  return std::make_shared<node_multiply>(left, right);
16  else if (op == '/')
17  return std::make_shared<node_divide>(left, right);
18  else
19  throw calc_error{"fatal error in make_binary_opreator: unknown operator: " + std::string(1,op)};
20 }
21 
23 : pimpl_{std::make_shared<node_void>()}
24 {}
25 
26 node::node(std::istream& stream)
28 {}
29 
30 node::node(double number)
31 : pimpl_{std::make_shared<node_number>(number)}
32 {}
33 
34 node::node(std::string identifier)
35 : pimpl_{std::make_shared<node_identifier>(identifier)}
36 {}
37 
38 node::node(char op, node operand)
39 : pimpl_{std::make_shared<node_negate>(operand)}
40 {}
41 
42 node::node(node left, char op, node right)
43 : pimpl_{make_binary_operator(left, op, right)}
44 {}
45 
46 node::node(identifier_list parameters, node definition)
47 : pimpl_{std::make_shared<node_function>(parameters, definition)}
48 {}
49 
50 node::node(std::string name, node_list arguments)
51 : pimpl_{std::make_shared<node_function_call>(name, arguments)}
52 {}
53 
54 void node::print(std::ostream& stream, int indent)
55 const
56 {
57  pimpl_->print(stream, indent);
58 }
59 
61 const
62 {
63  return pimpl_->evaluate();
64 }
65 
66 std::string node::to_string()
67 const
68 {
69  return pimpl_->to_string();
70 }
71 
73 const
74 {
75  return pimpl_->get_parameters();
76 }
77 
78 void node::save(std::ostream& stream)
79 const
80 {
81  pimpl_->save(stream);
82 }
Definition: node.hpp:26
std::shared_ptr< node_impl > pimpl_
Definition: node.hpp:100
static std::shared_ptr< node_impl > make_binary_operator(node, char, node)
Factory function to make the binary operator nodes.
Definition: node.cpp:8
std::vector< std::string > identifier_list
A sequence of identifiers (e.g., parameter names).
Definition: node.hpp:19
static std::shared_ptr< node_impl > read_node(std::istream &stream)
Definition: node_impl.cpp:64
void print(std::ostream &stream, int indent=0) const
Definition: node.cpp:54
std::string to_string() const
Definition: node.cpp:66
double evaluate() const
Definition: node.cpp:60
node()
Definition: node.cpp:22
identifier_list const & get_parameters() const
Definition: node.cpp:72
std::vector< node > node_list
A sequence of nodes.
Definition: node.hpp:13
void save(std::ostream &stream) const
Definition: node.cpp:78