Calculator 구현. Simple Calculator 문제 " 입력되는 수식의 값을 계산하는 lex 와 yacc 의 source 을 작성하시오 " – 허용하는 연산자 : + * - / ( ) – 우선순위 : ( ) > * / > + - – 결합순위 : 모두 좌측.

Slides:



Advertisements
Similar presentations
Arithmetic Calculations
Advertisements

Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 2 Simple C Programs.
Application: Yacc A parser generator A context-free grammar An LR parser Yacc Yacc input file:... definitions... %... production rules... %... user-defined.
Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.
Structure of a YACC File Has the same three-part structure as Lex Each part is separated by a % symbol The three parts are even identical: – definition.
Computer Programming w/ Eng. Applications
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Yacc YACC BNF grammar example.y Other modules example.tab.c Executable
176 Formal Languages and Applications: We know that Pascal programming language is defined in terms of a CFG. All the other programming languages are context-free.
Language processing: introduction to compiler construction Andy D. Pimentel Computer Systems Architecture group
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
1 Operators And Expressions. 2 Operators Arithmetic Operators Relational and Logical Operators Special Operators.
Parsning: Hvor er vi Mellem- kode Kald til Runtimesys. Mellemk.- optimering Kode- generering Kode- optimering Leksikalsk- analyse Syntax- analyse Semantik-
ICS 103 Lab 2-Arithmetic Expressions. Lab Objectives Learn different arithmetic operators Learn different arithmetic operators Learn how to use arithmetic.
1 YACC Yet Another Compiler Compiler. 2 Yacc is a parser generator: Input: A Grammar Output: A parser for the grammar (Reminder: a parser finds derivations)
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Parser construction tools: YACC
Syntax Analysis – Part II Quick Look at Using Bison Top-Down Parsers EECS 483 – Lecture 5 University of Michigan Wednesday, September 20, 2006.
Compilers: Yacc/7 1 Compiler Structures Objective – –describe yacc (actually bison) – –give simple examples of its use , Semester 1,
LEX and YACC work as a team
Introduction To Yacc and Semantics © Allan C. Milne Abertay University v
1 YACC Parser Generator. 2 YACC YACC (Yet Another Compiler Compiler) Produce a parser for a given grammar.  Compile a LALR(1) grammar Original written.
PL&C Lab, DongGuk University Compiler Lecture Note, MiscellaneousPage 1 Miscellaneous 컴파일러 입문.
YACC Example Taken from LEX & YACC Simple calculator a = a a=10 b = 7 c = a + b c c = 17 pressure = ( ) * 16.4 $
BASICS CONCEPTS OF ‘C’.  C Character Set C Character Set  Tokens in C Tokens in C  Constants Constants  Variables Variables  Global Variables Global.
Compiler Tools Lex/Yacc – Flex & Bison. Compiler Front End (from Engineering a Compiler) Scanner (Lexical Analyzer) Maps stream of characters into words.
Prof Busch - LSU1 YACC Yet Another Compiler Compiler.
–Writing a parser with YACC (Yet Another Compiler Compiler). Automatically generate a parser for a context free grammar (LALR parser) –Allows syntax direct.
Lex.
Introduction to YACC Panfeng Xue
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 5.3Math Library Functions Math library functions –perform.
1 Using Yacc. 2 Introduction Grammar –CFG –Recursive Rules Shift/Reduce Parsing –See Figure 3-2. –LALR(1) –What Yacc Cannot Parse It cannot deal with.
Syntactic Analysis Tools
Compiler Principle and Technology Prof. Dongming LU Mar. 26th, 2014.
YACC. Introduction What is YACC ? a tool for automatically generating a parser given a grammar written in a yacc specification (.y file) YACC (Yet Another.
Selection-making Decisions Selection allows you to choose between two or more possible program flow --- it lets you make decisions in your program. Examples.
ICS312 LEX Set 25. LEX Lex is a program that generates lexical analyzers Converting the source code into the symbols (tokens) is the work of the C program.
Applications of Context-Free Grammars (CFG) Parsers. The YACC Parser-Generator. by: Saleh Al-shomrani.
1 LEX & YACC Tutorial February 28, 2008 Tom St. John.
Writing Parsers with Ruby
1 Programming Languages (CS 550) Lecture 1 Summary Grammars and Parsing Jeremy R. Johnson.
PL&C Lab, DongGuk University Compiler Lecture Note, MiscellaneousPage 1 Yet Another Compiler-Compiler Stephen C. Johnson July 31, 1978 YACC.
Semantic Values and Symbol Tables © Allan C. Milne Abertay University v
LECTURE 11 Semantic Analysis and Yacc. REVIEW OF LAST LECTURE In the last lecture, we introduced the basic idea behind semantic analysis. Instead of merely.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
More yacc. What is yacc – Tool to produce a parser given a grammar – YACC (Yet Another Compiler Compiler) is a program designed to compile a LALR(1) grammar.
LEX Input file: Output file: Total=-636 %{ int total = 0; %} % [0-9]+ {printf("+"); REJECT;} [+/-]?[0-9]+ {ECHO;
Chapter INTRODUCTION Data Types and Arithmetic Calculations.
Week 4 – Functions Coding Functions. Purpose of Coding Functions A function is written to perform a well-defined task; rather than having all logic in.
YACC Primer CS 671 January 29, CS 671 – Spring Yacc Yet Another Compiler Compiler Automatically constructs an LALR(1) parsing table from.
YACC (Yet Another Compiler-Compiler) Chung-Ju Wu
1 Syntax Analysis Part III Chapter 4 COP5621 Compiler Construction Copyright Robert van Engelen, Florida State University,
1 Chapter 3 – Operators and Expressions Outline 3.1Introduction 3.2Arithmetic operators 3.3Relational operators 3.4Logical operators 3.5Assignment operators.
Syntax error handling –Errors can occur at many levels lexical: unknown operator syntactic: unbalanced parentheses semantic: variable never declared runtime:
Yacc.
Language processing: introduction to compiler construction
Control Statements in C
Variables Mr. Crone.
Operators And Expressions
Tutorial On Lex & Yacc.
TMF1414 Introduction to Programming
Bison: Parser Generator
CMPE 152: Compiler Design December 5 Class Meeting
CMSC 104, Section 4 Richard Chang
Syntax Analysis Part III
Govt. Polytechnic,Dhangar
Programming Language C Language.
Compiler Lecture Note, Miscellaneous
Compiler Structures 7. Yacc Objectives , Semester 2,
Compiler Design Yacc Example "Yet Another Compiler Compiler"
Presentation transcript:

Calculator 구현

Simple Calculator 문제 " 입력되는 수식의 값을 계산하는 lex 와 yacc 의 source 을 작성하시오 " – 허용하는 연산자 : + * - / ( ) – 우선순위 : ( ) > * / > + - – 결합순위 : 모두 좌측 결합 입력 예 (1+2+3)*(2*(51-47)/(1+2*3))

실습용 문법 덧셈과 곱셈 식을 생성하는 문법 Exp : Exp ‘+’ Term | Exp ‘-’ Term | Term Term : Term ‘*’ Fact | Term ‘/’ Fact | Fact Fact : ‘(’ Exp ‘)’ | NUMBER

Lex 입력 %{ #include "exp.tab.h" %} % [0-9]+{yylval = atoi(yytext);return(NUMBER);} [ \t]; \nreturn(0); \+return('+'); \*return('*');.{ printf("'%c': illegal character\n", yytext[0]); exit(-1); }

Yacc 입력 %{ int result; %} %token NUMBER % Exp : Exp '+' Term{ $$ = $1 + $3; result = $$;} | Term{ $$ = $1; } ; Term : Term '*' Num{ $$ = $1 * $3; } | Num{ $$ = $1; } ; Num : NUMBER{ $$ = $1; } ; % main() { yyparse(); printf("Result is %d\n", result); }

Calculator 의 확장 -1 To handle variables with single letter names To handle multiple expressions, one per line To use floating point values

사용 예 2/3 = a = 2/7 a = z = a + 1 a/z = $

Yacc 입력 - 1 %{ double vbltable[26]; %} %union { double dval; int vblno; } %token NAME %token NUMBER %left '-' '+' %left '*' '/' %nonassoc UMINUS %type expression %

Yacc 입력 - 2 statement_list: statement '\n' | statement_list statement '\n‘ ; statement: NAME '=' expression { vbltable[$1] = $3; } | expression { printf("= %g\n", $1); } ; expression: expression '+' expression { $$ = $1 + $3; } | expression '-' expression { $$ = $1 - $3; } | expression '*' expression { $$ = $1 * $3; } | expression '/' expression { if ( $3 == 0.0 ) yyerror("divide by zero"); else $$ = $1 / $3; } | '-' expression %prec UMINUS { $$ = -$2; } | '(' expression ')' { $$ = $2; } | NUMBER { $$ = $1; } | NAME { $$ = vbltable[$1]; } ;

Calculator 의 확장 -2 To allow longer variable names –Symbol table is needed to keep tracks of the name in use #define NSYMS 20 struct symtab { char *name; double value; } symtab[NSYMS]; struct symtab *symlook();

symlook() struct symtab *symlook(char *s) { char *p; struct symtab *sp; for(sp = symtab; sp < &symtab[NSYMS]; sp++) { if(sp->name && !strcmp(sp->name, s)) return sp; if(!sp->name) { sp->name = strdup(s); return sp; } yyerror("Too many symbols"); exit(1); }

Lex & Yacc 입력 Lex 입력 : 4.l Yacc 입력 : 4.y 심볼테이블 헤더 : 4hdr.h

Calculator 의 확장 -3 To allow mathematical functions –Square root, exponential, logarithm s2 = sqrt(2) s2 = s2*s2 =2

First approach %token SQRT LOG EXP... %... expression:... | SQRT '(' expression ')' { $$ = sqrt($3);} | LOG '(' expression ')' { $$ = log($3);} | EXP '(' expression ')' { $$ = exp($3);} In lex.... sqrt return SQRT; log return LOG; exp return EXP;...

Another approach Reserved words in the symbol table #define NSYMS 20 struct symtab { char *name; double (*funcptr)(); double value; } symtab[NSYMS]; struct symtab *symlook();

main() { extern double sqrt(), exp(), log(); addfunc("sqrt", sqrt); addfunc("exp", exp); addfunc("log", log); yyparse(); } addfunc(char *name, double (*func)()) { struct symtab *sp = symlook(name); sp->funcptr = func; }

Lex & Yacc 입력 Lex 입력 : 5.l Yacc 입력 : 5.y 심볼테이블 헤더 : 5hdr.h