Pratt.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include "Lex.hpp"
4 
5 #include <unordered_map>
6 
7 namespace iv
8 {
9 
18 class Pratt
19 {
20 public:
21  struct Unary;
22  struct Binary;
23  struct Value;
24 
25  struct Expression
26  {
27  int line;
28  int column;
29 
30  int name;
31 
32  virtual ~Expression(){}
33  virtual Unary const * ToUnary() const { return nullptr; }
34  virtual Binary const * ToBinary() const { return nullptr; }
35  virtual Value const * ToValue() const { return nullptr; }
36  };
37 
38  struct Unary : public Expression
39  {
40  Expression const * child;
41 
42  virtual Unary const * ToUnary() const override { return this; }
43  };
44 
45  struct Binary : public Expression
46  {
47  Expression const * left;
48  Expression const * right;
49 
50  virtual Binary const * ToBinary() const override { return this; }
51  };
52 
53  struct Value : public Expression
54  {
60  std::string token_str;
61 
62  virtual Value const * ToValue() const override { return this; }
63  };
64 
65 public:
67 
68  Pratt( Instance * inst );
69  ~Pratt();
70 
71  Instance * instance();
72 
73  //------------- define expression structure ------------------------------------------------------
86  void def_unary( int name, int precedence, const char * op_left, bool child_mandatory, const char * op_right, bool phantom=false );
87 
93  void def_binary( int name, int precedence, const char * op_left, bool left_child_mandatory, const char * op_middle, bool right_child_mandatory, const char * op_right );
94  void def_value( int name );
95 
96  //----------------------------------------------------------------------------------------------------------
100  void define_operators( Lex * lex );
101 
107  void read_expression( Lex * lex );
108 
113  void clear();
114 
115  //------------------------------------------------------------------------------------------------------
120  Expression const * root();
121 
122 //------------------------------------------------------------------------------------------------------
123 private:
124  Expression * expr( int precedence, const char * terminator );
125 
126 private:
127  struct Def
128  {
129  int name;
130  int precedence;
131  bool unary;
132  bool phantom;
133 
134  std::string op_left;
135  bool child_mandatory;
136  std::string op_middle;
137  bool right_child_mandatory;
138  std::string op_right;
139  };
140 
141 private:
142  Instance * inst;
143  Lex * lex;
144  Expression * _root;
145  std::unordered_set< Def * > defs;
146 
147  std::unordered_set< std::string > operators;
148 
149  std::unordered_map< std::string, Def * > defs_prefix;
150  std::unordered_map< std::string, Def * > defs_nonprefix;
151  int value_name;
152 };
153 
154 }