Homework 3 Semantic Analysis. Remi Meier Compiler Design

Similar documents
Homework 1 Simple code genera/on. Luca Della Toffola Compiler Design HS15

A Short Summary of Javali

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

CSCE 314 Programming Languages. Type System

Semantic Analysis. Compiler Architecture

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

Introduction to Programming Using Java (98-388)

Project Compiler. CS031 TA Help Session November 28, 2011

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

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING

CMSC 330: Organization of Programming Languages

Syntax Errors; Static Semantics

CS 406: Syntax Directed Translation

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

Program Representations

Semantic Analysis and Type Checking

Linked List Nodes (reminder)

An Activation Record for Simple Subprograms. Activation Record for a Language with Stack-Dynamic Local Variables

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

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

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Semantic Processing. Semantic Errors. Semantics - Part 1. Semantics - Part 1

What are the characteristics of Object Oriented programming language?

» Access elements of a container sequentially without exposing the underlying representation

Programming Assignment 5 Interpreter and Static Analysis

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

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

SDC Design patterns GoF

Intermediate Code Generation

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

Project 5 Due 11:59:59pm Wed, Nov 25, 2015 (no late submissions)

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

SEMANTIC ANALYSIS TYPES AND DECLARATIONS

Semantic Analysis. Lecture 9. February 7, 2018

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

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

Lecture08: Scope and Lexical Address

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

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

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

IBS Software Services Technical Interview Questions. Q1. What is the difference between declaration and definition?

CSE302: Compiler Design

Decaf Language Reference Manual

Introduce C# as Object Oriented programming language. Explain, tokens,

COMP 181 Compilers. Administrative. Last time. Prelude. Compilation strategy. Translation strategy. Lecture 2 Overview

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CMPT 379 Compilers. Parse trees

2.4 Structuring programs

Interruptible Iterators

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

Intermediate Formats. for object oriented languages

CSE 307: Principles of Programming Languages

Typescript on LLVM Language Reference Manual

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

LECTURE 3. Compiler Phases

Absolute C++ Walter Savitch

5. Semantic Analysis!

Lecture 14 Sections Mon, Mar 2, 2009

JAVA OBJECT-ORIENTED PROGRAMMING

A Tour of the Cool Support Code

Intermediate Formats. for object oriented languages

Compiler construction

Produced by. Design Patterns. MSc in Communications Software. Eamonn de Leastar

The role of semantic analysis in a compiler

Compiling and Interpreting Programming. Overview of Compilers and Interpreters

Project 5 Due 11:59:59pm Tuesday, April 25, 2017

Array. Prepared By - Rifat Shahriyar

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

CPS2000 Compiler Theory & Practice

Implementing Subprograms

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

5. Semantic Analysis. Mircea Lungu Oscar Nierstrasz

COP4020 Programming Languages. Compilers and Interpreters Robert van Engelen & Chris Lacher

CIS 341 Final Examination 4 May 2017

Java Exceptions Java, winter semester

Programming for the Web with PHP

Chapter 1 Getting Started

Short Notes of CS201

JavaCC Parser. The Compilation Task. Automated? JavaCC Parser

Java: introduction to object-oriented features

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

Java Review: Objects

Relation Overriding. Syntax and Semantics. Simple Semantic Domains. Operational Semantics

Declarations and Access Control SCJP tips

AspectC++ A Language Overview

CS201 - Introduction to Programming Glossary By

CS453 Compiler Construction

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

The SPL Programming Language Reference Manual

OBJECT ORIENTED DATA STRUCTURE & ALGORITHMS

Decaf Language Reference

Type Checking. Outline. General properties of type systems. Types in programming languages. Notation for type rules.

Object-Oriented Design

Visitors. Move functionality

Intermediate Formats. Martin Rinard Laboratory for Computer Science

Transcription:

Homework 3 Semantic Analysis Remi Meier Compiler Design 28.10.2015 1

Compiler phases Javali Compiler x86 Assembly IR IR Front-end Optimizations Back-end Machine independent Machine dependent Lexical Analysis Syntactic Analysis AST Semantic Analysis 2

Homework 3 Class class Main { void main() { write(true); writeln(); Text HW 2 Write Method Seq WriteLn HW 3 ERROR BoolConst Abstract Syntax Tree How do we check a program for mistakes that are difficult / impossible to catch with grammar rules?

Semantic Analysis Text Lexer Parser AST syntactically correct Semantic Analysis AST enriched, correct Input Syntactically well-formed AST Output Enriched AST with types and other semantic information Warnings: warn programmer about possible mistakes Error messages: ensure correctness for later compiler stages Two parts: 1) Collect information (enrich AST) 2) Check for correctness of the AST 4

What information? We use the following terms: Names are words in the program text Symbols are semantic entities storing information about names class Main { int foo; int main() { int bar; write(bar); Main int foo int main int bar write bar field foo in of class Main type int of var bar inherits in returns in class Object method main 5

Symbol table Keep information about symbols in symbol table: mapping: name symbol central repository of information hierarchical structure through lexical scoping Lexical scoping: class A { void main() { class B extends A { Javali scopes: Global: all class symbols, built-in types Class: members and super-class members Method: parameters and local variables 6

Scoping rules class A { void main() { Javali scopes: global, class, method class B extends A { Rules: within a scope: symbols have unique names inner scopes hide symbols of outer scopes But: separate namespace for types separate namespace for methods 7

Scoping rules: example class foo { foo foo; void foo() { int foo; void bar() { class bar extends foo { foo foo; void bar() { foo(); bar(); Types / Classes separate namespace e.g.: int, class foo, class bar (Inherited) Methods separate namespace can be overridden through inheritance e.g.: bar() (Inherited) Fields same namespace as local variables and parameters can be hidden by local variable / parameter e.g.: foo.foo can be shadowed through inheritance e.g.: bar.foo 8

Implementation Symbol VariableSymbol Param, Local, Field MethodSymbol Method declarations TypeSymbol PrimitiveTypeSymbol int, boolean, void ArrayTypeSymbol Foo[] ClassSymbol Class declarations Hints: Create symbols for every: class, method, parameter, local variable, array type, field, Object, null, and primitive types Enrich AST with symbols 9

Implementation No need for a single symbol table link tables to reflect scopes: e.g., a symbol table per method symbol collect as much information as you need in whatever way you want Use visitors to collect information to check for correctness second step 10

Check for correctness Look at list of checks in homework description throw SemanticFailure on detected error class Test { void m() { write(1); class A extends B { class B extends A { INVALID_START_POINT: no Main or main() CIRCULAR_INHERITANCE class Main { void main() { int a, a; DOUBLE_DECLARATION 11

Check for correctness int m() { if (true) { return 0; void m() { int a; boolean b; a = a + b; MISSING_RETURN TYPE_ERROR 12

Demo 13

Notes Some checks can be performed while collecting information Visitors are your friends In general, you cannot statically ensure correctness of a program Due date is Nov, 12 th. Start early! 14

Design Patterns 15

Task 1: Tree traversal In-order 0 Preorder 0 1 2 1 2 3 4 5 3 4 5 6 6 Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. 16

Iterator pattern interface TreeIterator { Node getcurrent(); boolean hasnext(); void next(); PreOrderTreeIterator TreeIterator InOrderTreeIterator it = new InOrderTreeIterator(tree) while (it.hasnext()) { it.next(); it.getcurrent() common foreach (Node n : tree) { 17

Task 2: Printing strategies 0 Decimal 3, 1, 4, 0, 2, 6, 5 1 2 Binary 11, 1, 100, 0, 10, 110, 111 3 4 5 6 Define a family of algorithms, encapsulate each one, and make them interchangeable. 18

Strategy pattern interface PrintingStrategy { String printnode(node n); BinaryPrinter PrintingStrategy DecimalPrinter PrintingStrategy strategy; if (isbinary) strategy = new BinaryPrinter(); else strategy = new DecimalPrinter(); Strategy selection foreach (Node n : tree) { strategy.printnode(n); Iteration over tree Composition of patterns: Data Structure + + Iterator Strategy 19

Task 3: Tree observer 0 NodeObserver 1 2 3 4 +1 5 ChangeLogger ChangeLogger ChangeLogger 6 +1 interface NodeObserver { void update(node n); Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. 20

Observer pattern 0 1 2 addobserver() 0 1 2 3 4 5 3 4 5 6 6 setvalue() notifyobservers(this) void notifyobservers(node n) { for (NodeObserver obs : observers) { obs.update(n); if (getparent()!= null) getparent().notifyobservers(n); 21