Homework #2: CMPT-379 - Homework #2: CMPT-379 Distributed...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Homework #2: CMPT-379 Distributed on Sep 30; due on Oct 18 Anoop Sarkar – anoop@cs.sfu.ca Reading for this homework includes Chp 4 of the Dragon book. If needed, refer to: http://tldp.org/HOWTO/Lex-YACC-HOWTO.html Only submit answers for questions marked with . You must use a makefile such that make compiles all your programs, and make test runs each program, and supplies the necessary input files. You have been provided a file makefile.answer which you should use as your makefile. The stdout when you run make test must match makefile.answer.out , and stderr must match makefile.answer.err . (1) The following program is yacc code for a very simple (and incomplete) expression interpreter. %{ #include <stdio.h> %} %token NAME NUMBER %% statement: NAME ’=’ expression { printf("%c = %d\n", $1, $3); } | expression { printf("%d\n", $1); } ; expression: expression ’+’ NUMBER { $$ = $1 + $3; } | expression ’-’ NUMBER { $$ = $1 - $3; } | NUMBER { $$ = $1; } ; %% The % { . . . % } section contains arbitrary C / C ++ code and the %token definitions is a list of tokens provided by the lexical analyzer. bison can be used to convert this parser definition into a parser implementation by using the following command: bison -osimple-expr.tab.c -d simple-expr.y The -d option produces a header file called simple-expr.tab.h to convey information about the tokens to the lexical analyzer. Examine the contents of this file. The lexical analyzer can be defined in lex code as follows: %{ #include "simple-expr.tab.h" #include <stdlib.h> extern int yylval; %} %% [0-9]+ { yylval = atoi(yytext); return NUMBER; } [a-z] { yylval = yytext[0]; return NAME; } [ \t\n] ; . return yytext[0]; %% The lex file can be compiled to a C program using flex : flex -osimple-expr.lex.c simple-expr.lex The final interpreter binary is created by compiling the output from flex and bison with a C / C ++ compiler: 1
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
gcc -o ./simple-expr simple-expr.tab.c simple-expr.lex.c -ly -lfl echo "a=2+3+5" | ./simple-expr Convert the above yacc and lex code so that it can handle multiple expressions, exactly one per line. For
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 03/28/2011 for the course COMPUTING 379 taught by Professor Dr.anoopsarkar during the Spring '11 term at American College of Computer & Information Sciences.

Page1 / 5

Homework #2: CMPT-379 - Homework #2: CMPT-379 Distributed...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online