CD Lab1
CD Lab1
ASSESSMENT – 1
Date: 05.08.2024
1. Write a C/C++ Program to simulate the lexical analysis phase of a compiler using
files.
CODING:
Filename:lexical_analyzer.c
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
if (isKeyword(subStr)) {
printf("'%s' IS A KEYWORD\n", subStr);
} else if (isInteger(subStr)) {
printf("'%s' IS AN INTEGER\n", subStr);
} else if (isRealNumber(subStr)) {
printf("'%s' IS A REAL NUMBER\n", subStr);
} else if (isIdentifier(subStr)) {
printf("'%s' IS A VALID IDENTIFIER\n", subStr);
} else {
printf("'%s' IS NOT A VALID IDENTIFIER\n", subStr);
}
free(subStr);
}
int main() {
FILE* file = fopen("input.txt", "r"); // Open the input file in read mode
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
INPUT:
int a=a+2;
OUTPUT:
'int' IS A KEYWORD
'a' IS A VALID IDENTIFIER
'=' IS AN OPERATOR
'a' IS A VALID IDENTIFIER
'+' IS AN OPERATOR
'2' IS AN INTEGER
typedef enum {
KEYWORD, IDENTIFIER, SYMBOL, LITERAL
} TokenType;
typedef struct {
TokenType type;
char value[100];
} Token;
typedef struct {
char name[100];
char dataType[100];
} Variable;
int typeSizes[256];
void initializeTypeSizes() {
typeSizes['i'] = 4; // int
typeSizes['d'] = 8; // double
typeSizes['f'] = 4; // float
typeSizes['b'] = 1; // bool
typeSizes['c'] = 2; // char
}
Token* tokenize(const char* code, int* tokenCount) {
Token* tokens = malloc(100 * sizeof(Token));
*tokenCount = 0;
char currentToken[100];
int currentTokenIndex = 0;
if (ispunct(c)) {
Token token;
token.type = SYMBOL;
token.value[0] = c;
token.value[1] = '\0';
tokens[(*tokenCount)++] = token;
}
}
}
return tokens;
}
variables[variableCount++] = variable;
address += typeSizes[(int)variable.dataType[0]];
i++; // Skip the identifier
}
}
}
}
int main() {
initializeTypeSizes();
fseek(inputFile, 0, SEEK_END);
long fileSize = ftell(inputFile);
fseek(inputFile, 0, SEEK_SET);
char* code = malloc(fileSize + 1);
fread(code, 1, fileSize, inputFile);
code[fileSize] = '\0';
fclose(inputFile);
int tokenCount;
Token* tokens = tokenize(code, &tokenCount);
create_SymbolTable(tokens, tokenCount);
free(tokens);
free(code);
return 0;
}
Input filename:input.c
#include <stdio.h>
#include<math.h>
int main()
{
int length=10;
int breadth=20;
float area=length*breadth;
char a;
char p;
int perimeter=2*(length+breadth);
printf("area of rectangle %c= %f",a,area);
printf("perimeter is rectangle %p=%d",p,perimeter);
return 0;
}
INPUT:
length=10;
breadth=20;
OUTPUT:
Symbol Type Size Address
-------------------------------------------------------
main int 4 1000
length int 4 1004
area float 4 1008
a char 2 1012
p char 2 1014
perimeter int 4 1016
rectangle is 4 1020