forked from strivedi4u/hacktoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lexical-Analyzer.c
101 lines (88 loc) · 2.78 KB
/
Lexical-Analyzer.c
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
#include <stdio.h>
#include <ctype.h>
#include <string.h>
// List of keywords
char *keywords[] = { "if", "else", "while", "int", "return", "void", "main", "char", "float" };
int numKeywords = 9;
// Function to check if a string is a keyword
int isKeyword(char *word) {
for (int i = 0; i < numKeywords; i++) {
if (strcmp(word, keywords[i]) == 0)
return 1;
}
return 0;
}
// Function to check if a character is an operator
int isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '=' || ch == '>' || ch == '<');
}
// Function to check if a character is a special symbol
int isSpecialSymbol(char ch) {
return (ch == '(' || ch == ')' || ch == '{' || ch == '}' || ch == ';' || ch == ',');
}
// Function to check if a string is a number
int isNumber(char *str) {
for (int i = 0; i < strlen(str); i++) {
if (!isdigit(str[i]))
return 0;
}
return 1;
}
// Lexical analyzer function
void lexicalAnalyzer(char *source) {
char buffer[100]; // Buffer to store words and identifiers
int i = 0, j = 0;
while (source[i] != '\0') {
// Skip white spaces
if (isspace(source[i])) {
i++;
continue;
}
// Check if it's a letter or digit (start of identifier or keyword)
if (isalpha(source[i])) {
j = 0;
// Accumulate characters to form a word (identifier or keyword)
while (isalnum(source[i])) {
buffer[j++] = source[i++];
}
buffer[j] = '\0';
// Check if the accumulated string is a keyword
if (isKeyword(buffer))
printf("<KEYWORD, %s>\n", buffer);
else
printf("<IDENTIFIER, %s>\n", buffer);
}
// Check if it's a number
else if (isdigit(source[i])) {
j = 0;
// Accumulate digits to form a number
while (isdigit(source[i])) {
buffer[j++] = source[i++];
}
buffer[j] = '\0';
printf("<NUMBER, %s>\n", buffer);
}
// Check if it's an operator
else if (isOperator(source[i])) {
printf("<OPERATOR, %c>\n", source[i]);
i++;
}
// Check if it's a special symbol
else if (isSpecialSymbol(source[i])) {
printf("<SPECIAL SYMBOL, %c>\n", source[i]);
i++;
}
// Handle unrecognized characters
else {
printf("<UNKNOWN, %c>\n", source[i]);
i++;
}
}
}
int main() {
// Example input source code
char sourceCode[] = "int main() { int a = 5; if (a > 2) a = a + 1; return 0; }";
printf("Lexical Analysis of Source Code:\n");
lexicalAnalyzer(sourceCode);
return 0;
}