0% found this document useful (0 votes)
38 views30 pages

EX 8 - 14 47 ACD - Merged

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)
38 views30 pages

EX 8 - 14 47 ACD - Merged

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/ 30

IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY

Exercise no: IMPLEMENTATION OF SHIFT REDUCE PARSER


Date:

AIM:
To implement shift reduce parser in java.
DESCRIPTION:
A Shift-Reduce parser (SR parser) is a type of bottom-up parsing technique used in compiler construction to
analyze the syntax of a given input string according to a specified grammar. It operates by iteratively shifting
tokens from the input onto a stack and then reducing portions of the stack when possible based on the grammar
rules. The process continues until the entire input is processed and successfully parsed, or until a parsing error is
encountered.
ALGORITHM:
1:Initialize a stack with a special start symbol and an input buffer containing the tokens of the input string.
2:Repeat until either the stack is empty or the input buffer is empty:
a. If the stack's top symbol is a terminal or a non-terminal that does not have a production rule that applies to the
current input symbol, shift the next input token onto the stack.
b. If the stack's top symbol combined with some symbols below it form the right-hand side of a production rule,
reduce it by replacing those symbols with the corresponding non-terminal symbol on the left-hand side of the
production rule.
3:If the stack contains only the start symbol and the input buffer is empty, parsing is successful.
PROGRAM CODE:
import java.util.Scanner;

public class Parser {


static int i = 0, j = 0, c = 0;
static char[] stk = new char[50];

static void check(char[] a) {


String ac = "REDUCE TO ";
int len = stk.length;
for (int z = 0; z < len - 2; z++) {
if (stk[z] == 'i' && stk[z + 1] == 'd') {
System.out.printf("%sS\n$%s\t%s$\t", ac, new String(stk), new String(a));
stk[z] = 'S';
stk[z + 1] = '\0';
return;
}
if (stk[z] == 'S' && stk[z + 1] == '+' && stk[z + 2] == 'S') {
System.out.printf("%sS+S\n$%s\t%s$\t", ac, new String(stk), new String(a));
stk[z] = 'S';
stk[z + 1] = '\0';
Registration no:2127210801047 Page no:
IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
stk[z + 2] = '\0';
return;
}
if (stk[z] == 'S' && stk[z + 1] == '*' && stk[z + 2] == 'S') {
System.out.printf("%sS*S\n$%s\t%s$\t", ac, new String(stk), new String(a));
stk[z] = 'S';
stk[z + 1] = '\0';
stk[z + 2] = '\0';
return;
}
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Enter the grammar:");


String grammar = scanner.nextLine();

System.out.println("Enter the input string:");


String input = scanner.nextLine();
scanner.close();

System.out.println("GRAMMAR is -\n" + grammar);


c = input.length();
System.out.println("\nstack \t input \t action\n$\t" + input + "$\t");

char[] a = input.toCharArray();
for (i = 0; j < c; i++, j++) {
System.out.print("SHIFT\n$");
stk[i] = a[j];
stk[i + 1] = '\0';
a[j] = ' ';
System.out.printf("%s\t%s$\t", new String(stk), new String(a));
check(a);
}
check(a);
if (stk[0] == 'S' && stk[1] == '\0')
System.out.println("Accept");
else
System.out.println("Reject");
}
}

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY

OUTPUT:

RESULT:
Thus, the implementation of shift reduce parser in java has been executed successfully.

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
Exercise no: LEX PROGRAMS
Date:

a. To count the vowels and consonants of a string.


b. To check whether the number is positive or negative.
c. To check whether the number is even or odd.
d. To check the mismatching parenthesis.
e. To check whether the identifier is valid or not.
f. To analyze the lexemes of a program .

a. To count the vowels and consonants of a string.

AIM
To count the vowels and consonants of a string.
ALGORITHM
1. The %option noyywrap directive is used to specify that Flex should not generate code forwrapping the
input file in a loop.
2. %{ ... %} is used for including code that will be copied directly into the generatedscanner.
3. Inside the code section, two variables vow and con are declared to count the number ofvowels and
consonants, respectively.
4. The %% section is where the regular expressions and corresponding actions are defined.
5. [aeiouAEIOU] {vow++;}: This regular expression matches any vowel (uppercase orlowercase) and
increments the vow counter.
6. [A-Z,a-z] {con++;}: This regular expression matches any alphabet (uppercase orlowercase) and
increments the con counter.
7. The main() function is where the program starts execution.
8. It prompts the user to enter some input string.
9. Then, it calls yylex(), which is a function generated by Flex. yylex() scans the input andmatches the
defined regular expressions, executing the corresponding actions.
10. After scanning is complete, it prints the counts of vowels and consonants.
PROGRAM
%option noyywrap
%{
#include<stdio.h>int vow=0, con=0;

%}

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
%%
[aeiouAEIOU] {vow++;}[A-Z,a-z]
{con++;}
%%
main( )
{
printf("Enter some input string:\n");yylex();
printf("Number of vowels=%d\n",vow);

printf("Number of consonants=%d\n",con);
}
OUTPUT

RESULT
Thus the lex program to count the vowels and consonants has been executed successfully.

b. To check whether the number is positive or negative.

AIM
To check whether the number is positive or negative.
ALGORITHM
1. The %option noyywrap directive specifies that Flex should not generate code forwrapping the
input file in a loop.
2. The %{ ... %} section includes the standard input/output library for printf.
1. The %% section is where the regular expressions and corresponding actions aredefined.
Registration no:2127210801047 Page no:
IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
2. [0-9]+: Matches one or more digits, representing a positive number. When a positivenumber is
found, it prints "Positive number" using printf.
3. -[0-9]+: Matches a hyphen followed by one or more digits, representing a negative number. When a
negative number is found, it prints "Negative number" using printf.
4. The main() function is where the program starts execution.
5. It calls yylex(), which is a function generated by Flex. yylex() scans the input andmatches the
defined regular expressions, executing the corresponding actions.
PROGRAM
%option noyywrap
%{
#include<stdio.h>
%}

%%
[0-9]+ {
int num = atoi(yytext);
if (num % 2 == 0) {
printf("%d is even\n", num);
}
else {
printf("%d is odd\n", num);
}
}
. { /* Ignore other characters */ }
%%

int main()
{
yylex();
return 0;

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
OUTPUT

RESULT
Thus the lex program to check whether the number is even or odd has been executedsucessfully.

c. To check whether the number is even or odd.

AIM
To check whether the number is even or odd.

ALGORITHM
1. The %option noyywrap directive specifies that Flex should not generate code forwrapping the
input file in a loop.
2. The %{ ... %} section includes the standard input/output library for printf.
3. The %% section is where the regular expressions and corresponding actions are defined.
4. [0-9]+: Matches one or more digits, representing a numeric constant. When a number isfound, the code
inside the action block is executed.
5. int num = atoi(yytext);: Converts the matched text (numeric constant) to an integer usingatoi() and
stores it in the variable num.
6. if (num % 2 == 0) { printf("%d is even\n", num); }: Checks if the number is even by calculating the
remainder when divided by 2. If the remainder is 0, it prints "is even."
7. else { printf("%d is odd\n", num); }: If the remainder is not 0, it prints "is odd."
8. .: Ignores other characters.
9. The int main() function is where the program starts execution.
10. It calls yylex(), which is a function generated by Flex. yylex() scans the input andmatches the
defined regular expressions, executing the corresponding actions.

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY

PROGRAM
%option noyywrap
%{
#include<stdio.h>
%}
%%
[0-9]+ { printf("Positive number\n"); }
-[0-9]+ { printf("Negative number\n"); }
%%
main()
{
yylex();
}
OUTPUT

RESULT
Thus the lex program to check whether the number is positve or negative has beenimplemented
successfully.

d. To check the mismatching parenthesis.


AIM
To check the mismatching parenthesis.

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY

ALGORITHM
1. Two integer variables openParenthesesCount and unmatchedClosingParenthesesCount are declared to
count the number of open parentheses and unmatched closing parentheses,respectively.
2. The %{ ... %} section contains code that will be copied directly into the generatedscanner.
3. Inside the %{ ... %} section, the two variables openParenthesesCount and
unmatchedClosingParenthesesCount are declared and initialized to 0.
4. The %% section is where the regular expressions and corresponding actions are defined.
5. \(: This regular expression matches an open parenthesis and increments the
openParenthesesCount.
6. \): This regular expression matches a closing parenthesis.
7. If there are open parentheses (openParenthesesCount > 0), it decrements the
openParenthesesCount.
8. Otherwise, it increments the unmatchedClosingParenthesesCount to track unmatchedclosing
parentheses.
9. .: This regular expression matches any character except newline.
10. It is followed by ;, indicating that other characters are ignored.
11. The int main(void) function is where the program starts execution.
12. It prompts the user to enter a string with parentheses.
13. Then, it calls yylex(), which is a function generated by Flex. yylex() scans the input andmatches the
defined regular expressions, executing the corresponding actions.
14. After scanning is complete, it checks if there are any unmatched opening or closingparentheses
and prints the appropriate message.
PROGRAM
%option noyywrap
%{
#include<stdio.h>
int openParenthesesCount = 0;
int unmatchedClosingParenthesesCount = 0;
%}

%%
\( { openParenthesesCount++; }
\) {

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
if (openParenthesesCount > 0) {
openParenthesesCount--;
} else {
unmatchedClosingParenthesesCount++;
}
}
. ; // Ignore other characters
%%

int main(void) {
printf("Enter a string with parentheses: ");yylex();

if (openParenthesesCount > 0) {
printf("Unmatched opening parentheses: %d\n", openParenthesesCount);
}
else if (unmatchedClosingParenthesesCount > 0) {
printf("Unmatched closing parentheses: %d\n", unmatchedClosingParenthesesCount);
}
else {
printf("All parentheses are matched!\n");
}
return 0;
}

OUTPUT

RESULT
Thus the lex program to check for matching paranthesis has been executed successfully.

e. To check whether the identifier is valid or not.

AIM
Registration no:2127210801047 Page no:
IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
To check whether the identifier is valid or not.
ALGORITHM
1. The %option noyywrap directive specifies that Flex should not generate code forwrapping the
input file in a loop.
2. The %{ ... %} section includes the standard input/output library for printf.
3. The %% section is where the regular expressions and corresponding actions are defined.
4. [a-zA-Z_][a-zA-Z0-9_]*: Matches a valid identifier. It starts with an alphabetic characteror underscore,
followed by zero or more alphanumeric characters or underscores. When avalid identifier is found, it prints
"Valid identifier" using printf.
5. [^a-zA-Z_][^a-zA-Z0-9_]*: Matches an invalid identifier. It starts with a character that isnot an
alphabetic character or underscore, followed by zero or more characters that are not alphanumeric
characters or underscores. When an invalid identifier is found, it prints"Invalid identifier" using printf.
6. The int main(void) function is where the program starts execution.
7. It prompts the user to enter an identifier.
8. Then, it calls yylex(), which is a function generated by Flex. yylex() scans the input andmatches the
defined regular expressions, executing the corresponding actions.
PROGRAM
%option noyywrap
%{
#include <stdio.h>
%}

%%
[a-zA-Z_][a-zA-Z0-9_]* { printf("Valid identifier: %s\n"); }
[^a-zA-Z_][^a-zA-Z0-9_]* { printf("Invalid identifier: %s\n"); }
%%

int main(void) {
printf("Enter an identifier: ");
yylex();
return 0;
}

OUTPUT

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY

RESULT
Thus the lex program to identify the valid idenntifier hass been executed successfully.

g. To analyze the lexemes of a program .

AIM
To analyze the lexemes of a program .
ALGORITHM
1. The %option noyywrap directive specifies that Flex should not generate code forwrapping the
input file in a loop.
2. The %{ ... %} section includes the standard input/output library for printf.
3. The %% section is where the regular expressions and corresponding actions are defined.
⚫ int|float|double|char|void: Matches C keywords (int, float, double, char, void) and printsthem as
"Keyword."
⚫ [a-zA-Z_][a-zA-Z0-9_]*: Matches identifiers (variable names) and prints them as"Identifier."
⚫ [0-9]+: Matches integer constants and prints them as "Integer Constant."
⚫ [0-9]*\.[0-9]+: Matches float constants and prints them as "Float Constant."
⚫ \"([^\\\"]|\\.)*\": Matches string constants and prints them as "String Constant."
⚫ \'([^\\\']|\\.)*\': Matches character constants and prints them as "Character Constant."
⚫ [+\-*/%]: Matches arithmetic operators (+, -, *, /, %) and prints them as "Operator."
==|!=|<=|>=|<|>: Matches relational operators (==, !=, <=, >=, <, >) and prints them as"Relational
Operator."
=: Matches the assignment operator (=) and prints it as "Assignment Operator."
⚫ [;:,\(\)\[\]\{\}]: Matches various punctuation characters and prints them as "Punctuation."
⚫ .: Ignores other characters.

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
4. The int main(void) function is where the program starts execution.
5. It prompts the user to enter a C program.
6. Then, it calls yylex(), which is a function generated by Flex. yylex() scans the input andmatches the
defined regular expressions, executing the corresponding actions.
7. It identifies and prints the category of each recognized token (keyword, identifier,constant,
operator, etc.).
PROGRAM
%option noyywrap
%{
#include <stdio.h>
%}
%%
int|float|double|char|void
{ printf("Keyword: %s\n", yytext); }
[a-zA-Z_][a-zA-Z0-9_]*{ printf("Identifier: %s\n", yytext); }
[0-9]+ printf("Integer Constant: %s\n", yytext); } [0-9]*\.[0-9]+
{ printf("Float Constant: %s\n", yytext); }
\"([^\\\"]|\\.)*\" { printf("String Constant: %s\n", yytext); }
\'([^\\\']|\\.)*\' { printf("Character Constant: %s\n", yytext); }[+\-*/%]
{ printf("Operator: %s\n", yytext); }
==|!=|<=|>=|<|> { printf("Relational Operator: %s\n", yytext); }
= { printf("Assignment Operator: %s\n", yytext); }
[;:,\(\)\[\]\{\}]
{ printf("Punctuation: %s\n", yytext); }
. { /* Ignore other characters */ }
%%
int main(void) {
printf("Enter a C program:\n");
yylex();

return 0;
}

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
OUTPUT

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY

RESULT
Thus the lex program to analyze the lexemes has been executed successfully.

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
Exercise no: YACC IMPLEMENATION
Date:

AIM:

To implement YACC- calculator .


DESCRIPTION:
YACC, or "Yet Another Compiler Compiler," is a tool used in compiler design to generate parsers for formal
grammars. It takes input in the form of a grammar specification, typicallywritten in BNF or EBNF notation,
and produces a parser in a chosen programming languagesuch as C or C++. This parser can analyze the
syntactic structure of input programs, aiding subsequent compiler phases. YACC is commonly paired with Lex
(or Flex) for lexical analysis, together providing a comprehensive solution for building compilers, interpreters,
and language processing tools.
ALGORITHM:
1. Match sequences of digits ([0-9]+) and convert them into integers using atoi(). Set thevalue of yylval to
the converted integer and return token NUMBER.
2. Match newline characters (\n) and return 0.
3. Match any other character and return it as a token.
4. yywrap() which is invoked when the end of input is reached. Always return 1 indicatingthe end of input.
5. Declare tokens, their precedence, and any external variables.
6. Define the start symbol as ArithmeticExpression.
7. Expressions (E) can be built recursively using various arithmetic operators, parentheses,or numbers.
8. Define actions for each rule to compute the result of the expression.
9. In Main Function print a prompt for the user to enter an arithmetic expression.
⚫ Invoke the parser using yyparse().
⚫ Check the flag variable to determine if the expression is valid or not.
10. Error Handling Function (yyerror()):
11. Print a message indicating that the entered expression is invalid.
12. Set the flag variable to 1 indicating an error occurred.

PROGRAM CODE:

arithmetic.l
%{
#include <stdio.h>
#include "y.tab.h"extern int yylval;

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
%}
%%
[0-9]+ {
yylval = atoi(yytext);
return NUMBER;
}
[\n] return 0;
. return yytext[0];
%%
int yywrap()
{
return 1;
}
arithmetic.y
%{
#include<stdio.h>int flag=0;
%}
%token NUMBER
%left '+' '-'
%left '*' '/' '%'
%left '(' ')'
%%
ArithmetiExpression:E{ printf("\nResult = %d",$$);return 0;
};
E:E'+'E{$$=$1+$3;}

|E'-'E{$$=$1-$3;}
|E'*'E{$$=$1*$3;}
|E'/'E{$$=$1/$3;}
|E'%'E{$$=$1%$3;}
|'('E')'{$$=$2;}
|NUMBER{$$=$1;}
%%
void main() {
printf("\nEnter Any Arithmetic Expression\n");
yyparse(); if(flag==0)

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
printf("\nEntered Arithmetic Expression is valid\n\n");
}
void yyerror()
{
printf("\nEntered Arithmetic Expression is invalid\n\n");
flag=1;
}

OUTPUT:

RESULT:
Thus the YACC calculator has been executed successfully.

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
Exercise no: TYPE CHECKING
Date:

AIM:
Develop a Java program to perform type checking on variable declarations and expressions.

DESCRIPTION:
The program prompts the user to enter variable declarations in the format "DataType VariableName" and then
enter an expression. It checks whether the data types of variables used in the expression match those declared.

ALGORITHM:
1. Start the main function.
2. Prompt the user to enter variable declarations.
3. Read the input and extract variable declarations using the extractVariableDeclarations function.
4. If no variables are declared, print "No variables declared" and end the program.
5. Otherwise, prompt the user to enter an expression.
6. Read the expression and perform type checking using the checkDataTypes function.
7. If all variables in the expression have the same data type, print "Data types of all variables
in theexpression match"; otherwise, print "Data types of variables in the expression do not
match".
8. End the main function.

PROGRAM CODE:

import java.util.*;
import java.util.Map;
import
java.util.Scanner;

public class TypeChecker {


public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);

System.out.println("Enter variable declarations (Format: <DataType> <VariableName>, separate


multiplevariables with commas):");
Map<String, String> variables = extractVariableDeclarations(scanner.nextLine());

if (variables.isEmpty()) {
System.out.println("Novariablesdeclared.
);
} else {

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
System.out.println("Enter the
expression:");String expression =
scanner.nextLine();

if (checkDataTypes(expression, variables)) {
System.out.println("Data types of all variables in the expression match");
} else { System.out.println("Data types of variables in the expression do not match");
}
}
scanner.close();
}
public static Map<String, String> extractVariableDeclarations(String declarationInput) {
Map<String, String> variables = new HashMap<>();
String[] declarations = declarationInput.split(",");

for (String declaration : declarations) {


String[] parts =
declaration.trim().split("\\s+");if
(parts.length == 2) {
variables.put(parts[1], parts[0]);
} else {
System.out.println("Invalid declaration: " + declaration);
}
}
return variables;
}
public static boolean checkDataTypes(String expression, Map<String, String> variables) {
String[] tokens = expression.split("[^a-zA-Z0-9]+");

String firstDataType =
null;for (String token :
tokens) {
if (variables.containsKey(token)) {
String dataType = variables.get(token);
System.out.println("Variable " + token + " is of type: " +
dataType);if (firstDataType == null) {
firstDataType = dataType;
} else if
(!firstDataType.equals(dataType)) {
return false;}}}
return true;}}

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY

OUTPUT:

RESULT:
Thus implemented type checking successfully.

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
Exercise no: INTERMEDIATE CODE GENERATION
Date:

AIM:
To generate intermediate code for a given infix expression.
DESCRIPTION:
The program prompts the user to enter an infix expression. It then converts the infix expression to postfix
notation and generates intermediate code for the postfix expression.
ALGORITHM:
1. Start the main function.
2. Prompt the user to enter an infix expression.
3. Read the expression and convert it to postfix notation using the infixToPostfix function.
4. Generate Three Address Code (TAC) for the postfix expression using the generateTAC function.
5. Print the generated TAC using the printTAC function.
6. End the main function.
PROGRAM CODE:
public class Icg {
private static final Map<Character, Integer> precedence = Map.of('+', 1, '-', 1, '*', 2, '/', 2, '%', 2, '^', 3);
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter the expression:");
String expression = scanner.nextLine();
scanner.close();
List<String> postfixExpression = infixToPostfix(expression);
List<String> tac = generateTAC(postfixExpression);
printTAC(tac);
}
private static List<String> infixToPostfix(String
expression) {List<String> postfix = new ArrayList<>();
Stack<Character> stack = new Stack<>();
for
(charexpression.toCharArray())
{
if (Character.isLetterOrDigit(c)) {
postfix.add(String.valueOf(c));
} else if (c ==
'(') {
stack.push(
c);
} else if (c == ')') {
while (!stack.isEmpty() && stack.peek() !=
'(') {
postfix.add(String.valueOf(stack.pop()));
Registration no:2127210801047 Page no:
IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
}

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
stack.pop(); // Remove '('
} else {
while (!stack.isEmpty() && precedence.getOrDefault(stack.peek(), 0) >=
precedence.getOrDefault(c,0)) { postfix.add(String.valueOf(stack.pop()));
} stack.push(c);}} while (!stack.isEmpty())
postfix.add(String.valueOf(stack.pop
()));return postfix;}
private static List<String> generateTAC(List<String>
postfixExpression) {List<String> tac = new ArrayList<>();
Stack<String> stack = new
Stack<>();int tempCount = 1;
for (String token : postfixExpression) {
if
(Character.isLetterOrDigit(token.charAt(
0))) {stack.push(token);
} else {
String op = token;
String arg2 =
stack.pop();String
arg1 = stack.pop();
String temp = "t" + tempCount++;
String tacInstruction = temp + " = " + arg1 + " " + op + " " +
arg2;tac.add(tacInstruction);
stack.push(tem
p);}}return tac;
}
private static void printTAC(List<String> tac) {
System.out.println("Three Address Code (TAC):");
tac.forEach(System.out::println);
}
}

OUTPUT:

RESULT:
Thus implemented intermediate code generation successfully.

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
Exercise no: IMPLEMENTATION OF DAG
Date:

AIM:
To implement Directed Acyclic Graph (DAG) for an expression.

DESCRIPTION:
The program prompts the user to enter an infix expression. It then converts the infix expression to postfix
notation, generates Three Address Code (TAC) for the postfix expression, and finally constructs a
DirectedAcyclic Graph (DAG) from the TAC.

ALGORITHM:
1. Start the main function.
2. Prompt the user to enter an infix expression.
3. Read the expression and convert it to postfix notation using the infixToPostfix function.
4. Generate Three Address Code (TAC) for the postfix expression using the generateTAC function.
5. Generate Quadruples from the TAC using the generateQuadruplesFromTAC function.
6. Print the generated TAC.
7. Print the Directed Acyclic Graph (DAG) constructed from the Quadruples.
8. End the main function.

PROGRAM CODE:
public class Dag {
private static final Map<Character, Integer> precedence = new HashMap<>();
static {
precedence.put('+', 1);
precedence.put('-', 1);
precedence.put('*', 2);
precedence.put('/', 2);
precedence.put('%', 2);
precedence.put('^', 3);
// Add more operators as needed
}
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter the expression:
"); String expression =
scanner.nextLine();
List<String> postfixExpression = infixToPostfix(expression);
List<String> tac = generateTAC(postfixExpression);
List<Quadruple> quadruples =
generateQuadruplesFromTAC(tac);System.out.println("Three
Registration no:2127210801047 Page no:
IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
Address Code (TAC):");
for (String instruction : tac)
System.out.println(instruction);
System.out.println("\nDAG");
printQuadruples(quadruples);
scanner.close();}
private static List<String> infixToPostfix(String expression) {List<String> postfix = new ArrayList<>();
Stack<Character> stack = new
Stack<>();for (char c :
expression.toCharArray()) {
if
(Character.isLetterOrDigit
(c)) {
postfix.add(String.valueOf
(c));
} else if (c ==
'(') {
stack.push(
c);
} else if (c == ')') {
while (!stack.isEmpty() && stack.peek()
!= '(')
postfix.add(String.valueOf(stack.pop())
);
stack.pop(); // Remove '('
} else {
while (!stack.isEmpty() && precedence.getOrDefault(stack.peek(), 0) >=
precedence.getOrDefault(c,0)) postfix.add(String.valueOf(stack.pop()));
stack.push(c);
}
}
while (!stack.isEmpty()) {
postfix.add(String.valueOf(stack.pop
()));
}
return postfix;
}
private static List<String> generateTAC(List<String>
postfixExpression) {List<String> tac = new ArrayList<>();
Stack<String> stack = new
Stack<>();int tempCount = 1;

for (String token : postfixExpression) {


if
(Character.isLetterOrDigit(token.charAt(
0))) {stack.push(token);

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
} else {
String op = token;
String arg2 =
stack.pop();String
arg1 = stack.pop();
String temp = "t" + tempCount++;
String tacInstruction = temp + " = " + arg1 + " " + op + " " +
arg2;tac.add(tacInstruction);
stack.push(temp);
}
}

return tac;}
private static List<Quadruple> generateQuadruplesFromTAC(List<String> tac) {
List<Quadruple> quadruples = new ArrayList<>();
int tempCount = 1;
for (String instruction : tac) {
String[] parts = instruction.split("\\s*=\\s*");
String[] opAndArgs =
parts[1].split("\\s+");String[] args =
new String[2];
String op =
opAndArgs[1];args[0]
= opAndArgs[0];
args[1] =
opAndArgs[2];
Quadruple quadruple = new Quadruple(op, args[0], args[1],
parts[0]);quadruples.add(quadruple);
} return quadruples;}
private static void printQuadruples(List<Quadruple> quadruples) {
System.out.println("| Operator | Argument 1 | Argument 2 | Result |");
System.out.println("| | | | |");
for (Quadruple quadruple : quadruples) {
System.out.printf("| %-9s| %-11s| %-11s| %-10s|%n", quadruple.op, quadruple.arg1, quadruple.arg2,
quadruple.result);}}}
class
Quadruple
{String
op; String
arg1;
String
arg2;
String
result;
public Quadruple(String op, String arg1, String arg2, String
result) {this.op = op;

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
this.arg1 = arg1; this.arg2 = arg2; this.result = result;}}

OUTPUT:

RESULT:
Thus implemented DAG successfully.

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
Exercise no: CODE GENERATION
Date:

AIM:
To generate code for a given arithmetic expression.
DESCRIPTION:
The program prompts the user to enter an arithmetic expression. It then generates assembly-like code for
loading variables and performing arithmetic operations based on the expression.
ALGORITHM:
1. Start the main function.
2. Prompt the user to enter an arithmetic expression.
3. Read the expression and store it in an array.
4. Iterate through the expression array:
• Load variables into registers and print corresponding assembly-like code.
• Perform arithmetic operations and print corresponding assembly-like code.
5. End the main function.

PROGRAM CODE:
import
java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the
expression:");String expression =
scanner.nextLine(); scanner.close();
char[] a =
expression.toCharArray();int h
= 0;

for (int i = 2; i < a.length;


i++) {if
(Character.isLetter(a[i]))
{
System.out.printf("\nMOV R%d, %c", h++, a[i]);
}
}

for (int i = 2; i < a.length; i++) {


if (a[i] == '+' || a[i] == '-' || a[i] == '*' || a[i] ==
'/') {char operation = a[i];
switch

Registration no:2127210801047 Page no:


IT18611-AUTOMATA AND COMPILER DESIGN LABORATORY
(operation) {
case '+':
System.out.printf("\nADD R0, R1\nSTF %c, R0",
a[0]);break;
case '-':
System.out.printf("\nSUB R0, R1\nSTF %c, R0",
a[0]);break;
case '*':
System.out.printf("\nMUL R0, R1\nSTF %c, R0", a[0]);

break;
case '/':
System.out.printf("\nDIV R0, R1\nSTF %c, R0", a[0]);
break;
}
}
}
}
}

OUTPUT:

RESULT:
Thus Implemented Code Generation successfully.

Registration no:2127210801047 Page no:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy