-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
575 lines (503 loc) · 18.4 KB
/
Copy pathmain.cpp
File metadata and controls
575 lines (503 loc) · 18.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
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <stack>
using namespace std;
// ---------- Token ----------
enum TokenType
{
KEYWORD,
IDENTIFIER,
NUMBER,
OPERATOR,
SEPARATOR,
STRING_LITERAL,
CHAR_LITERAL,
INVALID
};
struct Token
{
string value;
TokenType type;
int line;
int col;
};
// ---------- Symbol ----------
struct Symbol
{
string type;
bool initialized = false;
bool used = false;
int scopeLevel = 0;
int size = -1; // arrays
};
map<string, Symbol> symbolTable;
int currentScope = 0;
// ---------- Error Containers ----------
struct Issue
{
int line;
string message;
string codeLine;
int col;
};
vector<Issue> lexicalErrors, syntaxErrors, semanticErrors, runtimeErrors, warnings;
// ---------- Settings ----------
set<string> keywords = {"int", "float", "double", "char", "string", "if", "else", "while", "for", "do", "return", "void"};
set<string> predefined = {"cout", "cin", "printf", "scanf", "main"};
bool isKeyword(const string &s) { return keywords.count(s); }
bool isPredefined(const string &s) { return predefined.count(s); }
// ---------- Error Reporter ----------
void report(vector<Issue> &container, const string &msg, int line, const string &codeLine, int col = -1)
{
container.push_back({line, msg, codeLine, col});
}
// ---------- Lexer ----------
vector<Token> lexer(const vector<string> &lines)
{
vector<Token> tokens;
for (int lineNo = 0; lineNo < (int)lines.size(); lineNo++)
{
string line = lines[lineNo];
string originalLine = line;
// Remove comments
size_t commentPos = line.find("//");
if (commentPos != string::npos)
line = line.substr(0, commentPos);
// Trim trailing spaces
size_t lastNonSpace = line.find_last_not_of(" \t");
if (lastNonSpace != string::npos)
line = line.substr(0, lastNonSpace + 1);
else
line = "";
if (line.empty())
continue;
if (!line.empty() && line[0] == '#')
continue;
string word = "";
for (int i = 0; i <= (int)line.size(); i++)
{
char ch = (i < (int)line.size()) ? line[i] : ' ';
// ---------- STRING LITERAL ----------
if (ch == '"')
{
string str = "";
int startCol = i + 1;
i++;
while (i < (int)line.size() && line[i] != '"')
str += line[i++];
if (i >= (int)line.size())
report(lexicalErrors, "Unterminated string literal", lineNo + 1, originalLine, startCol);
else
tokens.push_back({str, STRING_LITERAL, lineNo + 1, startCol});
continue;
}
// ---------- CHAR LITERAL ----------
if (ch == '\'')
{
string str = "";
int startCol = i + 1;
i++;
if (i < (int)line.size() && i + 1 < (int)line.size() && line[i + 1] == '\'')
{
str += line[i];
tokens.push_back({str, CHAR_LITERAL, lineNo + 1, startCol});
i += 2;
}
else
{
report(lexicalErrors, "Invalid char literal", lineNo + 1, originalLine, startCol);
}
continue;
}
// ---------- IDENTIFIER / NUMBER BUILDING ----------
if (isalnum(ch) || ch == '_' || ch == '.')
{
word += ch;
}
else
{
if (!word.empty())
{
int startCol = i - (int)word.size() + 1;
bool isNumber = true;
int dotCount = 0;
for (char c : word)
{
if (c == '.')
dotCount++;
else if (!isdigit(c))
isNumber = false;
}
if (dotCount > 1)
isNumber = false;
if (isNumber && (isdigit(word[0]) || word[0] == '.'))
{
tokens.push_back({word, NUMBER, lineNo + 1, startCol});
}
else if (isKeyword(word))
{
tokens.push_back({word, KEYWORD, lineNo + 1, startCol});
}
else
{
tokens.push_back({word, IDENTIFIER, lineNo + 1, startCol});
}
word = "";
}
// ---------- OPERATORS ----------
if (ch == '<' || ch == '>' || ch == '=' || ch == '!' ||
ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%')
{
string op(1, ch);
if (i + 1 < (int)line.size())
{
char next = line[i + 1];
if ((ch == '<' && next == '=') ||
(ch == '>' && next == '=') ||
(ch == '=' && next == '=') ||
(ch == '!' && next == '=') ||
(ch == '+' && next == '+') ||
(ch == '-' && next == '-') ||
(ch == '<' && next == '<') ||
(ch == '>' && next == '>'))
{
op += next;
i++;
}
}
tokens.push_back({op, OPERATOR, lineNo + 1, i + 1});
}
// ---------- SEPARATORS ----------
else if (ch == ';' || ch == '{' || ch == '}' ||
ch == '(' || ch == ')' || ch == ',' ||
ch == '[' || ch == ']')
{
tokens.push_back({string(1, ch), SEPARATOR, lineNo + 1, i + 1});
}
// ---------- INVALID CHAR ----------
else if (!isspace(ch) && ch != '\0')
{
report(lexicalErrors,
"Invalid character '" + string(1, ch) + "'",
lineNo + 1,
originalLine,
i + 1);
}
}
}
}
return tokens;
}
// ---------- Type Utilities ----------
string inferLiteralType(const Token &t)
{
if (t.type == NUMBER)
{
if (t.value.find('.') != string::npos)
return "float";
return "int";
}
if (t.type == STRING_LITERAL)
return "string";
if (t.type == CHAR_LITERAL)
return "char";
return "unknown";
}
bool isTypeCompatible(const string &lhs, const string &rhs)
{
if (lhs == rhs)
return true;
if (lhs == "float" && rhs == "int")
return true;
if (lhs == "double" && (rhs == "int" || rhs == "float"))
return true;
if (lhs == "int" && rhs == "char")
return true;
if (lhs == "char" && rhs == "char")
return true;
return false;
}
bool isOpening(const string &s)
{
return s == "{" || s == "(" || s == "[";
}
bool isClosing(const string &s)
{
return s == "}" || s == ")" || s == "]";
}
bool isMatching(const string &open, const string &close)
{
return (open == "{" && close == "}") ||
(open == "(" && close == ")") ||
(open == "[" && close == "]");
}
// ---------- Parser + Semantic Analyzer ----------
void parse(vector<Token> &tokens, const vector<string> &lines)
{
stack<Token> delimiterStack;
// Pass 1: bracket matching
for (int i = 0; i < (int)tokens.size(); i++)
{
Token t = tokens[i];
if (isOpening(t.value))
{
delimiterStack.push(t);
if (t.value == "{")
currentScope++;
}
else if (isClosing(t.value))
{
if (delimiterStack.empty())
{
report(syntaxErrors,
"Unmatched closing '" + t.value + "'",
t.line,
lines[t.line - 1],
t.col);
}
else
{
Token open = delimiterStack.top();
delimiterStack.pop();
if (!isMatching(open.value, t.value))
{
report(syntaxErrors,
"Mismatched '" + open.value + "' and '" + t.value + "'",
t.line,
lines[t.line - 1],
t.col);
}
if (t.value == "}")
currentScope--;
}
}
}
// Pass 2: declarations, type checks, runtime checks
for (int i = 0; i < (int)tokens.size(); i++)
{
Token t = tokens[i];
// Variable declarations
if (t.type == KEYWORD && (t.value == "int" || t.value == "float" || t.value == "double" || t.value == "char" || t.value == "string"))
{
if (i + 1 >= (int)tokens.size() || tokens[i + 1].type != IDENTIFIER)
{
report(syntaxErrors,
"Invalid declaration: expected identifier after type",
t.line,
lines[t.line - 1],
t.col);
}
if (i + 1 < (int)tokens.size() && tokens[i + 1].type == IDENTIFIER)
{
// Check if this is a function declaration
bool isFunction = false;
for (int j = i + 2; j < (int)tokens.size() && tokens[j].line == t.line; j++)
{
if (tokens[j].value == "(")
{
isFunction = true;
break;
}
if (tokens[j].value == ";" || tokens[j].value == "=" || tokens[j].value == "[")
break;
}
if (!isFunction)
{
string varName = tokens[i + 1].value;
int size = -1;
// Array declaration
if (i + 2 < (int)tokens.size() && tokens[i + 2].value == "[")
{
if (i + 3 < (int)tokens.size() && tokens[i + 3].type == NUMBER)
{
size = stoi(tokens[i + 3].value);
}
if (i + 4 >= (int)tokens.size() || tokens[i + 4].value != "]")
{
report(syntaxErrors, "Expected closing bracket for array", tokens[i + 2].line,
lines[tokens[i + 2].line - 1], tokens[i + 2].col);
}
}
// Redeclaration check
if (symbolTable.count(varName) && symbolTable[varName].scopeLevel == currentScope)
{
report(semanticErrors, "Redeclaration of variable '" + varName + "'",
tokens[i + 1].line, lines[tokens[i + 1].line - 1], tokens[i + 1].col);
}
else
{
symbolTable[varName] = {t.value, false, false, currentScope, size};
}
string codeLine = lines[t.line - 1];
codeLine.erase(codeLine.find_last_not_of(" \t\n\r") + 1);
if (!codeLine.empty() && codeLine.back() != ';' &&
codeLine.back() != '{' &&
codeLine.back() != '}' &&
codeLine.find("if") != 0 &&
codeLine.find("while") != 0 &&
codeLine.find("for") != 0)
{
report(syntaxErrors,
"Missing semicolon",
t.line,
lines[t.line - 1],
t.col);
}
}
}
}
// Assignment: type checking + undeclared variable check
if (t.type == IDENTIFIER && i + 1 < (int)tokens.size() && tokens[i + 1].value == "=")
{
string varName = t.value;
if (!symbolTable.count(varName))
{
report(semanticErrors,
"Use of undeclared variable '" + varName + "'",
t.line,
lines[t.line - 1],
t.col);
}
if (symbolTable.count(varName))
{
symbolTable[varName].used = true;
symbolTable[varName].initialized = true;
for (int j = i + 2; j < (int)tokens.size() && tokens[j].line == t.line; j++)
{
if (tokens[j].type == STRING_LITERAL || tokens[j].type == NUMBER || tokens[j].type == CHAR_LITERAL)
{
string lhsType = symbolTable[varName].type;
string rhsType = inferLiteralType(tokens[j]);
if (rhsType != "unknown" && !isTypeCompatible(lhsType, rhsType))
{
report(semanticErrors, "Type mismatch: cannot assign '" + rhsType + "' to '" + lhsType + "'",
t.line, lines[t.line - 1], t.col);
}
break;
}
}
}
}
// Division by zero
if (t.value == "/" && i + 1 < (int)tokens.size())
{
for (int j = i + 1; j < (int)tokens.size() && tokens[j].line == t.line; j++)
{
if (tokens[j].type == NUMBER && tokens[j].value == "0")
{
report(runtimeErrors, "Division by zero", t.line, lines[t.line - 1], t.col);
break;
}
if (tokens[j].value == ";" || tokens[j].value == ",")
break;
}
}
// Array bounds check (access only, not declaration)
if (t.type == IDENTIFIER && i + 1 < (int)tokens.size() && tokens[i + 1].value == "[")
{
string varName = t.value;
bool isDeclaration = false;
if (i > 0 && tokens[i - 1].type == KEYWORD &&
(tokens[i - 1].value == "int" || tokens[i - 1].value == "float" ||
tokens[i - 1].value == "double" || tokens[i - 1].value == "char"))
{
isDeclaration = true;
}
if (!isDeclaration && symbolTable.count(varName) && symbolTable[varName].size > 0)
{
for (int j = i + 2; j < (int)tokens.size() && tokens[j].line == t.line && tokens[j].value != "]"; j++)
{
if (tokens[j].type == NUMBER)
{
int idx = stoi(tokens[j].value);
if (idx >= symbolTable[varName].size)
{
warnings.push_back({t.line, "Array index out-of-bounds for '" + varName + "'",
lines[t.line - 1], t.col});
}
break;
}
}
}
}
}
// Report any unclosed delimiters
while (!delimiterStack.empty())
{
Token open = delimiterStack.top();
delimiterStack.pop();
report(syntaxErrors,
"Missing closing for '" + open.value + "'",
open.line,
lines[open.line - 1],
open.col);
}
}
// ---------- Display Function ----------
void displayIssues()
{
auto printSection = [](const string &title, vector<Issue> &v, const string &color)
{
if (v.empty())
return;
cout << color << "\n==== " << title << " ====\033[0m\n";
for (auto &e : v)
{
cout << "Line " << e.line << ": " << e.message << "\n";
if (!e.codeLine.empty())
{
string cleanLine = e.codeLine;
size_t commentPos = cleanLine.find("//");
if (commentPos != string::npos)
cleanLine = cleanLine.substr(0, commentPos);
size_t last = cleanLine.find_last_not_of(" \t");
if (last != string::npos)
cleanLine = cleanLine.substr(0, last + 1);
cout << " >> " << cleanLine << "\n";
if (e.col > 0)
{
cout << " ";
for (int i = 1; i < e.col; i++)
cout << " ";
cout << "^\n";
}
}
}
};
printSection("Lexical Errors", lexicalErrors, "\033[1;31m");
printSection("Syntax Errors", syntaxErrors, "\033[1;31m");
printSection("Semantic Errors", semanticErrors, "\033[1;31m");
printSection("Runtime Errors", runtimeErrors, "\033[1;31m");
printSection("Warnings", warnings, "\033[1;33m");
int totalErrors = (int)(lexicalErrors.size() + syntaxErrors.size() + semanticErrors.size() + runtimeErrors.size());
cout << "\n\033[1;36m==== Summary ====\033[0m\n";
cout << "Total Errors: " << totalErrors << "\n";
cout << "Total Warnings: " << warnings.size() << "\n";
}
// ---------- Main ----------
int main()
{
cout << "\033[1;36m==== MINI C++ STATIC ANALYZER ====\033[0m\n\n";
cout << "\033[1;32mEnter C++ code line by line (type END to finish):\033[0m\n";
cout << "\033[1;32m............INPUT.............:\033[0m\n";
vector<string> lines;
string line;
while (getline(cin, line))
{
if (line == "END")
break;
lines.push_back(line);
}
cout << "\033[1;32m............OUTPUT.............:\033[0m\n";
vector<Token> tokens = lexer(lines);
parse(tokens, lines);
displayIssues();
if (lexicalErrors.empty() && syntaxErrors.empty() && semanticErrors.empty() && runtimeErrors.empty())
cout << "\n\033[1;32mNo errors detected.\033[0m\n";
else
cout << "\n\033[1;31mError detection complete.\033[0m\n";
return 0;
}