Professional Documents
Culture Documents
Compiler Design ECX6235 Answers For Tma 02: Name Reg. No Centre Due Date
Compiler Design ECX6235 Answers For Tma 02: Name Reg. No Centre Due Date
ECX6235
ANSWERS FOR TMA 02
REG. No : 511078618
CENTRE : COLOMBO
User
Lamps
GUI
Ceiling fan
STATUS → on | off
SWITCH → on | off (Remove this production)
(a)
Grammar
(b)
START
get COMPONENT
LAMP STATUS
lamp1 on
[Q2]
(a)
(b)
Lex code
/* Home Automation */
%{
#include "y.tab.h"
#include <stdlib.h>
#include <string.h>
/*#include "home.h" */
void yyerror(char *);
%}
DIGIT [0-9]
%%
{DIGIT}+ { return(NUMBER); }
START { return(START); }
COMPONENT{ return(COMPONENT); }
COMPONENT{ return(STATUS); }
LAMP { return(LAMP); }
lamp1 { return(l1); }
lamp2 { return(l2); }
FAN {return(FAN)}
fan {return(fan)}
. yyerror("Unknown character");
%%
int yywrap(void) {
return 1;
}
Yacc code
%{
#include <stdio.h>
#include <stdlib.h>
/* #include "home.h" */
}%
%token DIGIT
%token START
%token COMPONENT
%token STATUS
%token LAMP
%token lamp1
%token lamp2
%token FAN
%token fan
%token on
%token off
%%
program:
program expr '\n' { printf("%d\n", $2); }
|
;
STATUS:
LAMP
| on {$$ = $1}
| off {$$ = $2}
FAN
| on {$$ = $3}
| off {$$ = $4}
%%
int main(void) {
yyparse();
return 0;
}
[Q3]
Correctness rules
• There are only two components are valid (LAMP & FAN)
• Only positive Integer values (0-9) are valid input for lamps.
• When a component add to the design it is on ‘off’ status.
[Q4]
Parsing Mechanisms
Parsing
Bottom up Parsing
Bottom-up parsing starts with the input symbols and tries to construct the parse tree up to the
start symbol. From leaves to the root
Top-down Parsing
A top-down parser starts with the root of the parse tree.The root node is labeled with the goal
symbol of the grammar
Repeat until the leaves of the parse tree matches the input string
• At a node labeled A, select a production with A on its LHS and, for each symbol on its
RHS, construct the appropriate child
• When a terminal symbol is added to the fringe and it doesn’t match the fringe,
backtrack
• Find the next node to be expanded (label ∈ NT).The key is picking the right production
in step 1
When the parser starts constructing the parse tree from the start symbol and then tries to
transform the start symbol to the input, it is called top-down parsing.
• Backtracking
It means, if one derivation of a production fails, the syntax analyzer restarts the process
using different rules of same production. This technique may process the input string
more than once to determine the right production.
The top-down techniques can be implemented in any recursive programming language. Like
any program. Top down investing really favours those who are adept at predicting the direction.
But its extreme simplicity is also top-down parsing's great strength. Because a top-down parser
is extremely simple, it is very easy to figure out what it is doing. And easy to figure out means
easy to customize.