Skip to content

Instantly share code, notes, and snippets.

@vnkdj5
Last active May 23, 2021 09:13
Show Gist options
  • Select an option

  • Save vnkdj5/568643ae6d5edb972bf64d3774657661 to your computer and use it in GitHub Desktop.

Select an option

Save vnkdj5/568643ae6d5edb972bf64d3774657661 to your computer and use it in GitHub Desktop.
Write a program using Lex specifications to implement lexical analysis phase of compiler to generate tokens of subset of Java program.
import java.io.*;
class Test
{
public static void main(String args[])
{
int b;
int a=12;
if(a==12)
{
;
}
}
%{
FILE* yyin;
%}
DIGIT [0-9]
NUMBER {DIGIT}+
REAL {DIGIT}*[.]{NUMBER}
TEXT [A-Za-z]
KEYWORDS "class"|"static"
DATATYPE "int"|"float"|"double"|"long"|"void"|"String"
CONDITIONAL "if"|"else"|"else if"|"switch"|"case"
ITERATIVE "for"|"while"|"do"
PREPROCESSOR "import"[^\n]*";"
SC ";"
IDENTIFIER {TEXT}({DIGIT}|{TEXT}|"_")*
NONIDENTIFIER {DIGIT}({TEXT}|{DIGIT}|"_")*
ARITH_OP "+"|"-"|"/"|"%"|"*";
LOGICAL_OP "&&"|"||"|"!"|"!="
REL_OP "<"|">"|"<="|">="|"=="
UNARY "++"|"--"
ACCESS "public"|"private"|"protected"|""
FUNCTION {ACCESS}{DATATYPE}{IDENTIFER}"("({DATATYPE}{IDENTIFIER})*")"
%%
[ \n\t]+ ;
{PREPROCESSOR} {printf("%s\t==> PREPROCESSOR\n",yytext);}
{CONDITIONAL} { printf("%s\t==> CONDITIONAL\n",yytext);}
{ITERATIVE} {printf("%s\t==> ITERATIVE CONSTRUCT\n",yytext);}
{DATATYPE} {printf("%s\t==> DATATYPE\n",yytext);}
{ACCESS} {printf("%s\t==> ACCESS SPECIFIER\n",yytext);}
{KEYWORDS} {printf("%s\t==> KEYWORDS\n",yytext);}
{IDENTIFIER} {printf("%s\t==> IDENTIFIER\n",yytext);}
{REAL} {printf("%s\t==> REAL CONSTANT\n",yytext);}
{NUMBER} {printf("%s\t==> CONSTAINT INTEGER\n",yytext);}
{NONIDENTIFIER} {printf("%s\t==> NONIDENTIFIER\n",yytext);}
{SC} {printf("%s\t==> DELIMITER\n",yytext);}
{UNARY} {printf("%s\t==> UNARY OP\n",yytext);}
{ARITH_OP} {printf("%s\t==> ARITHMETIC OPERATOR\n",yytext);}
{LOGICAL_OP} {printf("%s\t==> LOGICAL OP\n",yytext);}
{REL_OP} {printf("%s\t==> RELATIONAL OP\n",yytext);}
"=" {printf("%s\t==> ASSIGNMENT OP\n",yytext);}
"{" {printf("%s\t==> BLOCK BEGIN\n",yytext);}
"}" {printf("%s\t==> BLOCK END\n",yytext);}
"(" {printf("%s\t==> PARANTHESIS BEGIN\n",yytext);}
")" {printf("%s\t==> PARENTHESIS END\n",yytext);}
. ;
%%
int yywrap()
{
return 1;
}
int main(int argc,char* argv[])
{
yyin=fopen(argv[1],"r");
yylex();
fclose(yyin);
}
@Omkar281100
Copy link

Can you send algorithm and flow chart of this code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment