forked from esrever10/freeCompute
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.c
More file actions
121 lines (112 loc) · 2.14 KB
/
parser.c
File metadata and controls
121 lines (112 loc) · 2.14 KB
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
/*************************************************************************
> File Name: parser.c
> Author: ellochen
> Mail: god_mode@yeah.net
> Created Time: Wed May 8 23:24:27 2013
************************************************************************/
#include <stdio.h>
#include "parser.h"
#include "lex.h"
#include "token.h"
/*
Statement:
Expression
Expression:
Term
Expression + Term
Expression - Term
Term:
Primary
Term * Primary
Term / Primary
Primary:
Number
( Expression )
- Primary
+ Primary
Number:
double
*/
extern char *CURSOR;
static double expression();
static double primary()
{
char *back = CURSOR;
struct Token token = getNextToken();
if (TOKEN_DOUBLECONST == token.type) {
return token.var.d;
}else if (TOKEN_LPAREN == token.type) {
double var = expression();
back = CURSOR;
token = getNextToken();
if (TOKEN_RPAREN == token.type) {
return var;
}else {
printf("括号不匹配,错误字符:%d\n",token.type);
return -1;
}
}else if (TOKEN_PLUS == token.type) {
return primary();
}else if (TOKEN_MINUS == token.type) {
return -primary();
}else {
CURSOR = back;
return 1;
}
}
static double term()
{
double var = primary();
char *back = CURSOR;
struct Token token = getNextToken();
while(1) {
if (TOKEN_STAR == token.type) {
var *= primary();
back = CURSOR;
token = getNextToken();
}else if (TOKEN_SLASH == token.type) {
double temp = primary();
if (0 == temp) {
printf("除数不能为0\n");
return -1;
}else {
var /= temp;
}
back = CURSOR;
token = getNextToken();
}else if (TOKEN_LINEEND == token.type) {
break;
}else {
CURSOR = back;
break;
}
}
return var;
}
static double expression()
{
double var = term();
char *back = CURSOR;
struct Token token = getNextToken();
while(1) {
if (TOKEN_PLUS == token.type){
var += term();
back = CURSOR;
token = getNextToken();
}else if (TOKEN_MINUS == token.type) {
var -= term();
back = CURSOR;
token = getNextToken();
}else if (TOKEN_LINEEND == token.type) {
break;
}else {
CURSOR = back;
return var;
}
}
return var;
}
double statement()
{
return expression();
}