Skip to main content

8. Implementation of Calculator using LEX and YACC


Implementing a calculator using LEX and YACC involves defining the lexical rules using LEX and the grammar rules using YACC to parse and evaluate arithmetic expressions. Let's go through each line of code step by step.


**Lexer (Lexical Analyzer using LEX)**


Here's the code for the Lex part of the calculator:


```lex

%{

#include "y.tab.h"

%}


%%


[0-9]+      { yylval = atoi(yytext); return NUM; }

[-+\*/\(\)] { return yytext[0]; }

[ \t\n]     ; /* Ignore whitespace */


%%

```


Explanation of the Lex code:


1. `%{ ... %}`: This section allows including C code within the Lex file. Here, we include the "y.tab.h" header file that will be generated by YACC, containing token definitions.


2. `%%`: This double percentage sign separates the Lex rules from the C code.


3. `[0-9]+`: This rule matches a sequence of digits (a number) and converts it to an integer using `atoi()`. The `yylval` variable is used to pass the value to YACC, and `NUM` is returned as the token.


4. `[-+\*/\(\)]`: This rule matches operators (+, -, *, /) and parentheses. The corresponding character is returned as a token.


5. `[ \t\n]`: This rule matches whitespace characters (space, tab, newline) and ignores them.


**Parser (YACC Grammar)**


Now, let's look at the YACC part of the calculator:


```yacc

%{

#include <stdio.h>

int yylex();

void yyerror(const char *s);

%}


%token NUM


%%

expression : NUM

           | expression '+' expression

           | expression '-' expression

           | expression '*' expression

           | expression '/' expression

           | '(' expression ')'

           ;


%%


int main() {

    yyparse();

    return 0;

}


void yyerror(const char *s) {

    fprintf(stderr, "Error: %s\n", s);

}

```


Explanation of the YACC code:


1. `%{ ... %}`: Similar to Lex, this section allows including C code within the YACC file. We include the necessary header and define `yylex()` and `yyerror()` functions.


2. `%token NUM`: This defines a token name for numbers recognized by Lex.


3. `%%`: Separates the YACC rules from the C code.


4. `expression`: This is the main grammar rule for arithmetic expressions. It defines how expressions can be formed using operators and parentheses.


5. `NUM`: Represents a terminal symbol (token) for numbers recognized by Lex.


6. The grammar rules below `expression` define the different ways arithmetic expressions can be formed, including addition, subtraction, multiplication, division, and parentheses.


7. `main()`: This function initiates the parsing process by calling `yyparse()`.


8. `yyerror()`: This function is called when an error is encountered during parsing. It prints an error message.


The Lex and YACC programs work together to read input expressions, tokenize them, and then parse and evaluate the expressions using the defined grammar rules.


Please note that the provided code snippets are simplified for explanation purposes and might need additional adjustments to handle edge cases, error handling, and proper expression evaluation.


Comments

Popular posts from this blog

Program 6: Finding Prime Numbers in a Range

  ** Program 6: Finding Prime Numbers in a Range ** ```assembly .model small .stack 100h .data     start dw 1     end dw 20 .code     main proc         mov ax, start           ; Load 'start' into AX              find_primes:         inc ax                  ; Move to the next number         cmp ax, end             ; Compare with 'end'         jg end_prog             ; Jump to end if AX > 'end'                  mov cx, ax              ; Copy AX to CX   ...

4. Write a LEX Program to convert the substring abc to ABC from the given input string.

Sure, here's a LEX program that converts the substring "abc" to "ABC" in the given input string: ```lex %{ #include <stdio.h> %} %% .*abc.*    { printf("%s", yytext); }    /* Match and print everything containing 'abc' */ .         ;                            /* Ignore other characters */ %% int main() {     yylex();     return 0; } ``` Now, let's break down the code line by line: 1. `%{` and `%}`: These are used to enclose C code that should be included in the generated C code. In this case, it includes the standard input-output library (`<stdio.h>`). 2. `.*abc.*`: This is a regular expression pattern. It matches any sequence of characters that contains the substring "abc". 3. `{ printf("%s", yytext); }`: This is the action associated with the pattern. When the pattern is matched, the `yytext` variable contains the matched te...

ktu 2019 Cse Complier programing Lab Syllabus

 1Design and implement a lexical analyzer using C language to recognize all valid tokens  in the input program. The lexical analyzer should ignore redundant spaces, tabs and  newlines. It should also ignore comments. 2. Implement a Lexical Analyzer for a given program using Lex Tool. 3. Write a lex program to display the number of lines, words and characters in an input text. 4. Write a LEX Program to convert the substring abc to ABC from the given input string. 5. Write a lex program to find out the total number of vowels and consonants from the given  input string. 6. Generate a YACC specification to recognize a valid arithmetic expression that uses  operators +, – , *,/ and parenthesis. 7. Generate a YACC specification to recognize a valid identifier which starts with a letter  followed by any number of letters or digits.   8. Implementation of Calculator using LEX and YACC  9. Convert the BNF rules into YACC form and write code to generat...