You are on page 1of 6

Compiler Construction

Lab: #04

Group Members:
Toheed Ejaz Khan ▷ 01-134192-108

Ahmed Fayyaz Malik ▷ 01-134192-099

Usama Tayyeb Hashmi ▷ 01-134192-086


Code:
#include<iostream>
#include<fstream>
using namespace std;

fstream file;
char ch;
enum TokenType {
IDENT, ADD, SUB, MULT, DIV, OSB, CSB, OMB, CMB, PLEQ, MINEQ, MULEQ, DIVEQ,
NUM, KEYW, VAR, INC, DEC, ASSIGN, EQL, OSQB, CSQB, STR, SEP, TERM, CMT, EXRT,
INST,LESS, GREAT, LESEQ, GRAEQ, NOT
};
TokenType LexicalAnalyzer()
{
string identifier = "";
if (isdigit(ch))
{
while (isdigit(ch))
{
identifier += ch;
file.get(ch);
}
file.putback(ch);
return NUM;
}
else if (isalpha(ch) || ch == '_')
{
do
{
identifier += ch;
file.get(ch);
} while (isdigit(ch) || isalpha(ch) || ch == '_');
file.putback(ch);
if (identifier == "if" || identifier == "else" || identifier == "while"
|| identifier == "do" || identifier == "main" || identifier == "int")
{
return KEYW;
}
else
{
return VAR;
}
}
else if (ch == '+')
{
file.get(ch);
if (ch == '=')
{
return PLEQ;
}
else if (ch == '+')
{
return INC;
}
else
{
file.putback(ch);
return ADD;
}
}
else if (ch == '-')
{
file.get(ch);
if (ch == '-')
{
return DEC;
}
else if (ch == '=')
{
return MINEQ;
}
else
{
file.putback(ch);
return SUB;
}

}
else if (ch == '*')
{
file.get(ch);
if (ch == '=')
{
return MULEQ;
}
else
{
file.putback(ch);
return MULT;
}
}
else if (ch == '/')
{
file.get(ch);
if (ch == '=')
{
return DIVEQ;
}
else if (ch == '*')
{
while (true)
{
file.get(ch);
if (ch == '*')
{
file.get(ch);
if (ch == '/')
{
break;
}
}
}
file.putback(ch);
return CMT;
}
else if (ch == '/')
{
while (ch != '\n')
{
file.get(ch);
}
file.putback(ch);
return CMT;
}
else
{
file.putback(ch);
return DIV;
}
}
else if (ch == '=')
{
file.get(ch);
if (ch == '=')
{
return EQL;
}
else
{
file.putback(ch);
return ASSIGN;
}
}
else if (ch == '<')
{
file.get(ch);
if (ch == '<')
{
return EXRT;
}
else if (ch == '=')
{
return LESEQ;
}
else
{
file.putback(ch);
return LESS;
}
}
else if (ch == '>')
{
file.get(ch);
if (ch == '>')
{
return INST;
}
else if (ch == '=')
{
return GRAEQ;
}
else
{
file.putback(ch);
return GREAT;
}
}
else if (ch == '(')
{
return OSB;
}
else if (ch == ')')
{
return CSB;
}
else if (ch == '{')
{
return OMB;
}
else if (ch == '}')
{
return CMB;
}
else if (ch == '[')
{
return OSQB;
}
else if (ch == ']')
{
return CSQB;
}
else if (ch == '"')
{
file.get(ch);
while (ch != '"')
{
file.get(ch);
}
if (ch != '"')
{

file.putback(ch);
}
return STR;
}
else if (ch == ',')
{
return SEP;
}
else if (ch == ';')
{
return TERM;
}
else
{
return IDENT;
}
}
int main()
{
int token;
file.open("Text.txt");
if (file.is_open())
{
while (file.get(ch))
{
token = LexicalAnalyzer();
if (token != 0)
{
cout << token << " - ";
}
}
cout << '\b' << '\b';
}
else
{
cout << "File Error" << endl;
}
file.close();
}

Output:

You might also like