Professional Documents
Culture Documents
eXperimenT - 2
Name: Abhinav V
Reg.No: 21BAI1213
implemenTaTion of leXiCal analyzer using leX Tool
Program:
%{
#include <stdio.h>
#include <stdlib.h>
%}
%option noyywrap
%{
/* Define tokens */
#define IDENTIFIER 257
#define KEYWORD 258
#define INTEGER 259
#define PLUS 260
#define MINUS 261
#define MULTIPLY 262
#define DIVIDE 263
%}
/* Regular expressions and actions */
%%
[ \t\n] /* Ignore whitespace */
[0-9]+ { printf("INTEGER: %s\n", yytext); }
[a-zA-Z][a-zA-Z0-9]* { printf("IDENTIFIER: %s\n", yytext); }
"if" { printf("KEYWORD: if\n"); }
"else" { printf("KEYWORD: else\n"); }
"while" { printf("KEYWORD: while\n"); }
"int" { printf("KEYWORD: int\n"); }
"+" { printf("PLUS\n"); }
"-" { printf("MINUS\n"); }
"*" { printf("MULTIPLY\n"); }
"/" { printf("DIVIDE\n"); }
[[:punct:]] { /* Ignore punctuation */ }
. { printf("Invalid token: %s\n", yytext); }
%%
int main() {
while(yylex());
return 0;
}
Output :
ConsTruCTion of synTaX analyzer
Program:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// Token types
typedef enum {
INTEGER,
PLUS,
MINUS,
END
} TokenType;
// Function prototypes
Token getNextToken();
void error(const char *msg);
void eat(TokenType expected);
int expr();
int term();
int factor();
int main() {
// Initialize the current token
currentToken = getNextToken();
return 0;
}
// Get the next token from input
Token getNextToken() {
int c;
while ((c = getchar()) != EOF) {
if (isdigit(c)) {
ungetc(c, stdin);
int value;
scanf("%d", &value);
return (Token){INTEGER, value};
} else if (isspace(c)) {
continue; // Ignore whitespace
} else if (c == '+') {
return (Token){PLUS, 0};
} else if (c == '-') {
return (Token){MINUS, 0};
} else {
error("Invalid character");
}
}
return (Token){END, 0}; // Return END token at the end of input
}
return result;
}
return result;
}
Output:
implemenT a C program for ll(1) Top Down parser for
any given ll(1) grammar
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct {
char production[3][10];
} CfgRule;
typedef struct {
CfgRule *rules;
int count;
} Cfg;
Cfg new_cfg() {
Cfg cfg = {NULL, 0};
return cfg;
}
typedef enum {
T_EOF,
T_ERROR,
T_INT,
T_LPAREN,
T_RPAREN,
T_PLUS,
T_TIMES,
} TokenType;
typedef struct {
TokenType type;
char *value;
} Token;
typedef struct {
Cfg *grammar;
TokenStream *input;
int input_index;
Token lookahead;
} Parser;
int main() {
Cfg grammar = new_cfg();
CfgRule rule1 = {"E", "+T", ""};
CfgRule rule2 = {"E", "T", ""};
CfgRule rule3 = {"T", "*F", ""};
CfgRule rule4 = {"T", "F", ""};
CfgRule rule5 = {"F", "(E)", ""};
CfgRule rule6 = {"F", "i", ""}; // i stands for an integer
add_rule(&grammar, rule1);
add_rule(&grammar, rule2);
add_rule(&grammar, rule3);
add_rule(&grammar, rule4);
add_rule(&grammar, rule5);
add_rule(&grammar, rule6);
return 0;
}
Output: