Syntax Analysis Part VIII

Similar documents
Syntax Analysis Part IV

Lexical and Syntax Analysis

PRACTICAL CLASS: Flex & Bison

Lex & Yacc (GNU distribution - flex & bison) Jeonghwan Park

Introduction to Lex & Yacc. (flex & bison)

LECTURE 11. Semantic Analysis and Yacc

Introduction to Yacc. General Description Input file Output files Parsing conflicts Pseudovariables Examples. Principles of Compilers - 16/03/2006

flex is not a bad tool to use for doing modest text transformations and for programs that collect statistics on input.

Compiler Design 1. Yacc/Bison. Goutam Biswas. Lect 8

Marcello Bersani Ed. 22, via Golgi 42, 3 piano 3769

Chapter 3: Describing Syntax and Semantics. Introduction Formal methods of describing syntax (BNF)

Yacc. Generator of LALR(1) parsers. YACC = Yet Another Compiler Compiler symptom of two facts: Compiler. Compiler. Parser

Gechstudentszone.wordpress.com

An Introduction to LEX and YACC. SYSC Programming Languages

Principles of Programming Languages

TDDD55 - Compilers and Interpreters Lesson 3

COMPILERS AND INTERPRETERS Lesson 4 TDDD16

CSE302: Compiler Design

TDDD55- Compilers and Interpreters Lesson 2

As we have seen, token attribute values are supplied via yylval, as in. More on Yacc s value stack

Compiler Lab. Introduction to tools Lex and Yacc

Lex & Yacc. By H. Altay Güvenir. A compiler or an interpreter performs its task in 3 stages:

Lab 2. Lexing and Parsing with Flex and Bison - 2 labs

UNIT - 7 LEX AND YACC - 1

Lex & Yacc. by H. Altay Güvenir. A compiler or an interpreter performs its task in 3 stages:

Big Picture: Compilation Process. CSCI: 4500/6500 Programming Languages. Big Picture: Compilation Process. Big Picture: Compilation Process.

Table of Contents. Chapter 1. Introducing Flex and Bison

Gechstudentszone.wordpress.com

Chapter 4. Lexical analysis. Concepts. Lexical scanning Regular expressions DFAs and FSAs Lex. Lexical analysis in perspective

CSCI Compiler Design

COMPILER CONSTRUCTION LAB 2 THE SYMBOL TABLE. Tutorial 2 LABS. PHASES OF A COMPILER Source Program. Lab 2 Symbol table

Compiler construction in4020 lecture 5

Compiler Construction

Chapter 2 - Introduction to C Programming

Concepts. Lexical scanning Regular expressions DFAs and FSAs Lex. Lexical analysis in perspective

Lexical Analysis. Implementing Scanners & LEX: A Lexical Analyzer Tool

Compiler Construction

TDDD55- Compilers and Interpreters Lesson 3

Using an LALR(1) Parser Generator

Programming Languages (CS 550) Lecture 4 Summary Scanner and Parser Generators. Jeremy R. Johnson

Chapter 3 Lexical Analysis

C: How to Program. Week /Mar/05

Prof. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan

Parsing and Pattern Recognition

Compiler course. Chapter 3 Lexical Analysis

Compiler construction 2005 lecture 5

CS 403: Scanning and Parsing

CS143 Handout 04 Summer 2011 June 22, 2011 flex In A Nutshell

Compiler construction 2002 week 5

Big Picture: Compilation Process. CSCI: 4500/6500 Programming Languages. Big Picture: Compilation Process. Big Picture: Compilation Process

Compiler Construction. Lecture 10

8. Characters and Arrays

Flex and lexical analysis

The structure of a compiler

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

THE COMPILATION PROCESS EXAMPLE OF TOKENS AND ATTRIBUTES

CS 0449 Sample Midterm

Lexical and Syntax Analysis

Applications of Context-Free Grammars (CFG)

Syntax Directed Translation

Lecture 02 C FUNDAMENTALS

Etienne Bernard eb/textes/minimanlexyacc-english.html

CMSC445 Compiler design Blaheta. Project 2: Lexer. Due: 15 February 2012

CSC 467 Lecture 3: Regular Expressions

Software II: Principles of Programming Languages

Chapter 3 -- Scanner (Lexical Analyzer)

SOFTWARE Ph.D. Qualifying Exam Spring Consider the following C program which consists of two function definitions including the main function.

Group A Assignment 3(2)

Exercise 1 Codify in Yacc the generator of the abstract trees of the language defined by the following grammar:

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

Lesson 10. CDT301 Compiler Theory, Spring 2011 Teacher: Linus Källberg

LEX/Flex Scanner Generator

Parsing How parser works?

Conditional Statement

Lexical and Parser Tools

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Introduction to Compilers and Language Design

Syntax-Directed Translation

Scanning. COMP 520: Compiler Design (4 credits) Professor Laurie Hendren.

Introduction to C Programming

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

Exercise ANTLRv4. Patryk Kiepas. March 25, 2017

Scanning. COMP 520: Compiler Design (4 credits) Alexander Krolik MWF 13:30-14:30, MD 279

Module 8 - Lexical Analyzer Generator. 8.1 Need for a Tool. 8.2 Lexical Analyzer Generator Tool

Parsing. COMP 520: Compiler Design (4 credits) Professor Laurie Hendren.

HW8 Use Lex/Yacc to Turn this: Into this: Lex and Yacc. Lex / Yacc History. A Quick Tour. if myvar == 6.02e23**2 then f(..!

File IO and command line input CSE 2451

High Performance Programming Programming in C part 1

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

C LANGUAGE A Short Course

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

A Pragmatic Introduction to Abstract Language Analysis with Flex and Bison under Windows DRAFT

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Lex and Yacc. A Quick Tour

Operators and Expressions:

CS 2301 Exam 3 B-Term 2011

Linear Data Structure

Fundamental of Programming (C)

Type 3 languages. Regular grammars Finite automata. Regular expressions. Deterministic Nondeterministic. a, a, ε, E 1.E 2, E 1 E 2, E 1*, (E 1 )

Transcription:

Syntax Analysis Part VIII Exercises: Bison Text adapted from : Marinella Sciortino, Università di Palermo

Exercise I Write an interpreter for hand calculator with the following operators +, - (binary) *, / (binary, with precedence over +, -) (unary, absolute value) Use balanced parentheses to force precedence

Exercise I: Bison %{ #include <stdio.h> % %token NUMBER OP CP %token ADD SUB MUL DIV ABS %token EOL

Exercise I: Bison %% calclist: /* empty */ calclist exp EOL { printf("= %d\n", $2) Default action: copy $1 exp: factor exp ADD factor { $$ = $1 + $3 exp SUB factor { $$ = $1 - $3 factor: term factor MUL term { $$ = $1 * $3 factor DIV term { $$ = $1 / $3

Exercise I: Bison term: NUMBER ABS term { $$ = $2 >= 0? $2 : - $2 OP exp CP { $$ = $2 %% main(int argc, char **argv) { yyparse() yyerror(char *s) { fprintf(stderr, "error: %s\n", s)

Exercise I: Flex %option noyywrap %{ #include "calculator.tab.h" % %% "(" { return OP ")" { return CP "+" { return ADD "-" { return SUB "*" { return MUL "/" { return DIV " " { return ABS [0-9]+ { yylval = atoi(yytext) return NUMBER \n { return EOL [ \t] { /* ignore whitespace */. { printf("mystery character %c\n", *yytext) %%

Exercise II Write an interpreter that checks expressions of well-nested parentheses computes the number of parentheses in the expression

Exercise II: Bison %{ % #include <ctype.h> #include<stdio.h> %% lines : lines expr '\n' { printf("%d\n", $2) lines '\n' { printf("0\n") expr : '(' expr ')' { $$ = $2 + 2 '(' expr ')' expr { $$ = $2 + $4 + 2 '(' ')' { $$ = 2 '(' ')' expr { $$ = $3 + 2

Exercise II: Bison %% int yylex() { int c = getchar() return c int main() { if (yyparse()!= 0 ) fprintf(stderr, "Abnormal exit\n") return 0 int yyerror(char *s) { fprintf(stderr, "Error: %s\n", s)

Exercise III Write a parser accepting the language L = { a n b n c n n 1 L is not context-free: need to use semantic actions

Exercise III: Bison %{ % #include <stdio.h> int counta = 0, countb = 0, countc = 0 int yylex() void yyerror(char *s) void checkcounters()

Exercise III: Bison %% lines : lines S '\n' lines '\n' /* empty */ S : As Bs Cs {checkcounters() As : As 'a' {counta++ 'a' {counta++ Bs : Bs 'b' {countb++ 'b' {countb++ Cs : Cs 'c' {countc++ 'c' {countc++

Exercise III: Bison %% void checkcounters(){ if ((counta == countb) && (counta == countc)) printf("%s\n", "accept") else printf("%s\n", "reject" ) counta = 0 countb = 0 countc = 0 int yylex() { int c = getchar() return c

Exercise III: Bison int main() { if (yyparse()!= 0 ) fprintf(stderr, "Exit\n") return 0 void yyerror(char *s) { fprintf(stderr, "Error: %s\n", s)

Exercise IV Write a parser accepting the language MIX(3) = { w w {a, b, c *, # a (w) = # b (w) = # c (w) L is not context-free: need to use semantic actions

Exercise IV: Bison %{ #include <stdio.h> #include <ctype.h> int yylex() void yyerror(char const *) int counta, countb, countc, valid = 0 %

Exercise IV: Bison %% lines : lines S '\n { valid = (counta == countb && countb == countc)? 1 : 0 printf("the string %s to the language.\n\n, (valid == 1? "belongs" : "does not belong")) counta = countb = countc = 0 lines error '\n' { yyerrok /* empty */ S : 'a' S { counta++ 'b' S { countb++ 'c' S { countc++ /* empty */ {

Exercise IV: Bison %% int main() { if (yyparse()!= 0) { fprintf(stderr, "%s\n\n", "Abnormal exit.") return 0 int yylex() { return getchar() void yyerror(char const *s) { counta = countb = countc = 0 fprintf(stderr, "Error: %s.\n\n", s)

Exercise V Write an interpreter for micro-language with instructions : int id id = num id = id id = id + id print(id)

Exercise V identifiers use only alphabetic symbols each identifier must be uniquely defined and initialized to 0 numbers are unsigned integers print(id) prints the string "id : num"

Exercise V Example : int n int k n = 132 k = n k = k + n print(k) k : 264

Exercise V: Flex %option noyywrap %{ % #include <stdio.h> #include "parser.tab.h" WS [ \t\n] LETTER [A-Za-z] DIGIT [0-9] NZDIGIT [1-9] EQUAL "="

Exercise V: Flex %% print { return PRINT int { return INT {LETTER+ { yylval.identifier = strdup(yytext) return ID {NZDIGIT{DIGIT* { yylval.number = atoi( yytext ) return NUM {WS+ /* eat up whitespaces */ <<EOF>> { return ENDFILE. { return yytext[0]

Exercise V: Bison %{ #include <ctype.h> #include <stdio.h> #include "uthash.h" int yylex() void yyerror(char *s) /* base structure of a variable in the symbol table */ typedef struct variable { const char *id // hash key int value UT_hash_handle hh // makes structure hashable variable /* symbol table initialization */ variable *mysymboltable = NULL

Exercise V: Bison /* * add variable to symbol table */ void addvar(char *id){ variable *tmp HASH_FIND_STR(mySymbolTable, id, tmp) if (tmp == NULL){ tmp = (variable*) malloc(sizeof(variable)) tmp->id = id tmp->value = 0 HASH_ADD_KEYPTR(hh, mysymboltable, tmp->id, strlen(tmp->id), tmp) else { printf("error: multiple definition for variable %s\n", id) exit(-1)

Exercise V: Bison /* * update variable "id" in the symbol table */ void setvar(char *id, int value){ variable *tmp HASH_FIND_STR(mySymbolTable, id, tmp) if(tmp == NULL){ printf("error: variable %s is not defined\n", id) exit(-1) tmp->value = value

Exercise V: Bison % /* * read variable "id" in the symbol table */ int getvar(char *id){ variable *tmp HASH_FIND_STR(mySymbolTable, id, tmp) if(tmp == NULL){ printf("error: variable %s is not defined\n", id) exit(-1) return tmp->value

Exercise V: Bison %union { int number char* identifier %token %token %token %type <number> NUM <identifier> ID PRINT INT ENDFILE <number> expr

Exercise V: Bison %% program : program stmt ' stmt '' program ENDFILE { return 0 stmt : INT ID { addvar($2) ID '=' expr { setvar($1, $3) PRINT '(' ID ')' { printf("%s : %d\n", $3, getvar($3)) expr : ID '+' ID { getvar($1) + getvar($3) ID { $$ = getvar($1) NUM { $$ = $1

Exercise V: Bison %% int main() { if (yyparse()!= 0) fprintf(stderr, "Abnormal exit\n") return 0 void yyerror(char *s) { fprintf(stderr, "Error: %s\n", s)