0% found this document useful (0 votes)
5 views5 pages

CD Week 4

The document outlines two experiments involving YACC and Lex for parsing strings and arithmetic expressions. The first experiment checks if the string 'aaabbb' is accepted by a specified grammar, while the second validates arithmetic expressions with various operators. Both experiments include detailed algorithms, code snippets, and conclusions on the effectiveness of the parsers.

Uploaded by

yeruvamokshitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

CD Week 4

The document outlines two experiments involving YACC and Lex for parsing strings and arithmetic expressions. The first experiment checks if the string 'aaabbb' is accepted by a specified grammar, while the second validates arithmetic expressions with various operators. Both experiments include detailed algorithms, code snippets, and conclusions on the effectiveness of the parsers.

Uploaded by

yeruvamokshitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Roll No:160122733163.. Exp.no:4 Date:10-02-2025………...

1.Aim: Check whether string aaabbb is accepted by given grammar below using YACC or
not S-> aSb|S

Description: Parsing is the process of analyzing a string of symbols to determine its syntactic
correctness according to a given grammar. This process is performed by a parser, which
checks whether an input string follows the production rules of a formal grammar.

• The lexer (Lex/Flex) converts the input into tokens (A for 'a', B for 'b').
• The parser (YACC) matches the tokens against the grammar.
• If the string matches the grammar rules, it is accepted; otherwise, it is rejected.

Functions used:
• yyparse(): This function is the main parser generated by YACC, which processes tokens
according to the grammar rules. It repeatedly calls yylex() to get tokens and determines if
the input string is valid or not.
• yyerror(char *msg): This function is called when a syntax error occurs during parsing. It
prints "Rejected" and terminates the program using exit(1).
• yywrap(): This function is called by yylex() when the end of the input file is reached.
Returning 1 indicates no more input is available.

Algorithm:

• Start by defining the grammar rules: S → aSb and S → ε.


• Use a lexical analyzer (Flex) to tokenize input characters ('a' → A, 'b' → B, \n → End).
• Read the input string character by character and convert it into tokens.
• Pass the tokens to the YACC parser for syntax validation.
• Begin parsing from the start symbol S.
• If the first token is A, recursively call S and expect a matching B.
• If an empty string is encountered, return successfully as it is a valid base case.
• If tokens do not match the expected pattern, report a syntax error and reject the input.
• If all characters are processed successfully, print "Accepted".
• If a mismatch or an extra/missing character is found, print "Rejected" and terminate.

Code:

Lex program:

%{
#include "y.tab.h"
%}

%%
a return A;
b return B;
\n return '\n';
. return 0; // Invalid character
%%

Page No. ………………….. Signature of the Faculty………………………...


Roll No:160122733163.. Exp.no:4 Date:10-02-2025………...

int yywrap() {
return 1;
}

YACC program:
%{
#include <stdio.h>
#include <stdlib.h>
int yylex();
void yyerror(char *msg);
%}

%token A B

%%
start : S '\n' { printf("Accepted\n"); return 0; }
S :ASB
|;
%%

void yyerror(char *msg) {


printf("Rejected\n");
exit(1);
}

int main() {
printf("Enter the string:\n");
yyparse();
}

Output1 :

Conclusion:
The YACC-based parser effectively verifies whether a given string follows the specified
grammar. It ensures that every 'a' has a matching 'b' in the correct order using recursive
parsing. The lexer converts input characters into tokens, while the parser applies grammar
rules for validation. If the input follows the expected pattern, it is accepted; otherwise, it is
rejected.

Page No. ………………….. Signature of the Faculty………………………...


Roll No:160122733163.. Exp.no:4 Date:10-02-2025………...

2.Aim: Program to implement parser with scanner


i)To recognize a valid arithmetic expression with use operators +,-,*,%,/ using lex,YACC
tool

Description:
This program validates arithmetic expressions containing numbers, identifiers, and operators
(+, -, *, /) using Lex (Flex) for lexical analysis and YACC (Bison) for syntax analysis.
Lex (Lexer):
• Recognizes numbers ([0-9]+) and assigns them as NUMBER tokens.
• Recognizes identifiers ([a-zA-Z]+) and assigns them as ID tokens.
• Ignores whitespace and tabs.
• Returns operators and parentheses as single-character tokens.
YACC (Parser):
• Defines grammar rules for arithmetic expressions.
• Supports operators (+,-,*,/) with correct precedence and associativity.
• Handles negative numbers and identifiers.
• Uses yyerror() to detect invalid expressions.

Algorithm:

• Read the input string and tokenize numbers, identifiers, and operators.
• Skip whitespace and invalid characters.
• Start parsing from the expr non-terminal.
• Apply operator precedence and associativity using %left.
• Use recursive rules to recognize valid expressions.
• Single numbers (NUMBER) and identifiers (ID) are valid.
• Operators follow precedence (*, / before +, -).
• Parentheses enforce priority.
• If an unexpected token is found, yyerror() prints "Expression is invalid".
• If parsing completes successfully, "Expression is valid" is printed.
• Otherwise, an error message is displayed.

Code:

Lex program:
%{
#include"y.tab.h"
extern yylval;
%}

/* defined section */

%%

[0-9]+ {yylval=atoi(yytext); return NUMBER;} //this is send to the yacc code as token
INTEGER
[a-zA-Z]+ {return ID;} //this is send to the yacc code as token ID

Page No. ………………….. Signature of the Faculty………………………...


Roll No:160122733163.. Exp.no:4 Date:10-02-2025………...

[\t]+ ;
\n {return 0;}
. {return yytext[0];}
%%

YACC program:
%{
#include<stdio.h>
%}
%token NUMBER ID
%left '+' '-'
%left '*' '/'

%%
expr: expr '+' expr
|expr '-' expr
|expr '*' expr
|expr '/' expr
|'-'NUMBER
|'-'ID
|'('expr')'
|NUMBER
|ID
;
%%

//main function

main()
{
printf("Enter the expression\n");
yyparse();
printf("\nExpression is valid\n");
exit(0);
}

//if error occured

int yyerror(char *s)


{
printf("\nExpression is invalid");
exit(0);
}

Page No. ………………….. Signature of the Faculty………………………...


Roll No:160122733163.. Exp.no:4 Date:10-02-2025………...

Output1:

Conclusion:

This Lex-YACC program efficiently verifies arithmetic expressions by using tokenization


and syntax analysis. It ensures correct precedence, associativity, and validity of expressions
while rejecting invalid inputs. The use of recursive parsing allows flexibility in recognizing
complex expressions.

Page No. ………………….. Signature of the Faculty………………………...

You might also like