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

6. Generate a YACC specification to recognize a valid arithmetic expression that uses operators +, – , *,/ and parenthesis.

Below is a YACC specification for recognizing valid arithmetic expressions that involve operators (+, -, *, /) and parentheses. I'll explain each line of the code afterward: ```yacc %{ #include <stdio.h> %} %token NUMBER %left '+' '-' %left '*' '/' %% expression: expression '+' expression            | expression '-' expression            | expression '*' expression            | expression '/' expression            | '(' expression ')'            | NUMBER            ; %% int yylex() {     // Code for tokenizing input and returning tokens } void yyerror(const char *s) {     fprintf(stderr, "Error: %s\n", s); } int main() {     yyparse();     return 0; } ``` Now, let's break down the YACC specification line by line: 1. `%{` ... `%}`: This is the C code section where y...

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...

1, Design 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

#include <stdio.h> #include <ctype.h> int main() {     char c;     while ((c = getchar()) != EOF) {         if (isspace(c)) {             // Ignore whitespace, tabs, and newlines             continue;         }         if (c == '/') {             // Check for comments             char nextChar = getchar();             if (nextChar == '/') {                 while ((nextChar = getchar()) != '\n');         ...