Calculator  Step 3
parse.hpp
Go to the documentation of this file.
1 #ifndef PARSE_HPP_
2 #define PARSE_HPP_
3 
4 #include <istream>
5 #include <locale>
6 #include <ostream>
7 #include <stdexcept>
8 #include <string>
9 
10 class node;
11 
13 class parse_error : public std::runtime_error {
14 public:
15  parse_error(std::string const& msg) : runtime_error{msg} {}
16 };
17 
30 class parser
31 {
32 public:
36  enum kind : int { eof, identifier, number,
37  plus='+', minus='-', times='*', slash='/', lparen = '(', rparen=')', equal='=' };
38 
42  parser(std::istream& input);
43 
49  bool get_expr(node& result);
50 
51 private:
56  std::string charify(char c);
62  bool get_number(std::string const& token, node& result);
70  bool get_add_expr(node& result);
78  bool get_mul_expr(node& result);
86  bool get_primary(node& result);
94  bool get_unary(node& result);
106  kind get_token(std::string& token);
111  void get_identifier(std::string& identifier);
112 
118  void push_back(std::string const& token, kind k) { token_ = token; kind_ = k; }
119 
124  bool isalpha(char c) const { return ctype_.is(ctype_.alpha, c); }
129  bool isalnum(char c) const { return ctype_.is(ctype_.alnum, c); }
134  bool isdigit(char c) const { return ctype_.is(ctype_.digit, c); }
139  bool isprint(char c) const { return ctype_.is(ctype_.print, c); }
140 
141  std::istream& input_;
142  std::ctype<char> const& ctype_;
143  std::string token_;
145 };
146 
152 void parse_loop(std::istream& input, std::ostream& output);
153 
154 #endif
void parse_loop(std::istream &input, std::ostream &output)
Definition: parse.cpp:272
bool isprint(char c) const
Definition: parse.hpp:139
bool get_expr(node &result)
Definition: parse.cpp:143
parser(std::istream &input)
Definition: parse.cpp:6
parse_error(std::string const &msg)
Definition: parse.hpp:15
void get_identifier(std::string &identifier)
Definition: parse.cpp:37
std::string charify(char c)
Definition: parse.cpp:13
Definition: node.hpp:16
void push_back(std::string const &token, kind k)
Definition: parse.hpp:118
Definition: parse.hpp:30
bool get_primary(node &result)
Definition: parse.cpp:244
bool get_unary(node &result)
Definition: parse.cpp:222
bool isalpha(char c) const
Definition: parse.hpp:124
kind get_token(std::string &token)
Definition: parse.cpp:56
std::string token_
One token push-back.
Definition: parse.hpp:143
std::istream & input_
Share the input stream.
Definition: parse.hpp:141
kind kind_
The kind of token that was pushed back.
Definition: parse.hpp:144
kind
Definition: parse.hpp:36
bool get_number(std::string const &token, node &result)
Definition: parse.cpp:129
std::ctype< char > const & ctype_
Cache the ctype facet for checking character categories.
Definition: parse.hpp:142
bool get_mul_expr(node &result)
Definition: parse.cpp:200
bool get_add_expr(node &result)
Definition: parse.cpp:178
bool isalnum(char c) const
Definition: parse.hpp:129
bool isdigit(char c) const
Definition: parse.hpp:134