Created by natalia on 19 04 14 package CompilerGenerator lex Created b

  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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
/**
* Created by natalia on 19.04.14.
*/
//package CompilerGenerator.lex;
/**
* Created by natalia on 05.04.14.
*/
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.util.ArrayList;
class Reader {
private File openedFile_;
private BufferedReader reader_;
private ArrayList<String> readedText_;
public Reader(String path) {
openedFile_ = new File(path);
try {
reader_ = new BufferedReader(new InputStreamReader(new FileInputStream(openedFile_), "UTF-8"));
} catch (UnsupportedEncodingException exc) {
System.out.println(" UTF-8 exception. " + exc.getMessage());
} catch (FileNotFoundException exc) {
System.out.println("File Not Found. " + exc.getMessage());
}
readedText_ = new ArrayList<String>();
}
public ArrayList<String> Read() {
String currentString;
try {
while((currentString = reader_.readLine()) != null) {
readedText_.add(currentString);
}
} catch (IOException exc) {
System.out.println("IOException while reading file. " + exc.getMessage());
}
return new ArrayList<String>(readedText_);
}
}
enum tokenType {
N, T, R, LP, RP, LFP, RFP, OR, E, TERM, NTERM
}
class Token {
tokenType type;
String value;
String coords;
public Token(tokenType t, String v) {
type = t;
value = v;
}
public Token(tokenType t, String v, String c) {
type = t;
value = v;
coords = c;
}
public tokenType getType() {
return type;
}
public String toString() {
return type + " - " + value;
}
}
enum nodeType {
TERM, NTERM, CLOSURE, FIGCLOSURE, ALTERNATIVE
}
class Node {
nodeType type;
public Node(nodeType t) {
type = t;
}
public nodeType getType() { return type; }
public String toString() {
return "";
}
}
class Atom extends Node {
String value;
public Atom(nodeType t, String v) {
super(t);
value = v;
}
public String getValue() { return value; }
public String toString() {
return value;
}
}
class Closure extends Node {
Node alt;
public Closure(nodeType t, Node n) {
super(t);
alt = n;
}
//public LinkedList<Node> getValue() { return tokens; }
public Node getValue() { return alt;}
public String toString() {
//System.out.println("CLOSURE!!!");
String sk = "", cl;
if(this.getType() == nodeType.CLOSURE) {
sk = "( "; cl = " )";
} else {
sk = "{ "; cl = "}";
}
String s = sk;
s += alt.toString();
return s + cl;
}
}
class Alternative extends Node {
LinkedList<LinkedList<Node>> alts;
public Alternative(nodeType t, LinkedList<LinkedList<Node>> a) {
super(t);
alts = a;
}
public LinkedList<LinkedList<Node>> getValue() { return alts; }
public String toString() {
String s = "";
for(LinkedList<Node> l: alts) {
if (l != null)
for (Node n : l) {
if (n != null)
s += n.toString();
}
s += " | ";
}
return s.substring(0, s.length()-2);
}
}
class Parse {
List<Token> tokens = new LinkedList<Token>();
LinkedList<String> nterms = new LinkedList<String>();
LinkedList<String> terms = new LinkedList<String>();
HashMap<String , Node> rules = new HashMap<String, Node>();
public Parse(List<Token> t) {
tokens = t;
}
public void error(String coords, String message) {
System.out.print("Syntax error at " + coords + ": " + message);
System.exit(1);
}
//count first
HashMap<String, LinkedList<String>> first = new HashMap<String, LinkedList<String>>();
public LinkedList<String> countFirstForConcat(LinkedList<Node> n) {
LinkedList<String> result = F(n.get(0));
if(result.contains("$EPS")) {
result.remove("$EPS");
LinkedList<Node> copy = (LinkedList<Node>)n.clone();
copy.remove(0);
result = Union(result, countFirstForConcat(copy));
}
return result;
}
public LinkedList<String> F(Node n) {
LinkedList<String> result = new LinkedList<String>();
switch (n.getType()) {
case TERM:
Atom a = (Atom)n;
result.add(a.getValue());
break;
case NTERM:
Atom ab = (Atom)n;
result = first.get(ab.getValue());
break;
case ALTERNATIVE:
Alternative al = (Alternative)n;
for(LinkedList<Node> alt: al.getValue())
result = Union(result, countFirstForConcat(alt));
break;
case CLOSURE:
Closure cl = (Closure)n;
result = F(cl.getValue());
break;
case FIGCLOSURE:
Closure figcl = (Closure)n;
result = F(figcl.getValue());
result.add("$EPS");
break;
default:
return null;
}
return result;
}
public void countFirst() {
for(String key: rules.keySet())
for(String nt: nterms)
first.put(nt, new LinkedList<String>());
boolean isChanging = true;
while (isChanging) {
isChanging = false;
for (String lR : nterms) {
LinkedList<String> newFirst = F(rules.get(lR));
if(ifContainsNewElements(first.get(lR), newFirst)) {
isChanging = true;
first.put(lR, newFirst);
}
}
}
for(String nt: nterms) {
System.out.print("\nFirst(" + nt + ") = ");
for(String s: first.get(nt))
System.out.print(s + " ");
}
}
private boolean ifContainsNewElements(List<String> before, List<String> after) {
for(String a: after)
if(!before.contains(a))
return true;
return false;
}
private LinkedList<String> Union(List<String> a, List<String> b) {
LinkedList<String> union = new LinkedList<String>();
if(a != null)
for(String l: a) {
union.add(l);
}
if(b != null)
for(String l: b) {
if(!union.contains(l))
union.add(l);
}
return union;
}
//atom(with name), closure(with mas of ), alternative
int tokenNum = 0;
//parse () in a rule
public Node parseLP() {
Node n = parseAlternative();
if(tokens.get(tokenNum).getType() != tokenType.RP) {
return null;
}
tokenNum++;
return new Closure(nodeType.CLOSURE, n);
}
//parse {} in a rule
public Node parseLFP() {
Node n = parseAlternative();
if(tokens.get(tokenNum).getType() != tokenType.RFP) {
return null;
}
tokenNum++;
return new Closure(nodeType.FIGCLOSURE, n);
}
//parse one part of alternative
public LinkedList<Node> parseNAlternative() {
LinkedList<Node> l = new LinkedList<Node>();
Token cur = tokens.get(tokenNum);
do {
switch (cur.getType()) {
case LP:
tokenNum++;
l.add(parseLP());
break;
case LFP:
tokenNum++;
l.add(parseLFP());
break;
case TERM:
l.add(new Atom(nodeType.TERM, tokens.get(tokenNum).value));
tokenNum++;
break;
case NTERM:
l.add(new Atom(nodeType.NTERM, tokens.get(tokenNum).value));
tokenNum++;
break;
case R:
case OR:
case RP:
case RFP:
return l;
default:
error(tokens.get(tokenNum).coords, "impossible nterm");
}
if(tokenNum == tokens.size())
return l;
cur = tokens.get(tokenNum);
} while (cur.getType() != tokenType.OR && cur.getType() != tokenType.RP && cur.getType() != tokenType.RFP);
return l;
}
//parse alternatives in a rule
public Node parseAlternative() {
LinkedList<LinkedList<Node>> l = new LinkedList<LinkedList<Node>>();
do {
if(tokens.get(tokenNum).getType() == tokenType.OR)
tokenNum++;
l.add(parseNAlternative());
if(tokenNum >= tokens.size())
break;
} while (tokenNum+1 < tokens.size() && tokens.get(tokenNum).getType() == tokenType.OR &&
tokens.get(tokenNum).getType() != tokenType.R);
return new Alternative(nodeType.ALTERNATIVE, l);
}
//parse rules
public void parseR() {
//System.out.println("in parseR " + tokens.get(tokenNum));
if(tokenNum >= tokens.size())
return;
while (tokens.get(tokenNum).getType() == tokenType.R) {
tokenNum++;
Token cur = tokens.get(tokenNum);
if (cur.getType() == tokenType.NTERM) {//&& nterms.contains(cur.value)) {
tokenNum++;//rules.put(cur, null);
} else {
error(tokens.get(tokenNum).coords, "left part of a rule expected, " + tokens.get(tokenNum)+ " found");
//System.out.println("error at " + tokens.get(tokenNum).coords +": left part of a rule expected, " + tokens.get(tokenNum)+ " found");
return;
}
tokenNum++;
//System.out.println("curToken: " + tokens.get(tokenNum));
rules.put(cur.value, parseAlternative());
System.out.println(cur.value + " = "+rules.get(cur.value).toString() + "\n");
//System.out.println("in parseR2 " + tokens.get(tokenNum));
if(tokenNum >= tokens.size())
return;
}
if (tokenNum == tokens.size()) {
return;
}
error(tokens.get(tokenNum-1).coords, "one more rule or end of grammer expected, \"" + tokens.get(tokenNum-1).value + "\" found");
return;
}
//parse terminals
public void parseT() {
while (tokens.get(tokenNum).getType() == tokenType.TERM) {
terms.add(tokens.get(tokenNum++).value);
}
switch (tokens.get(tokenNum++).getType()) {
case T:
parseT();
break;
case R:
tokenNum--;
parseR();
break;
default:
error(tokens.get(tokenNum-1).coords, "rules expected");
break;
}
}
//parse nterminals
public void parseN() {
if(tokenNum >= tokens.size()) {
error(tokens.get(tokenNum-1).coords, "unexpected end");
}
while (tokens.get(tokenNum).getType() == tokenType.NTERM) {
nterms.add(tokens.get(tokenNum++).value);
}
switch (tokens.get(tokenNum++).getType()) {
case N:
parseN();
break;
case T:
parseT();
break;
default:
System.out.println("error at " + tokens.get(tokenNum-1).coords +": terms declaration expected;");
break;
}
}
public void startParse() {
tokenNum = 0;
switch (tokens.get(tokenNum++).getType()) {
case N:
parseN();
break;
default:
error(tokens.get(tokenNum-1).coords, "nterms declaration expected");
return;
}
}
}
public class lexer {
static private int strNum = 0;
static private Parse parse;// = new Parse();
static List<Token> tokens = new LinkedList<Token>();
private static void findLex(String s, Pattern p) {
int pos = 0;
Matcher m;
while(s.length() != 0){
m = p.matcher(s);
if(m.find()) {
String coords = "("+strNum+","+pos+")-("+strNum+","+
(pos+m.end())+")";
//System.out.println("BBBBBBBBBBBBBBBBBBB");
if (m.group(2) != null) {
System.out.println("KEYWORD ("+strNum+","+pos+")-("+strNum+","+
(pos+m.end())+"): "+m.group(2));
if(m.group(3) != null) tokens.add(new Token(tokenType.T, "$TERM", coords));
else if(m.group(4) != null) tokens.add(new Token(tokenType.N, "$NTERM", coords));
else if(m.group(5) != null) tokens.add(new Token(tokenType.R, "$RULE", coords));
else if(m.group(6) != null) tokens.add(new Token(tokenType.LP, m.group(6), coords));
else if(m.group(7) != null) tokens.add(new Token(tokenType.RP, m.group(7), coords));
else if(m.group(8) != null) tokens.add(new Token(tokenType.LFP, m.group(8), coords));
else if(m.group(9) != null) tokens.add(new Token(tokenType.RFP, m.group(9), coords));
else if(m.group(10) != null) tokens.add(new Token(tokenType.E, m.group(10), coords));
else if(m.group(11) != null) tokens.add(new Token(tokenType.OR, m.group(11), coords));
//tokens.add(new Token("AXIOM", "$AXIOM"));
//parse.addAxiom(m.group(1));
} else if(m.group(13) != null) {
System.out.println("TERM ("+strNum+","+pos+")-("+strNum+","+
(pos+m.end())+"): "+m.group(13));
tokens.add(new Token(tokenType.TERM, m.group(13), coords));
} else if(m.group(12) != null) {
System.out.println("NTERM ("+strNum+","+pos+")-("+strNum+","+
(pos+m.end())+"): "+m.group(12));
tokens.add(new Token(tokenType.NTERM, m.group(12), coords));
}
pos += m.end();
s = s.substring(m.end());
//System.out.println("s: "+s);
} else {
pos++;
if(s.charAt(0) != ' ') {
System.out.println("ERROR at (" + strNum + "," + pos + ")");
}
s = s.substring(1);
}
}
strNum++;
}
public static void main(String args[])
{
// Регулярные выражения
String nterm = "[A-Z]";
String term = "\".\"";
String keyword = "(\\$TERM)|(\\$NTERM)|(\\$RULE)|(\\()|(\\))|(\\{)|(\\})|(=)|(\\|)";
String pattern = "^((" + keyword + ")|(" + nterm + ")|(" + term + ")| |\\n)";
// Компиляция регулярного выражения
Pattern p = Pattern.compile(pattern);
Reader reader = new Reader("test2.txt");//"test.txt");
ArrayList<String> mas = reader.Read();
//System.out.println(reader1.Read());
// Сопоставление текста с регулярным выражением
String program = "";
for(String s: mas)
program += (s+'\n');
findLex(program, p);
//for(int i = 0; i < tokens.size(); i++)
// System.out.println(tokens.get(i));
parse = new Parse(tokens);
parse.startParse();
parse.countFirst();
}
}