-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExpressionParsing.h
122 lines (112 loc) · 3.11 KB
/
ExpressionParsing.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#ifndef EXPRESSIONS
#define EXPRESSIONS 0
#include<iostream>
#include<string>
#include<vector>
struct Token
{
std::string token;
char type; //n = number | i = identifier | o = operator | e = empty | 0 = null
//d = divider (i.e. parantheses or brackets)
};
Token GetToken(std::istream& in);
bool IsLetter(char ch){return ((ch >= 65 && ch <= 90)||(ch >= 97 && ch <= 122))?true:false;}
ExprStep ParseExpression (std::istream& in, Token& t,ExprStep &s,std::vector<ExprStep> &v) //returns a std::vector steps used to calculate expression
{
t = GetToken(in);
if(t.type == 'o' && (t.token=="-" || t.token=="+"))
{
s.type = 'u';
s.data.ufptr = NULL; //this is temporary
v.insert(v.end,s);
v.insert(v.end,ParseExpression(in,t,s,v));
}
//after expression stuff
t=GetToken(in);
/*
if op....
else if anything else, end of expression
*/
}
Token GetToken(std::istream& in)
{
Token t;
char ch;
cin.get(ch);
if(ch == ' ' || ch == '\t' || ch == '\r')//white space
return GetToken(in);
else if(ch >=48 && ch <= 57)//starts with digit: is a number
{
t.type = 'n';
t.token += ch;
ch = in.peek();
while(ch >=48 && ch <= 57)
{
in.get(ch);
t.token += ch;
ch = in.peek();
}
if(ch == '.')
{
in.get(ch);
ch = in.peek();
if(ch >=48 && ch <= 57)
{
t.token += '.';
t.token += ch;
in.get(ch);
ch = in.peek();
while(ch >=48 && ch <= 57)
{
in.get(ch);
t.token += ch;
ch = in.peek();
}
}
else
in.putback('.');
}
}
else if(IsLetter(ch)||(ch == '_'))
{//this token is an identifier
t.type = 'i';
t.token += ch;
ch = in.peek();
while(IsLetter(ch)||(ch == '_')||(ch >=48 && ch <= 57))
{
cin.get(ch);
t.token += ch;
ch = in.peek();
}
}
else if(!in)
{//no data
in.clear();
t.token = "";
t.type = '0';
}
else if(ch == '\n')
{//end of data
t.token = "";
t.type = '0';
}
else if(ch == '-' || ch == '+' || ch == '\\' ||
ch == '/' || ch == '*' || ch == '%')
{
t.token = ch;
t.type = 'o';
}
else if((ch == '(' || ch == ')' || ch == '[' ||
ch == ']' || ch == '{' || ch == '}')
{
t.token = ch;
t.type = 'd';
}
else
{
t.token = "0xERROR"; //error token: not valid number or identifier
t.type = 'e';
}
return t;
}
#endif