-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForLoopSyntaxChecker.java
More file actions
603 lines (533 loc) · 19.4 KB
/
ForLoopSyntaxChecker.java
File metadata and controls
603 lines (533 loc) · 19.4 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
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
import java.util.*;
public class ForLoopSyntaxChecker {
// Symbols
static Set<String> separatorSymbols = new HashSet<>(
Arrays.asList("=", "(", ")", "{", "}", ",", ";"));
// Boolean Symbols
static Set<String> booleanSymbols = new HashSet<>(Arrays.asList("<", ">", "<=", "=>", "!=", "=="));
// Operators
static Set<String> expOperators = new HashSet<>(Arrays.asList("+=", "-=", "*=", "/=", "%="));
// Error Counter
static int errorCounter = 0;
public static void main(String[] args) {
// Read syntax input
Scanner scan = new Scanner(System.in);
System.out.print("Enter syntax: ");
String syntaxInput = scan.nextLine();
// Split the input into an array and pass to tokenizer()
String[] arrayInput = syntaxInput.trim().split("\\s+");
String[] token = tokenizer(arrayInput);
// Count how many "for" exists and store its index
int tokenCounter = 0;
ArrayList<Integer> forIndex = new ArrayList<>();
for (String word : token) {
if (word.equals("for")) {
forIndex.add(tokenCounter);
}
tokenCounter++;
}
// Ensure forIndex is not empty
if (!forIndex.isEmpty()) {
for (int i = forIndex.size() - 1; i >= 0; i--) {
int forStartIndex = forIndex.get(i);
int forEndIndex = -1; // Initialize the end index to -1
// Find the corresponding closing "}" for the current "for"
int openBraces = 0;
for (int j = forStartIndex; j < token.length; j++) {
if (token[j].equals("{")) {
openBraces++;
} else if (token[j].equals("}")) {
openBraces--;
if (openBraces == 0) {
forEndIndex = j;
break; // Found the matching closing brace
}
}
}
// Check the syntax of the "for" loop
if (forEndIndex != -1) {
System.out.println("\nChecking sequence...");
if (checkSequence(token)) {
// Check Control Statement ()
int startControl = -1;
int endControl = -1;
for (int n = forStartIndex; n <= forEndIndex; n++) {
if (token[n].equals("(") && startControl == -1) {
startControl = n;
} else if (token[n].equals(")") && endControl == -1) {
endControl = n;
}
}
System.out.println("\nChecking control statements...");
checkControl(token, startControl, endControl);
// Check For Loop Statement {}
int startStatement = forStartIndex;
int endStatement = forEndIndex;
for (int j = forStartIndex; j <= forEndIndex; j++) {
if (token[j].equals("{") && j > startStatement) {
startStatement = j;
break; // Exit the loop when the first '{' is found
}
}
System.out.println("\nChecking statements...");
checkStatement(token, startStatement, endStatement);
}
boolean isSyntaxValid = true;
if (errorCounter > 0) {
isSyntaxValid = false;
}
if (isSyntaxValid) {
System.out.println("\n== Syntax of 'for' loop at index " + forStartIndex + " is VALID.");
} else {
System.err.println("\n== Syntax of 'for' loop at index " + forStartIndex + " is INVALID.");
break;
}
} else {
System.err.println(" Missing closing '}' for 'for' loop at index " + forStartIndex);
break;
}
}
}
}
// tokenizer(): Stores the array in a token with its corresponding label
public static String[] tokenizer(String[] array) {
ArrayList<String> tokenList = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (array[i].equals("for")) {
tokenList.add("for");
} else if (array[i].equals("System.out.println") || array[i].equals("System.out.print")) {
tokenList.add("print");
} else if (array[i].equals("int")) {
tokenList.add("int");
} else if (((array[i].startsWith("++")
|| array[i].startsWith("--")) && array[i].length() > 2 && Character.isLetter(array[i].charAt(2))) ||
(array[i].length() > 2 && Character.isLetter(array[i].charAt(0)) &&
((array[i].endsWith("--") || array[i].endsWith("++"))))) {
tokenList.add("update");
} else if (separatorSymbols.contains(array[i]) || booleanSymbols.contains(array[i])
|| expOperators.contains(array[i])) {
tokenList.add(array[i]);
} else if (array[i].matches("-?\\d+")) {
tokenList.add("integer");
} else if (array[i].matches("^^[a-zA-Z][a-zA-Z0-9_]*$")) {
tokenList.add("varName");
} else if (array[i].matches(".*[\"'].*")) {
tokenList.add("printContent");
} else if (expOperators.stream().anyMatch(array[i]::contains) && array[i].length() >= 3) {
String pattern = String.join("|", expOperators)
.replaceAll("\\+", "\\[+\\]")
.replaceAll("\\*", "\\[\\*\\]");
String[] exprArray = array[i].split("(?=" + pattern + ")|(?<=" + pattern + ")");
for (int j = 0; j < exprArray.length; j++) {
if (exprArray[j].matches("-?\\d+")) {
tokenList.add("integer");
} else if (exprArray[j].matches("^[a-zA-Z][a-zA-Z0-9_]*$")) {
tokenList.add("varName");
} else if (expOperators.contains(exprArray[j])) {
tokenList.add(exprArray[j]);
}
}
} else if (booleanSymbols.stream().anyMatch(array[i]::contains) && array[i].length() >= 3) {
String pattern = String.join("|", booleanSymbols);
String[] boolArray = array[i].split("(?=" + pattern + ")|(?<=" + pattern + ")");
for (int j = 0; j < boolArray.length; j++) {
if (boolArray[j].matches("-?\\d+")) {
tokenList.add("integer");
} else if (boolArray[j].matches("^[a-zA-Z][a-zA-Z0-9_]*$")) {
tokenList.add("varName");
} else if (booleanSymbols.contains(boolArray[j])) {
tokenList.add(boolArray[j]);
}
}
} else if (array[i].contains("=") && array[i].length() >= 3) {
String[] equalArray = array[i].split("(?<=\\=)|(?=\\=)");
for (int j = 0; j < equalArray.length; j++) {
if (equalArray[j].matches("-?\\d+")) {
tokenList.add("integer");
} else if (equalArray[j].matches("^[a-zA-Z][a-zA-Z0-9_]*$")) {
tokenList.add("varName");
} else if (equalArray[j].equals("=")) {
tokenList.add("=");
} else {
tokenList.add(equalArray[j]);
}
}
} else {
errorCounter++;
tokenList.add("illegal");
}
}
return tokenList.toArray(new String[0]);
}
// checkSequence(): Validate if separators () or {} are balanced & if it follows
// the proper for loop syntax
public static boolean checkSequence(String[] token) {
boolean beginningCorrect = false, middleCorrect = true, endCorrect = false, isBalanced = true;
boolean firstBraceCheckDone = false, openBraceCheckDone = false;
Stack<String> pairStack = new Stack<String>();
// check for parenthesis balance
for (int i = 0; i < token.length; i++) {
if (token[i].equals("(")) {
pairStack.push(token[i]);
}
if (token[i].equals(")")) {
if (pairStack.empty()) {
isBalanced = false;
} else {
pairStack.pop();
}
}
}
// check for any leftovers
if (!pairStack.empty()) {
isBalanced = false;
}
// check for curly brace balance
for (int i = 0; i < token.length; i++) {
if (token[i].equals("{")) {
pairStack.push(token[i]);
}
if (token[i].equals("}")) {
if (pairStack.empty()) {
isBalanced = false;
} else {
pairStack.pop();
}
}
}
// check for any leftovers again
if (!pairStack.empty()) {
isBalanced = false;
}
// checking the actual sequence
// check beginning
if (token[0].equals("for") && token[1].equals("(")) {
beginningCorrect = true;
}
// check middle
for (int i = 0; i < token.length; ++i) {
if (token[i].equals("(")) {
pairStack.push(token[i]);
}
if (token[i].equals(")")) {
if (!pairStack.isEmpty()) {
pairStack.pop();
}
}
// checks "){"
if (i > 0 && pairStack.isEmpty() && !openBraceCheckDone) {
if (i < token.length - 1) {
if (!token[i + 1].equals("{")) {
middleCorrect = false;
}
} else {
middleCorrect = false;
}
openBraceCheckDone = true;
}
// makes sure { is ONLY after ) and only triggers at the first )
if (token[i].equals("{") && !firstBraceCheckDone) {
if (!pairStack.isEmpty()) {
middleCorrect = false;
}
firstBraceCheckDone = true;
}
}
// check end
if (token[token.length - 1].equals("}")) {
endCorrect = true;
}
if (isBalanced && beginningCorrect && middleCorrect && endCorrect) {
System.out.println("Correct for () {} Sequence");
return true;
} else {
System.err.println("Incorrect for () {} Sequence");
errorCounter++;
return false;
}
}
// checkControl(): Validates if the control statements inside for() are correct
public static boolean checkControl(String[] token, int start, int end) {
start++; // Start checking tokens after "("
boolean validConditionMet = false;
ArrayList<String> line = new ArrayList<>();
ArrayList<String> controlContent = new ArrayList<>();
for (int i = start; i <= end; i++) {
String currentToken = token[i];
line.add(currentToken);
if (i == end || currentToken.equals(";")) {
String content = "";
if ((line.get(0).equals("int") && line.get(1).equals("varName") && line.get(2).equals("="))
|| (line.get(0).equals("varName") && line.size() >= 3 && line.get(1).equals("="))) {
if (checkVarDeclare(token, start, i)) {
content = "varDeclare";
}
} else if (line.get(0).equals("update")) {
if (checkUpdate(token, start, i)) {
content = "update";
}
} else if (line.get(0).equals("varName") && expOperators.contains(line.get(1))) {
if (checkExpression(token, start, i)) {
content = "expr";
}
} else if (line.get(0).equals("varName") && booleanSymbols.contains(line.get(1))) {
if (checkCondition(token, start, i)) {
content = "condition";
}
}
if (!content.isEmpty()) {
controlContent.add(content);
}
start = i + 1;
line.clear();
}
}
if (controlContent.size() == 3) {
int controlCounter = 0;
if (controlContent.get(0).equals("varDeclare")) {
controlCounter++;
System.out.println("Correct for loop initialization");
} else {
System.err.println("Incorrect for loop initialization");
}
if (controlContent.get(1).equals("condition")) {
controlCounter++;
System.out.println("Correct for loop condition");
} else {
System.err.println("Incorrect for loop condition");
}
if (controlContent.get(2).equals("update") || controlContent.get(2).equals("expr")) {
controlCounter++;
System.out.println("Correct for loop update");
} else {
System.err.println("Incorrect for loop update");
}
if (controlCounter == 3) {
validConditionMet = true;
System.out.println("Correct control statements");
}
}
if (controlContent.isEmpty()) {
errorCounter++;
System.err.println("Control statement is empty");
} else if (controlContent.size() < 3) {
errorCounter++;
System.err.println("Control statement has less than 3 correct statements");
} else if (controlContent.size() > 3) {
errorCounter++;
System.err.println("Control statement has more than 3 correct statements");
}
if (!validConditionMet) {
errorCounter++;
System.err.println("Illegal control statement");
}
return validConditionMet;
}
// checkStatement(): Validates if for loop statements are correct
// It should accept varDeclare, update, print, exp
public static boolean checkStatement(String[] token, int start, int end) {
start += 1; // Start checking tokens after "{"
ArrayList<String> line = new ArrayList<>();
int i = start;
boolean validConditionMet = true;
boolean insideNestedFor = false;
while (i < end) {
String currentToken = token[i];
if (currentToken.equals("for")) {
if (!line.isEmpty()) {
processLine(line, token, start, i);
line.clear();
}
System.out.println("Nested for loop found"); // Start a new line
insideNestedFor = true;
while (!currentToken.equals("}")) {
line.add(currentToken);
i++;
currentToken = token[i];
}
if (currentToken.equals("}")) {
line.add(currentToken);
insideNestedFor = false;
line.clear();
} else {
line.add(currentToken);
}
} else if (!insideNestedFor && (currentToken.equals(";") || currentToken.equals("}") || i == end - 1)) {
line.add(currentToken);
processLine(line, token, start, i);
line.clear();
} else {
line.add(currentToken);
}
i++;
}
if (!validConditionMet)
{
errorCounter++;
System.err.println("Illegal statement");
}
return validConditionMet;
}
// processLine(): works with checkStatement to verify if a line is valid
private static boolean processLine(List<String> line, String[] token, int start, int i) {
String lineString = String.join(" ", line);
if (lineString.endsWith(";") || token[i].equals("for") || i == token.length - 1 || lineString.endsWith("}")) {
if (line.get(0).equals("int") && line.size() >= 5
|| (line.get(0).equals("varName") && line.size() == 4 && line.get(1).equals("="))) {
if (checkVarDeclare(token, start, i)) {
System.out.println("Correct variable declaration");
return true;
} else {
System.err.println("Incorrect variable declaration");
return false;
}
} else if (line.get(0).equals("update")
&& line.get(line.size() - 1).contains(";") && line.size() == 2) {
if (checkUpdate(token, start, i)) {
System.out.println("Correct update");
return true;
} else {
System.err.println("Incorrect update");
return false;
}
} else if (line.get(0).equals("print") && line.size() == 5) {
if (checkPrint(token, start, i)) {
System.out.println("Correct print statement");
return true;
} else {
System.err.println("Incorrect print statement");
return false;
}
} else if (line.get(0).equals("varName") && expOperators.contains(line.get(1))
&& line.get(line.size() - 1).contains(";") && line.size() == 4) {
if (checkExpression(token, start, i)) {
System.out.println("Correct expression");
return true;
} else {
System.err.println("Incorrect expression");
return false;
}
}
}
errorCounter++;
System.err.println("Statement not found");
return false;
}
// checkVarDeclare(): Validates if the variable declaration is correct
// It accepts [int] <varName> = <varName>||<integer> ;
// or int [varName] , [varName] ... ;
public static boolean checkVarDeclare(String[] token, int start, int end) {
if (end - start >= 4 && token[start].equals("int") && token[start + 2].equals(",")) {
int i = start + 1;
while (i < end) {
if (token[i].equals("varName")) {
i++;
if (i < end + 1) {
if (token[i].equals(",")) {
i++;
} else if (token[i].equals(";")) {
return true;
} else {
errorCounter++;
return false;
}
} else {
// Invalid ending, return false
errorCounter++;
return false;
}
} else {
System.err.println("Incorrect Identifier List Declaration");
errorCounter++;
return false;
}
}
}
// Variable Declaration
else {
if (token[start].equals("int") && token[start + 1].equals("varName") &&
token[start + 2].equals("=")) {
for (int i = start; i < end; i++) {
if ((token[i + 3].equals("varName")
|| token[i + 3].equals("integer"))
&&
token[i + 4].equals(";")) {
return true;
}
}
} else if (token[start].equals("varName")) {
for (int i = start; i < end; i++) {
if (token[i + 1].equals("=") &&
(token[i + 2].equals("varName")
|| token[i + 2].equals("integer"))
&&
token[i + 3].equals(";")) {
return true;
}
}
}
}
errorCounter++;
return false;
}
// checkUpdate(): Validates if update has the correct syntax
public static boolean checkUpdate(String[] token, int start, int end) {
for (int i = start; i <= end - 1; i++) {
if (token[i].equals("update")) {
return true;
}
}
errorCounter++;
return false;
}
// checkCondition(): Validates if condition has the correct syntax
// It accepts <varName> <comparisonSymbol> <varName>||<integer>
public static boolean checkCondition(String[] token, int start, int end) {
int startIndex = start;
// finds condition
for (int i = 0; i < token.length; i++) {
if (token[i].equals(";")) {
startIndex = i + 1;
break;
}
}
// make sure that the left side is a variable or an integer
if ((token[startIndex].equals("varName")) &&
// make sure that it's followed by a comparison symbol
(booleanSymbols.contains(token[startIndex + 1])) &&
// make sure that the right side is either a variable or an integer
(token[startIndex + 2].equals("varName") || token[startIndex + 2].equals("integer"))) {
return true;
} else {
return false;
}
}
// checkExpression(): Validates if expression has the correct syntax
// It accepts <varName> <expOperator> <digit>||<varName> [;]
public static boolean checkExpression(String[] token, int start, int end) {
Set<String> expOp = new HashSet<>(Arrays.asList("+=", "-=", "*=", "/=", "%="));
for (int i = start; i < end; i++) {
if (token[i].equals("varName") && expOp.contains(token[i + 1]) &&
(token[i + 2].equals("integer") || token[i + 2].equals("varName"))) {
return true;
}
}
errorCounter++;
return false;
}
// checkPrint(): Validates if sysout print has the correct syntax
// It accepts <print> ( <printContent>||<varName> ) ;
public static boolean checkPrint(String[] token, int start, int end) {
for (int i = start; i <= end - 1; i++) {
if (token[i].equals("print") &&
token[i + 1].equals("(") &&
(token[i + 2].equals("printContent") || token[i + 2].equals("varName")) &&
token[i + 3].equals(")") &&
token[i + 4].equals(";")) {
return true;
}
}
errorCounter++;
return false;
}
}