Today. Assignments. Lecture Notes CPSC 326 (Spring 2019) Quiz 5. Exam 1 overview. Type checking basics. HW4 due. HW5 out, due in 2 Tuesdays

Similar documents
Today. Assignments. Lecture Notes CPSC 326 (Spring 2019) Quiz 4. Syntax Analysis: Abstract Syntax Trees. HW3 due. HW4 out (due next Thurs)

(2). In your own words, explain how dynamic scoping differs from static scoping.

Note regarding Projects... Every team will need to do a different project (within a section)

Today. Assignments. Lecture Notes CPSC 326 (Spring 2019) Quiz 2. Lexer design. Syntax Analysis: Context-Free Grammars. HW2 (out, due Tues)

Today. Assignments. Note on Revised Proposals Add Details...

Syntax-Directed Translation. Lecture 14

First Midterm Exam CS164, Fall 2007 Oct 2, 2007

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

Writing Evaluators MIF08. Laure Gonnord

Today. Assignments. Lecture Notes CPSC 326 (Spring 2019) Operator Associativity & Precedence. AST Navigation. HW4 out (due next Thurs)

Syntax Errors; Static Semantics

Context-free grammars (CFG s)

Abstract Syntax Trees & Top-Down Parsing

Abstract Syntax Trees & Top-Down Parsing

Syntax Analysis/Parsing. Context-free grammars (CFG s) Context-free grammars vs. Regular Expressions. BNF description of PL/0 syntax

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

Lecture 16: Static Semantics Overview 1

Error Handling Syntax-Directed Translation Recursive Descent Parsing

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

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

Syntax and Grammars 1 / 21

CSE P 501 Compilers. Parsing & Context-Free Grammars Hal Perkins Spring UW CSE P 501 Spring 2018 C-1

PL Revision overview

CPS 506 Comparative Programming Languages. Syntax Specification

SEMANTIC ANALYSIS TYPES AND DECLARATIONS

Lecture 14 Sections Mon, Mar 2, 2009

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

Project Compiler. CS031 TA Help Session November 28, 2011

What is a compiler? var a var b mov 3 a mov 4 r1 cmpi a r1 jge l_e mov 2 b jmp l_d l_e: mov 3 b l_d: ;done

The role of semantic analysis in a compiler

Abstract Syntax Trees & Top-Down Parsing

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

Program Analysis ( 软件源代码分析技术 ) ZHENG LI ( 李征 )

Structure of a compiler. More detailed overview of compiler front end. Today we ll take a quick look at typical parts of a compiler.

Semantic Analysis. Lecture 9. February 7, 2018

Homework & Announcements

Syntax Analysis. Martin Sulzmann. Martin Sulzmann Syntax Analysis 1 / 38

Parsing CSCI-400. Principles of Programming Languages.

Principles of Compiler Design

Decaf Language Reference

Error Handling Syntax-Directed Translation Recursive Descent Parsing

MIDTERM EXAM (Solutions)

CSE450. Translation of Programming Languages. Lecture 11: Semantic Analysis: Types & Type Checking

Error Handling Syntax-Directed Translation Recursive Descent Parsing

COS 320. Compiling Techniques

A programming language requires two major definitions A simple one pass compiler

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

A simple syntax-directed

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

Syntactic Analysis. The Big Picture Again. Grammar. ICS312 Machine-Level and Systems Programming

Syntax-directed translation. Context-sensitive analysis. What context-sensitive questions might the compiler ask?

Intermediate Code Generation

COMP-520 GoLite Tutorial

Project 1: Scheme Pretty-Printer

CSCI Compiler Design

11. a b c d e. 12. a b c d e. 13. a b c d e. 14. a b c d e. 15. a b c d e

A Simple Syntax-Directed Translator

CSE450 Translation of Programming Languages. Lecture 4: Syntax Analysis

Examples of attributes: values of evaluated subtrees, type information, source file coordinates,

Compiler Passes. Semantic Analysis. Semantic Analysis/Checking. Symbol Tables. An Example

Abstract Syntax Trees Synthetic and Inherited Attributes

CS558 Programming Languages

Lecture 15 CIS 341: COMPILERS

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

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

Describing Syntax and Semantics

TDDD55 - Compilers and Interpreters Lesson 3

Derivations vs Parses. Example. Parse Tree. Ambiguity. Different Parse Trees. Context Free Grammars 9/18/2012

Time : 1 Hour Max Marks : 30

CSCI 1260: Compilers and Program Analysis Steven Reiss Fall Lecture 4: Syntax Analysis I

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

Topic of the day: Ch. 4: Top-down parsing

n Closed book n You are allowed 5 cheat pages n Practice problems available in Course Materials n Check grades in Rainbow grades

Syntax. In Text: Chapter 3

Topic 3: Syntax Analysis I

Compiler Design Concepts. Syntax Analysis

Syntax/semantics. Program <> program execution Compiler/interpreter Syntax Grammars Syntax diagrams Automata/State Machines Scanning/Parsing

ICOM 4036 Spring 2004

CMSC 330: Organization of Programming Languages. Operational Semantics

Programming Language Specification and Translation. ICOM 4036 Fall Lecture 3

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

Semantic actions for expressions

Lecture 12: Conditional Expressions and Local Binding

CS164: Midterm I. Fall 2003

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

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

RYERSON UNIVERSITY DEPARTMENT OF COMPUTER SCIENCE CPS 710 FINAL EXAM FALL 2016

MASSACHUSETTS INSTITUTE OF TECHNOLOGY Fall Test I

Modules, Structs, Hashes, and Operational Semantics

CMPS Programming Languages. Dr. Chengwei Lei CEECS California State University, Bakersfield

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

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

The SPL Programming Language Reference Manual

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

Compilers and computer architecture: Semantic analysis

Error Handling Syntax-Directed Translation Recursive Descent Parsing. Lecture 6

UNIVERSITY OF CALIFORNIA

Course Overview. Introduction (Chapter 1) Compiler Frontend: Today. Compiler Backend:

Semantic actions for declarations and expressions

Formal Semantics. Chapter Twenty-Three Modern Programming Languages, 2nd ed. 1

Transcription:

Today Quiz 5 Exam 1 overview Type checking basics Assignments HW4 due HW5 out, due in 2 Tuesdays S. Bowers 1 of 11

Exam Overview Basics closed notes, book, etc. 4 multi-part questions worth 15% of final grade Possible Topics Anything from class, readings, and assignments is fair game Lexical analysis (tokens, lexemes, token streams) Syntactic analysis including CFGs, derivations, LL(1) and rewritings, recursive descent parsing Semantic analysis including generating ASTs, issues with associativity and precendence, and type checking (today and Tuesday) General understanding of MyPL syntax Reading specific: static vs dynamic static vs dynamic scoping (name visibility) program blocks and environments S. Bowers 2 of 11

Type Checking The goal of type checking is to: Detect errors due to type issues, e.g.: set x = 0 + "1"; if 42 <= true then set x = 1; end # + requires same-typed operands # int can't be compared to bool Also includes use before def errors, e.g.: var x = 42 + y; if x > 42 then var y = x + 1; else set x = y; end # y not defined # y not defined in this block Function call errors, e.g.: fun int add(x: int, y: int) return x + y; end var r1 = add(1, 2, 3); # wrong number of args var r2 = add(3.14, 1); # wrong argument types Type errors are based on a set of typing rules lots of possibilities, different languages have different rules we define a set of strict typing rules in HW5 (more later) S. Bowers 3 of 11

Basic Approach for HW5 navigate the AST using the Visitor pattern during navigation infer types and look for errors Given this code... 1: var x: int = 10; 2: var r = 0; 3: while x > 0 do 4: set r = r + x; 5: set x = x - 1; 6: end 1. For var x: int = 10 check and infer rhs type, compare against declared type, store x s type 2. For var r = 0, infer rhs type, store as r s type 3. For while x > 0 do ensure x is defined and compatible with 10 (both ints) check each body statement... 4. For set r = r + x 5. etc. ensure in rhs that r and x are defined and types are compatible for + ensure lhs is defined and result type (int) is compatible with lhs (r) type Note we have to keep track of variables and their types! we do this using a symbol table data structure (var -> type mappings) S. Bowers 4 of 11

Scope and Environment An environment stores the state of variables within a scope (block) We use static (block) scoping in MyPL Blocks can be nested (e.g., if-then or while statements) The visibility of a name is roughly the current and ancestor blocks Sub environments created through while and if statements: # global environment +--------------------+ var x = 1; x -> int while x < 10 do +----------------+ # sub environment 1 set x = x * 2; end +----------------+ if x == 10 then +----------------+ # sub environment 2 f -> float var f = 3.14; +----------------+ elseif x > 10 then +----------------+ # sub environment 3...... +----------------+ end +--------------------+ To find the type of a given name... 1. look in the current environment first 2. then the parent environment 3. and so on The symbol table maintains the environment information S. Bowers 5 of 11

Symbol Table Stores variable state in a stack of environments as program is being checked class SymbolTable(object): def push_environment(self) def pop_environment(self) def id_exists(self, identifier) def add_id(self, identifier) def set_info(self, identifier, info) def get_info(self, identifier) New environments created/removed when we visit statement lists... def visit_stmt_list(self, stmt_list): self.sym_table.push_environment() for stmt in stmt_list.stmts: stmt.accept(self) self.sym_table.pop_environment() Record inferred types in a self.current_type instance variable def visit_simple_rvalue(self, simple_rvalue): if simple_rvalue.val.tokentype == token.intval: self.current_type = token.inttype elif simple_rvalue.val.tokentype == token.floatval: self.current_type = token.floattype elif simple_rvalue.val.tokentype == token.boolval: self.current_type = token.booltype elif simple_rvalue.val.tokentype == token.stringval: self.current_type = token.stringtype elif simple_rvalue.val.tokentype == token.nil: self.current_type = token.nil S. Bowers 6 of 11

We use the inferred type to help in more complex statements and expressions def visit_assign_stmt(self, assign_stmt): # check and infer rhs type assign_stmt.rhs.accept(self) rhs_type = self.current_type # check and obtain lhs type assign_stmt.lhs.accept(self) lhs_type = self.current_type # error if rhs and lhs types don't match if rhs_type!= token.nil and rhs_type!= lhs_type: msg = 'mismatch type in assignment' self. error(msg, assign_stmt.lhs.path[0]) Checking simple lvalues... def visit_lvalue(self, lval): # check the first id in the path var_token = lval.path[0] if not self.sym_table.id_exists(var_token.lexeme): msg = 'undefined variable "%s"' % var_token.lexeme self. error(msg, var_token) self.current_type = self.sym_table.get_info(var_token.lexeme) # check if struct for a longer path expression... S. Bowers 7 of 11

Complex Expression Example... AST fragment for the complex expression 3 + 4 * 5 c1: ComplexExpr first_operand s1: SimpleExpr term t1: Token Lexeme = 3 tokentype = INT math_rel t2: Token lexeme = + tokentype = PLUS s2: SimpleExpr term t3: Token lexeme = 4 tokentype = INT rest c2: ComplexExpr first_operand math_rel rest t4: Token lexeme = * tokentype = MULT s3: SimpleExpr term t4: Token lexeme = 5 tokentype = INT The basic steps: 1. visit_complex_expr(c1) is called 2. call visit_complex_expr(c2), which sets current_type to INT 3. store current_type in temporary var right_hand_type 4. call visit_simple_expr(s1), which sets current_type to INT 5. check that current_type == right_hand_type 6. set current_type to INT (really, leave unchanged) Note that visit() functions called indirectly through accept() Exercise: What happens in visit_complex_expr(c2) call? S. Bowers 8 of 11

For HW5, you need to finish the visitor implementation... given your parser w/ AST generation given the symbol table implementation given MyPL typing rules (which I ll give you) Some aspects are tricky... how to represent struct and function types? what to do about nil values? what to do about return statements? how to report error messages?... I won t be picky about this S. Bowers 9 of 11

Understanding Type (Inference) Rules Basics e : t states that expression e has type t... e.g., 42 : int Γ denotes the typing context (the environment) stands for implies Γ e : t means it is implied from the given typing context that e has type t An example typing rule (not from MyPL)... Γ e 1 : t Γ e 2 : t Γ e 1 + e 2 : t If expressions e 1 and e 2 have type t in the current context, then expression e 1 + e 2 has the type t as well typing rules allow us to infer the types of complex expressions which help us to assign types to names and type check statements S. Bowers 10 of 11

Exercise: Go through the MyPL rules and provide examples... Note that: function types take the form f(t 1,..., t n ) t struct types take the form s{a 1 : t 1,..., a n : t n } nil : nil Γ, stmt... means the current context plus the given statement implies Γ f(t 1,..., t n ) t is shorthand for f has the given type (also structs) An example would be infering x s type in var x = 10 % (4 / 2) Or given an assignment from a function call, ensure the assignment is well-typed At this point for HW5... Get started on written part Implement basic expression and statement checking Holding off on functions and structs S. Bowers 11 of 11