This repository has been archived by the owner on May 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser.java
145 lines (131 loc) · 4.24 KB
/
Parser.java
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import java.io.*;
public class Parser {
private Lexer lex;
private BufferedReader pbr;
private Token look;
public Parser(Lexer l, BufferedReader br)
{
lex = l;
pbr = br;
move();
}
void move()
{
look = lex.lexical_scan(pbr);
System.err.println("token = " + look);
}
void error(String s)
{
throw new Error("near line " + lex.line + ": " + s);
}
void match(int t)
{
if (look.tag == t)
{
if (look.tag != Tag.EOF) move();
} else error("syntax error");
}
public void start()
{
if (look.tag == Tag.NUM || look.tag == '(')
{
expr();
match(Tag.EOF);
}
else if(look.tag == Tag.EOF)
{
match(Tag.EOF);
System.out.println("Nessun espressione");
}
else error("l'espressione non puo iniziare con " + look);
}
private void expr()
{
if(look.tag == '(' || look.tag == Tag.NUM)
{
term();
exprp();
}
else error("Era atteso '(' o NUM");
}
private void exprp()
{
if(look.tag == '+' || look.tag == '-')
{
switch (look.tag)
{
case '+':
match('+');
term();
exprp();
break;
case '-':
match('-');
term();
exprp();
break;
}
}
else if(look.tag == Tag.EOF || look.tag == ')'){}
else error("errore in exprp");
}
private void term()
{
if(look.tag == '(' || look.tag == Tag.NUM)
{
fact();
termp();
}
else error("errore in term");
}
private void termp()
{
if(look.tag == '*' || look.tag == '/')
{
switch (look.tag)
{
case '*':
match('*');
fact();
termp();
break;
case '/':
match('/');
fact();
termp();
break;
}
}
else if(look.tag == Tag.EOF || look.tag == ')' || look.tag == '+' || look.tag == '-'){}
else error("Errore in termp");
}
private void fact()
{
if(look.tag == Tag.NUM)
{
match(Tag.NUM);
}
else if(look.tag == '(')
{
match('(');
expr();
match(')');
}
else error("Errore in fact");
}
public static void main(String[] args)
{
Lexer lex = new Lexer();
String path = "Prova.txt"; // il percorso del file da leggere
try {
BufferedReader br = new BufferedReader(new FileReader(path));
Parser parser = new Parser(lex, br);
parser.start();
System.out.println("Input OK");
br.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}