Write a similar code using JAVA or Python.
Write a similar code using JAVA or Python.
The state diagram in Figure 4.1 describes the patterns for our tokens. It includes the actions required on each transition of the state diagram. The following is a C implementation of a lexical analyzer specified in the state diagram of Figure 4.1, including a main driver function for testing purposes /* front .c a lexical analyzer system for simple arithmetic expressions */ # include #include
ctype.h> /* Global declarations / /Variables / int charclass; char lexeme [1001 char nextchar; int lexten; int token; int nextToken; FILE in fp, *fopen)i 4.2 Lexical Analysis 173 Figure 4.1 Letter/Digit addChar i getchar A state diagram to recognize names, parentheses, and arithmetic operators Letter Start addchar: get id)return lookup (lexeme) Digit addChar, getchar (( int ) return Int-Lit Digit addchar getchar te lookup (nextchar) getChar unknown Done return t /*Function declarations void addchar ) void getChar ) void getNonBlank ) int lex() /Character classes/ #define LETTER 0 #define DIGIT 1 #de fine UNKNOWN 99 /* Token codes / #define INTLIT 10 #define IDENT 11 #de fine ASSIGN OP 20 #define ADDOp 21 #de fine SUB OP 22 #define MULT OP 23 #define DIVOP 24 #define LEFTPAREN 25 #define RIGHTPAREN 26 - - - - - 174 Chapter 4 Lexical and Syntax Analysis /* main driver / main) f /* Open the input data file and process its contents */ if ((in fp fopen ("front.in", "r"))NULL) printf ("ERROR cannot open front in In") else f getChar do f 1ex(); } while (nextToken != EOF); /* lookup a function to lookup operators and parentheses and return the token/ int lookup (char ch) ( switch (ch) case ( addChar () nextToken = LEFTPAREN; break; - case)" addChar nextToken = RIGHT PAREN; break; case '+': addChar nextToken break; ADDOP; - case - addChar () nextToken SUB_OP; break; case '*' . addChar 0 nextToken break; MULT OP; 176 Chapter 4 Lexical and Syntax Analysis /lex-a simple lexical analyzer for arithmetic expressions / int lex) f getNonBlank ) switch (charClass) /* Parse identifiers */ case LETTER: addChar getChar 0i while (charclassLETTER charClassDIGIT) ( addchar ) getchar) nextToken IDENT break; /* Parse integer lterals +/ case DIGIT: addChar ) getchar) while (charclassDIGIT) ( addChar getchar O nextToken = INT LIT ; break; /+ Parentheses and operators / case UNKNOWN: lookup (nextChar) getchar break /EOF case EOF: nextToken = EOF; lexeme [0] = ' E ; lexeme [1]O lexeme [ 2 ] = ' F ' ; lexeme [ 3 ] O i break ) /t End of switch / 4.3 The Parsing Problem printf ("Next token is: %d, Next Iexeme is %s ", next Token, lexeme) i return nextToken; )/End of function lex */ This code illustrates the relative simplicity of lexical analyzers. Of course, we have left out input buffering, as well as some other important details. Further- more, we have dealt with a very small and simple input language Consider the following expression