Semantic Analysis. Leonidas Fegaras. CSE 5317/4305 L6: Semantic Analysis 1

Size: px
Start display at page:

Download "Semantic Analysis. Leonidas Fegaras. CSE 5317/4305 L6: Semantic Analysis 1"

Transcription

1 Semantic Analysis Leonidas Fegaras CSE 5317/4305 L6: Semantic Analysis 1

2 Type Checking source file get next character scanner get token token parser AST type checking AST symbol table type errors Checking whether the use of names is consistent with their declaration in the program int x; x := x+1; correct use of x x.a := 1; x[0] := 0; type errors Statically typed languages: done at compile time, not at run time Need to remember declarations Symbol Table CSE 5317/4305 L6: Semantic Analysis 2

3 Symbol Table A compile-time data structure used to map names into declarations It stores: for each type name, its type definition eg. for the C type declaration typedef int* mytype, it maps the name mytype to a data structure that represents the type int* for each variable name, its type if the variable is an array, it also stores dimension information it may also store storage class, offset in activation record, etc for each constant name, its type and value for each function and procedure, its formal parameter list and its output type each formal parameter must have name type type of passing (by-reference, by-value, etc) CSE 5317/4305 L6: Semantic Analysis 3

4 Symbol Table (cont.) Need to capture nested scopes, if necessary { int a; { int a; a = 1; ; a = 2; ; Interface: void insert ( String key, Object binding ) Object lookup ( String key ) begin_scope () end_scope () CSE 5317/4305 L6: Semantic Analysis 4

5 class SymbolCell { String Ast name; The Gen Symbol Table binding; SymbolCell next; SymbolCell ( String n, Ast v, SymbolCell r ) { name=n; binding=v; next=r; public class SymbolTable { final int symbol_table_size = 997; SymbolCell[] symbol_table = new SymbolCell[symbol_table_size]; final int scope_stack_length = 100; int scope_stack_top = 0; int[] scope_stack = new int[scope_stack_length]; public SymbolTable () { scope_stack_top = 0; CSE 5317/4305 L6: Semantic Analysis 5

6 The Gen Symbol Table (cont.) int hash ( String s ) { return Math.abs(s.hashCode()) % symbol_table_size; public void insert ( String key, Ast binding ) { int loc = hash(key); symbol_table[loc] = new SymbolCell(key,binding,symbol_table[loc]); if (scope_stack_top >= scope_stack_length) fatal_error("stack overflow",new Variable(key)); else scope_stack[scope_stack_top++] = loc; public Ast lookup ( String key ) { int loc = hash(key); for (SymbolCell s = symbol_table[loc]; s!= null; s=s.next) if (s.name.equals(key)) return s.binding; return null; CSE 5317/4305 L6: Semantic Analysis 6

7 The Gen Symbol Table (cont.) public void begin_scope () { if (scope_stack_top >= scope_stack_length) fatal_error("stack overflow",new Number(0)); else scope_stack[scope_stack_top++] = -1; public void end_scope () { int i = scope_stack_top-1; for (; scope_stack[i]>=0 && i>0; i--) { int loc = scope_stack[i]; symbol_table[loc] = symbol_table[loc].next; ; scope_stack_top = i; CSE 5317/4305 L6: Semantic Analysis 7

8 Example { ; int a; { int a; a = 1; ; a = 2; push(-1) insert the binding a:int at the front of table[12] list push(12) push(-1) insert the binding a:int at the front of table[12] list push(12) pop() remove the head of table[12] list pop() pop() remove the head of table[12] list pop() hash( a )=12 CSE 5317/4305 L6: Semantic Analysis 8

9 Type ASTs A typechecker is a function that maps an AST that represents an expression into its type Need to define the data structures for types: abstract class Type { class IntegerType extends Type { public IntegerType () { class BooleanType extends Type { public BooleanType () { class NamedType extends Type { public String name; public NamedType ( String n ) { value=n; class ArrayType extends Type { public Type element; public ArrayType ( Type et ) { element=et; CSE 5317/4305 L6: Semantic Analysis 9

10 Type ASTs (cont.) class RecordComponents { public String attribute; public Type type; public RecordComponents next; public RecordComponents ( String a, Type t, RecordComponents el ) { attribute=a; type=t; next=el; class RecordType extends Type { public RecordComponents elements; public RecordType ( RecordComponents el ) { elements=el; CSE 5317/4305 L6: Semantic Analysis 10

11 Declarations The symbol table must contain type declarations (ie. typedefs),variable declarations, constant declarations, and function signatures: class SymbolCell { String Declaration name; SymbolCell next; binding; SymbolCell ( String n, Declaration v, SymbolCell r ) { name=n; binding=v; next=r; Symbol[] symbol_table = new Symbol[SIZE]; CSE 5317/4305 L6: Semantic Analysis 11

12 Declarations (cont.) abstract class Declaration { class TypeDeclaration extends Declaration { public Type declaration; public TypeDeclaration ( Type t ) { declaration=t; class VariableDeclaration extends Declaration { public Type declaration; public VariableDeclaration ( Type t ) { declaration=t; class ConstantDeclaration extends Declaration { public Type declaration; public Exp value; public ConstantDeclaration ( Type t, Exp v ) { declaration=t; value=v; CSE 5317/4305 L6: Semantic Analysis 12

13 Declarations (cont.) class TypeList { public Type head; public TypeList next; public TypeList ( Type h, TypeList n ) { head=h; next=n; class FunctionDeclaration extends Declaration { public Type result; public TypeList parameters; public FunctionDeclaration ( Type t, TypeList tl ) { result=t; parameters=tl; CSE 5317/4305 L6: Semantic Analysis 13

14 Typechecking A tree traversals that checks each node of the AST tree recursively: static Type typecheck ( Exp e ) { if (e instanceof IntegerExp) return new IntegerType(); else if (e instanceof TrueExp) return new BooleanType(); else if (e instanceof FalseExp) return new BooleanType(); else if (e instanceof VariableExp) { VariableExp v = (VariableExp) e; Declaration decl = lookup(v.value); if (decl == null) error("undefined variable"); else if (decl instanceof VariableDeclaration) return ((VariableDeclaration) decl).declaration; else error("this name is not a variable name"); CSE 5317/4305 L6: Semantic Analysis 14

15 Typechecking: BinaryExp else if (e instanceof BinaryExp) { BinaryExp b = (BinaryExp) e; Type left = typecheck(b.left); Type right = typecheck(b.right); switch ( b.operator ) { case "+": if (left instanceof IntegerType && right instanceof IntegerType) return new IntegerType(); else error("expected integers in addition");... CSE 5317/4305 L6: Semantic Analysis 15

16 Typechecking: CallExp else if (e instanceof CallExp) { CallExp c = (CallExp) e; Declaration decl = lookup(c.name); if (decl == null) error("undefined function"); else if (!(decl instanceof FunctionDeclaration)) error("this name is not a function name"); FunctionDeclaration f = (FunctionDeclaration) decl; TypeList s = f.parameters; for (ExpList r=c.arguments; r!=null && s!=null; r=r.next, s=s.next) if (!equal_types(s.head,typecheck(r.head))) error("wrong type of the argument in function call") if (r!= null s!= null) error("wrong number of parameters"); return f.result; equal_types(x,y) checks the types x and y for equality Two types of type equality: type equality based on type name equivalence, or based on structural equivalence CSE 5317/4305 L6: Semantic Analysis 16

17 The Calculator Interpreter Evaluate an expression e using a symbol table st: static double eval ( Tree e, SymbolTable st ) { if (e instanceof LongLeaf) return (double) ((LongLeaf) e).value(); else if (e instanceof DoubleLeaf) return ((DoubleLeaf) e).value(); else if (e instanceof StringLeaf) return error("strings are not permitted",e); else if (e instanceof VariableLeaf) { Tree s = st.lookup(((variableleaf) e).value()); if (s == null) return error("undefined variable",e); else if (s instanceof DoubleLeaf) return ((DoubleLeaf) s).value(); else return error("name is not a variable",e); CSE 5317/4305 L6: Semantic Analysis 17

18 The Calculator Interpreter (cont.) else match e { case call_exp(`fnc,...args): double res; Tree s = st.lookup(((variableleaf) fnc).value()); if (s == null) return error("undefined function",fnc); match s { case fnc_def(`body,...params): Trees arguments = #[]; for ( Tree arg: args ) arguments = arguments.append(new DoubleLeaf(eval(arg,st))); if (params.length()!= arguments.length()) return error("wrong number of arguments",e); st.begin_scope(); for ( Tree param: params ) { st.insert(((variableleaf) param).value(),arguments.head()); arguments = arguments.tail(); ; res = eval(body); st.end_scope(); return res ; case _: return error("name has not been defined as a function",fnc); CSE 5317/4305 L6: Semantic Analysis 18

19 The Calculator Interpreter (cont.) case if_exp(`e1,`e2,`e3): if (eval(e1,st) > 0) return eval(e2,st); else return eval(e3,st); case `f(`e1,`e2): double left = eval(e1,st); double right = eval(e2,st); match new VariableLeaf(f) { case plus_exp: return left + right; case minus_exp: return left - right; case times_exp: return left * right; case div_exp: return left / right; case and_exp: return ((left>0) && (right>0))? 1 : 0; case or_exp: return ((left>0) (right>0))? 1 : 0; case eq_exp: return (left == right)? 1 : 0; case ne_exp: return (left!= right)? 1 : 0; case gt_exp: return (left > right)? 1 : 0; case lt_exp: return (left < right)? 1 : 0; case ge_exp: return (left >= right)? 1 : 0; case le_exp: return (left <= right)? 1 : 0; case _: return error("unrecognized expression",e); CSE 5317/4305 L6: Semantic Analysis 19

Semantic Analysis. Leonidas Fegaras. CSE 5317/4305 L6: Semantic Analysis 1

Semantic Analysis. Leonidas Fegaras. CSE 5317/4305 L6: Semantic Analysis 1 Semantic Analysis Leonidas Fegaras CSE 5317/4305 L6: Semantic Analysis 1 Type Checking source file get next character scanner get token token parser AST type checking AST symbol table type errors Checking

More information

Abstract Syntax. Leonidas Fegaras. CSE 5317/4305 L5: Abstract Syntax 1

Abstract Syntax. Leonidas Fegaras. CSE 5317/4305 L5: Abstract Syntax 1 Abstract Syntax Leonidas Fegaras CSE 5317/4305 L5: Abstract Syntax 1 Abstract Syntax Tree (AST) A parser typically generates an Abstract Syntax Tree (AST): source file get next character scanner get token

More information

CA Compiler Construction

CA Compiler Construction CA4003 - Compiler Construction Semantic Analysis David Sinclair Semantic Actions A compiler has to do more than just recognise if a sequence of characters forms a valid sentence in the language. It must

More information

Compilers CS S-05 Semantic Analysis

Compilers CS S-05 Semantic Analysis Compilers CS414-2003S-05 Semantic Analysis David Galles Department of Computer Science University of San Francisco 05-0: Syntax Errors/Semantic Errors A program has syntax errors if it cannot be generated

More information

Acknowledgement. CS Compiler Design. Semantic Processing. Alternatives for semantic processing. Intro to Semantic Analysis. V.

Acknowledgement. CS Compiler Design. Semantic Processing. Alternatives for semantic processing. Intro to Semantic Analysis. V. Acknowledgement CS3300 - Compiler Design Intro to Semantic Analysis V. Krishna Nandivada IIT Madras Copyright c 2000 by Antony L. Hosking. Permission to make digital or hard copies of part or all of this

More information

The compilation process is driven by the syntactic structure of the program as discovered by the parser

The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic Analysis The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic routines: interpret meaning of the program based on its syntactic structure

More information

Compilers Project 3: Semantic Analyzer

Compilers Project 3: Semantic Analyzer Compilers Project 3: Semantic Analyzer CSE 40243 Due April 11, 2006 Updated March 14, 2006 Overview Your compiler is halfway done. It now can both recognize individual elements of the language (scan) and

More information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Statically vs. Dynamically typed languages

More information

Project Compiler. CS031 TA Help Session November 28, 2011

Project Compiler. CS031 TA Help Session November 28, 2011 Project Compiler CS031 TA Help Session November 28, 2011 Motivation Generally, it s easier to program in higher-level languages than in assembly. Our goal is to automate the conversion from a higher-level

More information

CS453 CLASSES, VARIABLES, ASSIGNMENTS

CS453 CLASSES, VARIABLES, ASSIGNMENTS CS453 CLASSES, VARIABLES, ASSIGNMENTS CS453 Lecture Code Generation for Classes 1 PA6 new in MeggyJava member / instance variables local variables assignments let s go check out the new MeggyJava grammar

More information

Semantic analysis. Semantic analysis. What we ll cover. Type checking. Symbol tables. Symbol table entries

Semantic analysis. Semantic analysis. What we ll cover. Type checking. Symbol tables. Symbol table entries Susan Eggers 1 CSE 401 Semantic analysis Semantic analysis Final part of analysis half of compilation lexical analysis syntactic analysis semantic analysis Afterwards comes synthesis half of compilation

More information

The role of semantic analysis in a compiler

The role of semantic analysis in a compiler Semantic Analysis Outline The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

Compiler Theory. (Semantic Analysis and Run-Time Environments)

Compiler Theory. (Semantic Analysis and Run-Time Environments) Compiler Theory (Semantic Analysis and Run-Time Environments) 005 Semantic Actions A compiler must do more than recognise whether a sentence belongs to the language of a grammar it must do something useful

More information

CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages 1 / 26 CSE 307: Principles of Programming Languages Names, Scopes, and Bindings R. Sekar 2 / 26 Topics Bindings 1. Bindings Bindings: Names and Attributes Names are a fundamental abstraction in languages

More information

CSE P 501 Compilers. Static Semantics Hal Perkins Winter /22/ Hal Perkins & UW CSE I-1

CSE P 501 Compilers. Static Semantics Hal Perkins Winter /22/ Hal Perkins & UW CSE I-1 CSE P 501 Compilers Static Semantics Hal Perkins Winter 2008 1/22/2008 2002-08 Hal Perkins & UW CSE I-1 Agenda Static semantics Types Attribute grammars Representing types Symbol tables Note: this covers

More information

Lecture 8 CS 412/413 Spring '00 -- Andrew Myers 2. Lecture 8 CS 412/413 Spring '00 -- Andrew Myers 4

Lecture 8 CS 412/413 Spring '00 -- Andrew Myers 2. Lecture 8 CS 412/413 Spring '00 -- Andrew Myers 4 CS412/413 Introduction to Compilers and Translators Spring 00 Outline Typechecking Symbol tables Using symbol tables for analysis Lecture 8: Semantic Analysis and Symbol Tables Lecture 8 CS 412/413 Spring

More information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

CS S-06 Semantic Analysis 1

CS S-06 Semantic Analysis 1 CS414-2017S-06 Semantic Analysis 1 06-0: Syntax Errors/Semantic Errors A program has syntax errors if it cannot be generated from the Context Free Grammar which describes the language The following code

More information

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis? Anatomy of a Compiler Program (character stream) Lexical Analyzer (Scanner) Syntax Analyzer (Parser) Semantic Analysis Parse Tree Intermediate Code Generator Intermediate Code Optimizer Code Generator

More information

The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis

The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis The Compiler So Far Overview of Semantic Analysis Adapted from Lectures by Profs. Alex Aiken and George Necula (UCB) Lexical analysis Detects inputs with illegal tokens Parsing Detects inputs with ill-formed

More information

Semantic Analysis and Type Checking

Semantic Analysis and Type Checking Semantic Analysis and Type Checking The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic routines: interpret meaning of the program based on

More information

SEMANTIC ANALYSIS TYPES AND DECLARATIONS

SEMANTIC ANALYSIS TYPES AND DECLARATIONS SEMANTIC ANALYSIS CS 403: Type Checking Stefan D. Bruda Winter 2015 Parsing only verifies that the program consists of tokens arranged in a syntactically valid combination now we move to check whether

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

Operational Semantics of Cool

Operational Semantics of Cool Operational Semantics of Cool Key Concepts semantics: the meaning of a program, what does program do? how the code is executed? operational semantics: high level code generation steps of calculating values

More information

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer. The Compiler So Far CSC 4181 Compiler Construction Scanner - Lexical analysis Detects inputs with illegal tokens e.g.: main 5 (); Parser - Syntactic analysis Detects inputs with ill-formed parse trees

More information

Implementing Classes and Assignments

Implementing Classes and Assignments Implementing Classes and Assignments Logistics Quiz 5 has been posted PA5 Overview today, will be posted Monday night, Due May 4 th HW4 will also be posted Monday night, Due April 27 th Will talk about

More information

UNIT-4 (COMPILER DESIGN)

UNIT-4 (COMPILER DESIGN) UNIT-4 (COMPILER DESIGN) An important part of any compiler is the construction and maintenance of a dictionary containing names and their associated values, such type of dictionary is called a symbol table.

More information

CSCI565 Compiler Design

CSCI565 Compiler Design CSCI565 Compiler Design Fall 2015 Homework 2 - Solution Problem 1: Attributive Grammar and Syntax-Directed Translation [30 points] In this problem you ned to develop a grammar for array variable expressions

More information

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics Recall Architecture of Compilers, Interpreters CMSC 330: Organization of Programming Languages Source Scanner Parser Static Analyzer Operational Semantics Intermediate Representation Front End Back End

More information

Symbol Tables COMP 520: Compiler Design (4 credits) Professor Laurie Hendren

Symbol Tables COMP 520: Compiler Design (4 credits) Professor Laurie Hendren COMP 520 Winter 2016 Symbol tables (1) Symbol Tables COMP 520: Compiler Design (4 credits) Professor Laurie Hendren hendren@cs.mcgill.ca WendyTheWhitespace-IntolerantDragon WendyTheWhitespacenogarDtnarelotnI

More information

Connecting Definition and Use? Tiger Semantic Analysis. Symbol Tables. Symbol Tables (cont d)

Connecting Definition and Use? Tiger Semantic Analysis. Symbol Tables. Symbol Tables (cont d) Tiger source program Tiger Semantic Analysis lexical analyzer report all lexical errors token get next token parser construct variable deinitions to their uses report all syntactic errors absyn checks

More information

Computer Programming: C++

Computer Programming: C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming: C++ Experiment #7 Arrays Part II Passing Array to a Function

More information

Compiler construction

Compiler construction Compiler construction Martin Steffen March 13, 2017 Contents 1 Abstract 1 1.1 Symbol tables. 1 1.1.1 Introduction 1 1.1.2 Symbol table design and interface.. 2 1.1.3 Implementing symbol tables 3 1.1.4

More information

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Lecture 13. Notation. The rules. Evaluation Rules So Far

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Lecture 13. Notation. The rules. Evaluation Rules So Far Lecture Outline Operational Semantics of Cool Lecture 13 COOL operational semantics Motivation Notation The rules Prof. Aiken CS 143 Lecture 13 1 Prof. Aiken CS 143 Lecture 13 2 Motivation We must specify

More information

Semantic actions for declarations and expressions

Semantic actions for declarations and expressions Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate

More information

Event Type Polymorphism

Event Type Polymorphism Event Type Polymorphism Rex D. Fernando Robert Dyer Hridesh Rajan Department of Computer Science Iowa State University {fernanre,rdyer,hridesh}@iastate.edu This work was supported in part by NSF grant

More information

Mid-Term 2 Grades

Mid-Term 2 Grades Mid-Term 2 Grades 100 46 1 HW 9 Homework 9, in untyped class interpreter: Add instanceof Restrict field access to local class Implement overloading (based on argument count) Due date is the same as for

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Semantic actions for declarations and expressions. Monday, September 28, 15

Semantic actions for declarations and expressions. Monday, September 28, 15 Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate

More information

RYERSON POLYTECHNIC UNIVERSITY DEPARTMENT OF MATH, PHYSICS, AND COMPUTER SCIENCE CPS 710 FINAL EXAM FALL 96 INSTRUCTIONS

RYERSON POLYTECHNIC UNIVERSITY DEPARTMENT OF MATH, PHYSICS, AND COMPUTER SCIENCE CPS 710 FINAL EXAM FALL 96 INSTRUCTIONS RYERSON POLYTECHNIC UNIVERSITY DEPARTMENT OF MATH, PHYSICS, AND COMPUTER SCIENCE CPS 710 FINAL EXAM FALL 96 STUDENT ID: INSTRUCTIONS Please write your student ID on this page. Do not write it or your name

More information

Test I Solutions MASSACHUSETTS INSTITUTE OF TECHNOLOGY Spring Department of Electrical Engineering and Computer Science

Test I Solutions MASSACHUSETTS INSTITUTE OF TECHNOLOGY Spring Department of Electrical Engineering and Computer Science Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY 6.035 Spring 2013 Test I Solutions Mean 83 Median 87 Std. dev 13.8203 14 12 10 8 6 4 2 0 0 10 20 30 40 50

More information

Operational Semantics. One-Slide Summary. Lecture Outline

Operational Semantics. One-Slide Summary. Lecture Outline Operational Semantics #1 One-Slide Summary Operational semantics are a precise way of specifying how to evaluate a program. A formal semantics tells you what each expression means. Meaning depends on context:

More information

Semantic Analysis Wilhelm/Seidl/Hack: Compiler Design Syntactic and Semantic Analysis, Chapter 4

Semantic Analysis Wilhelm/Seidl/Hack: Compiler Design Syntactic and Semantic Analysis, Chapter 4 Semantic Analysis Wilhelm/Seidl/Hack: Compiler Design Syntactic and Semantic Analysis, Chapter 4 Reinhard Wilhelm Universität des Saarlandes wilhelm@cs.uni-sb.de Standard Structure source(text) lexical

More information

Semantic Analysis. Compiler Architecture

Semantic Analysis. Compiler Architecture Processing Systems Prof. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan Source Compiler Architecture Front End Scanner (lexical tokens Parser (syntax Parse tree Semantic Analysis

More information

Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413

Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 13: Types and Type-Checking 19 Feb 07 Semantic Analysis Last time: Semantic errors related to scopes Symbol tables Name resolution This lecture:

More information

Semantic analysis and intermediate representations. Which methods / formalisms are used in the various phases during the analysis?

Semantic analysis and intermediate representations. Which methods / formalisms are used in the various phases during the analysis? Semantic analysis and intermediate representations Which methods / formalisms are used in the various phases during the analysis? The task of this phase is to check the "static semantics" and generate

More information

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1 CSE P 501 Compilers Implementing ASTs (in Java) Hal Perkins Autumn 2009 10/20/2009 2002-09 Hal Perkins & UW CSE H-1 Agenda Representing ASTs as Java objects Parser actions Operations on ASTs Modularity

More information

Today's Topics. CISC 458 Winter J.R. Cordy

Today's Topics. CISC 458 Winter J.R. Cordy Today's Topics Last Time Semantics - the meaning of program structures Stack model of expression evaluation, the Expression Stack (ES) Stack model of automatic storage, the Run Stack (RS) Today Managing

More information

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

Prof. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan Language Processing Systems Prof. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan Semantic Analysis Compiler Architecture Front End Back End Source language Scanner (lexical analysis)

More information

The Abstract Syntax Tree Differences Between Tolmach's and Porter's Representations

The Abstract Syntax Tree Differences Between Tolmach's and Porter's Representations The Abstract Syntax Tree Differences Between Tolmach's and Porter's Representations Harry Porter January 21, 2006 Introduction This document discusses the Abstract Syntax Tree (AST) representation used

More information

CSE 401 Midterm Exam Sample Solution 11/4/11

CSE 401 Midterm Exam Sample Solution 11/4/11 Question 1. (12 points, 2 each) The front end of a compiler consists of three parts: scanner, parser, and (static) semantics. Collectively these need to analyze the input program and decide if it is correctly

More information

Chapter 4. Abstract Syntax

Chapter 4. Abstract Syntax Chapter 4 Abstract Syntax Outline compiler must do more than recognize whether a sentence belongs to the language of a grammar it must do something useful with that sentence. The semantic actions of a

More information

Symbol Tables (1) COMP 520: Compiler Design (4 credits) Alexander Krolik MWF 13:30-14:30, MD 279

Symbol Tables (1) COMP 520: Compiler Design (4 credits) Alexander Krolik MWF 13:30-14:30, MD 279 COMP 520 Winter 2017 Symbol Tables COMP 520: Compiler Design (4 credits) Alexander Krolik alexander.krolik@mail.mcgill.ca MWF 13:30-14:30, MD 279 Symbol Tables (1) COMP 520 Winter 2017 Symbol Tables (2)

More information

5. Semantic Analysis!

5. Semantic Analysis! 5. Semantic Analysis! Prof. O. Nierstrasz! Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes.! http://www.cs.ucla.edu/~palsberg/! http://www.cs.purdue.edu/homes/hosking/!

More information

Visitors. Move functionality

Visitors. Move functionality Visitors Compiler Construction Visitor pattern, Semantic analysis Lennart Andersson How to modularize in Java (or any other OO language) if we do not have access to AOP mechanisms? Revision 2011-02-08

More information

CPS2000 Compiler Theory & Practice

CPS2000 Compiler Theory & Practice CPS2000 Compiler Theory & Practice Notes on Handcrafting a Parser Gordon Mangion Source File Compiler Lexical Analyser Keyword Table Abstract Syntax Tree Parser Symbol Table? Error Module? Abstract Syntax

More information

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Winter /22/ Hal Perkins & UW CSE H-1

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Winter /22/ Hal Perkins & UW CSE H-1 CSE P 501 Compilers Implementing ASTs (in Java) Hal Perkins Winter 2008 1/22/2008 2002-08 Hal Perkins & UW CSE H-1 Agenda Representing ASTs as Java objects Parser actions Operations on ASTs Modularity

More information

Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1

Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1 Static Semantics Lecture 15 (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1 Current Status Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing

More information

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

Prof. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan Language Processing Systems Prof. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan Semantic Analysis Compiler Architecture Front End Back End Source language Scanner (lexical analysis)

More information

Programming Languages Third Edition. Chapter 7 Basic Semantics

Programming Languages Third Edition. Chapter 7 Basic Semantics Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol

More information

Informal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility

Informal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility Informal Semantics of Data semantic specification names (identifiers) attributes binding declarations scope rules visibility 1 Ways to Specify Semantics Standards Documents (Language Definition) Language

More information

Lecture 16: Static Semantics Overview 1

Lecture 16: Static Semantics Overview 1 Lecture 16: Static Semantics Overview 1 Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces trees Detects & eliminates ill-formed parse trees Static semantic analysis

More information

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Notation. The rules. Evaluation Rules So Far.

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Notation. The rules. Evaluation Rules So Far. Lecture Outline Operational Semantics of Cool COOL operational semantics Motivation Adapted from Lectures by Profs. Alex Aiken and George Necula (UCB) Notation The rules CS781(Prasad) L24CG 1 CS781(Prasad)

More information

Parsing Scheme (+ (* 2 3) 1) * 1

Parsing Scheme (+ (* 2 3) 1) * 1 Parsing Scheme + (+ (* 2 3) 1) * 1 2 3 Compiling Scheme frame + frame halt * 1 3 2 3 2 refer 1 apply * refer apply + Compiling Scheme make-return START make-test make-close make-assign make- pair? yes

More information

Implementing Classes, Arrays, and Assignments

Implementing Classes, Arrays, and Assignments Implementing Classes, Arrays, and Assignments Logistics PA4 peer reviews are due Saturday HW9 is due Monday PA5 is due December 5th Will talk about monad implementation at some point, until then check

More information

Type Inference Systems. Type Judgments. Deriving a Type Judgment. Deriving a Judgment. Hypothetical Type Judgments CS412/CS413

Type Inference Systems. Type Judgments. Deriving a Type Judgment. Deriving a Judgment. Hypothetical Type Judgments CS412/CS413 Type Inference Systems CS412/CS413 Introduction to Compilers Tim Teitelbaum Type inference systems define types for all legal programs in a language Type inference systems are to type-checking: As regular

More information

5. Semantic Analysis. Mircea Lungu Oscar Nierstrasz

5. Semantic Analysis. Mircea Lungu Oscar Nierstrasz 5. Semantic Analysis Mircea Lungu Oscar Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes. http://www.cs.ucla.edu/~palsberg/

More information

LECTURE 3. Compiler Phases

LECTURE 3. Compiler Phases LECTURE 3 Compiler Phases COMPILER PHASES Compilation of a program proceeds through a fixed series of phases. Each phase uses an (intermediate) form of the program produced by an earlier phase. Subsequent

More information

CSE 341 Section 7. Eric Mullen Spring Adapted from slides by Nicholas Shahan, Dan Grossman, and Tam Dang

CSE 341 Section 7. Eric Mullen Spring Adapted from slides by Nicholas Shahan, Dan Grossman, and Tam Dang CSE 341 Section 7 Eric Mullen Spring 2017 Adapted from slides by Nicholas Shahan, Dan Grossman, and Tam Dang Outline Interpreting LBI (Language Being Implemented) Assume Correct Syntax Check for Correct

More information

SYMBOL TABLE CHAPTER CHAPTER HIGHLIGHTS. 9.1 Operation on Symbol Table. 9.2 Symbol Table Implementation. 9.3 Data Structure for Symbol Table

SYMBOL TABLE CHAPTER CHAPTER HIGHLIGHTS. 9.1 Operation on Symbol Table. 9.2 Symbol Table Implementation. 9.3 Data Structure for Symbol Table CHAPTER 9 SYMBOL TABLE CHAPTER HIGHLIGHTS 9.1 Operation on Symbol Table 9.2 Symbol Table Implementation 9.3 Data Structure for Symbol Table 9.3.1 List 9.3.2 Self Organizing List 9.3.3 Hash Table 9.3.4

More information

Racket: Modules, Contracts, Languages

Racket: Modules, Contracts, Languages Racket: Modules, Contracts, Languages Advanced Functional Programming Jean-Noël Monette November 2013 1 Today Modules are the way to structure larger programs in smaller pieces. Modules can import and

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

Functions and Recursion. Dr. Philip Cannata 1

Functions and Recursion. Dr. Philip Cannata 1 Functions and Recursion Dr. Philip Cannata 1 10 High Level Languages This Course Java (Object Oriented) Jython in Java Relation ASP RDF (Horn Clause Deduction, Semantic Web) Dr. Philip Cannata 2 let transformation,

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator

More information

Static Semantics. Winter /3/ Hal Perkins & UW CSE I-1

Static Semantics. Winter /3/ Hal Perkins & UW CSE I-1 CSE 401 Compilers Static Semantics Hal Perkins Winter 2009 2/3/2009 2002-09 Hal Perkins & UW CSE I-1 Agenda Static semantics Types Symbol tables General ideas for now; details later for MiniJava project

More information

More On Syntax Directed Translation

More On Syntax Directed Translation More On Syntax Directed Translation 1 Types of Attributes We have productions of the form: A X 1 X 2 X 3... X n with semantic rules of the form: b:= f(c 1, c 2, c 3,..., c n ) where b and the c s are attributes

More information

Overview of Assignment 5

Overview of Assignment 5 Overview of Assignment 5 Study AST for MiniJava Add to JavaCC parser semantic actions to create AST Understand visitor pattern Design symbol table Code visiter to create symbol table Code visitor to perform

More information

An Overview of Compilation

An Overview of Compilation An Overview of Compilation (www.cse.iitb.ac.in/ uday) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay January 2014 cs306 Compilation Overview: Outline 1/18 Outline

More information

Lecture 12: Conditional Expressions and Local Binding

Lecture 12: Conditional Expressions and Local Binding Lecture 12: Conditional Expressions and Local Binding Introduction Corresponds to EOPL 3.3-3.4 Please review Version-1 interpreter to make sure that you understand how it works Now we will extend the basic

More information

Recap: Functions as first-class values

Recap: Functions as first-class values Recap: Functions as first-class values Arguments, return values, bindings What are the benefits? Parameterized, similar functions (e.g. Testers) Creating, (Returning) Functions Iterator, Accumul, Reuse

More information

COP4020 Programming Assignment 2 - Fall 2016

COP4020 Programming Assignment 2 - Fall 2016 COP4020 Programming Assignment 2 - Fall 2016 To goal of this project is to implement in C or C++ (your choice) an interpreter that evaluates arithmetic expressions with variables in local scopes. The local

More information

Homework #3: CMPT-379

Homework #3: CMPT-379 Only submit answers for questions marked with. Homework #3: CMPT-379 Download the files for this homework: wget http://www.cs.sfu.ca/ msiahban/personal/teaching/cmpt-379-spring-2016/hw3.tgz Put your solution

More information

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University Lecture 7: Type Systems and Symbol Tables CS 540 George Mason University Static Analysis Compilers examine code to find semantic problems. Easy: undeclared variables, tag matching Difficult: preventing

More information

Lecture 20 Sections Wed, Apr 1, 2009

Lecture 20 Sections Wed, Apr 1, 2009 s Return End Call s Lecture 20 Sections 7.1-7.5 Hampden-Sydney College Wed, Apr 1, 2009 Outline s Return 1 s Return End End Call s 2 Call s 3 s Return End Call s To write the assembly code for the beginning

More information

Chapter 10. Implementing Subprograms ISBN

Chapter 10. Implementing Subprograms ISBN Chapter 10 Implementing Subprograms ISBN 0-321-33025-0 Chapter 10 Topics The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing Subprograms with Stack-Dynamic Local Variables

More information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

A Simple Syntax-Directed Translator

A Simple Syntax-Directed Translator Chapter 2 A Simple Syntax-Directed Translator 1-1 Introduction The analysis phase of a compiler breaks up a source program into constituent pieces and produces an internal representation for it, called

More information

Project 2: Scheme Interpreter

Project 2: Scheme Interpreter Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same

More information

Implementing Subprograms

Implementing Subprograms 1 Implementing Subprograms CS 315 Programming Languages Pinar Duygulu Bilkent University CS315 Programming Languages Pinar Duygulu The General Semantics of Calls and Returns 2 The subprogram call and return

More information

Compilers. Type checking. Yannis Smaragdakis, U. Athens (original slides by Sam

Compilers. Type checking. Yannis Smaragdakis, U. Athens (original slides by Sam Compilers Type checking Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Summary of parsing Parsing A solid foundation: context-free grammars A simple parser: LL(1) A more powerful parser:

More information

Semantic Analysis. Lecture 9. February 7, 2018

Semantic Analysis. Lecture 9. February 7, 2018 Semantic Analysis Lecture 9 February 7, 2018 Midterm 1 Compiler Stages 12 / 14 COOL Programming 10 / 12 Regular Languages 26 / 30 Context-free Languages 17 / 21 Parsing 20 / 23 Extra Credit 4 / 6 Average

More information

Intermediate Formats. for object oriented languages

Intermediate Formats. for object oriented languages Intermediate Formats for object oriented languages Program Representation Goals Enable Program Analysis and Transformation Semantic Checks, Correctness Checks, Optimizations Structure Translation to Machine

More information

Variables and Bindings

Variables and Bindings Net: Variables Variables and Bindings Q: How to use variables in ML? Q: How to assign to a variable? # let = 2+2;; val : int = 4 let = e;; Bind the value of epression e to the variable Variables and Bindings

More information

Parsing #1. Leonidas Fegaras. CSE 5317/4305 L3: Parsing #1 1

Parsing #1. Leonidas Fegaras. CSE 5317/4305 L3: Parsing #1 1 Parsing #1 Leonidas Fegaras CSE 5317/4305 L3: Parsing #1 1 Parser source file get next character scanner get token parser AST token A parser recognizes sequences of tokens according to some grammar and

More information

The basic operations defined on a symbol table include: free to remove all entries and free the storage of a symbol table

The basic operations defined on a symbol table include: free to remove all entries and free the storage of a symbol table SYMBOL TABLE: A symbol table is a data structure used by a language translator such as a compiler or interpreter, where each identifier in a program's source code is associated with information relating

More information

Lecture 11: Subprograms & their implementation. Subprograms. Parameters

Lecture 11: Subprograms & their implementation. Subprograms. Parameters Lecture 11: Subprograms & their implementation Subprograms Parameter passing Activation records The run-time stack Implementation of static and dynamic scope rules Subprograms A subprogram is a piece of

More information

CS453 Visitor patterns Type checking and Code Generation

CS453 Visitor patterns Type checking and Code Generation CS453 Visitor patterns Type checking and Code Generation Plan for Today Using visitor design pattern for PA3 Type checking for PA3 Code generation for PA3 CS453 Lecture Building ASTs and Visitor Design

More information

(Not Quite) Minijava

(Not Quite) Minijava (Not Quite) Minijava CMCS22620, Spring 2004 April 5, 2004 1 Syntax program mainclass classdecl mainclass class identifier { public static void main ( String [] identifier ) block } classdecl class identifier

More information

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)

More information