CS536 Types 1. Roadmap Back from our LR Parsing Detour Name analysis – Static v dynamic – Scope Today – Type checking 2 Scanner Parser Tokens Semantic.

Slides:



Advertisements
Similar presentations
CPSC 388 – Compiler Design and Construction
Advertisements

Semantic Analysis and Symbol Tables
Attribute Grammars Prabhaker Mateti ACK: Assembled from many sources.
Semantic Analysis Chapter 6. Two Flavors  Static (done during compile time) –C –Ada  Dynamic (done during run time) –LISP –Smalltalk  Optimization.
1 Mooly Sagiv and Greta Yorsh School of Computer Science Tel-Aviv University Modern Compiler Design.
Winter Compiler Construction T7 – semantic analysis part II type-checking Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv.
INF 212 ANALYSIS OF PROG. LANGS Type Systems Instructors: Crista Lopes Copyright © Instructors.
Chapter 5: Elementary Data Types Properties of types and objects –Data objects, variables and constants –Data types –Declarations –Type checking –Assignment.
Copyright © by Curt Hill Expressions and Assignment Statements Part 2.
Compiler Construction
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
CS 330 Programming Languages 10 / 16 / 2008 Instructor: Michael Eckmann.
Cse321, Programming Languages and Compilers 1 6/19/2015 Lecture #18, March 14, 2007 Syntax directed translations, Meanings of programs, Rules for writing.
CS 330 Programming Languages 10 / 24 / 2006 Instructor: Michael Eckmann.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
1 Type Type system for a programming language = –set of types AND – rules that specify how a typed program is allowed to behave Why? –to generate better.
Cs164 Prof. Bodik, Fall Symbol Tables and Static Checks Lecture 14.
Abstract Syntax Trees Lecture 14 Wed, Mar 3, 2004.
CS 330 Programming Languages 10 / 21 / 2008 Instructor: Michael Eckmann.
CSc 453 Semantic Analysis Saumya Debray The University of Arizona Tucson.
Semantic Analysis CS 671 February 5, CS 671 – Spring The Compiler So Far Lexical analysis Detects inputs with illegal tokens –e.g.: main$
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
Names Variables Type Checking Strong Typing Type Compatibility 1.
March 12, ICE 1341 – Programming Languages (Lecture #6) In-Young Ko Programming Languages (ICE 1341) Lecture #6 Programming Languages (ICE 1341)
Lesson 11 CDT301 – Compiler Theory, Spring 2011 Teacher: Linus Källberg.
CS212: Object Oriented Analysis and Design Lecture 10: Copy constructor.
CS412/413 Introduction to Compilers and Translators Spring ’99 Lecture 8: Semantic Analysis and Symbol Tables.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
410/510 1 of 18 Week 5 – Lecture 1 Semantic Analysis Compiler Construction.
Formal Semantics Chapter Twenty-ThreeModern Programming Languages, 2nd ed.1.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CS212: Object Oriented Analysis and Design Lecture 9: Function Overloading in C++
Types in programming languages1 What are types, and why do we need them?
1 Review. 2 Creating a Runnable Program  What is the function of the compiler?  What is the function of the linker?  Java doesn't have a linker. If.
CS536 Semantic Analysis Introduction with Emphasis on Name Analysis 1.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
1 Static Checking and Type Systems Chapter 6 COP5621 Compiler Construction Copyright Robert van Engelen, Florida State University, 2005.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts.
Semantic Analysis II Type Checking EECS 483 – Lecture 12 University of Michigan Wednesday, October 18, 2006.
1 Structure of Compilers Lexical Analyzer (scanner) Modified Source Program Parser Tokens Semantic Analysis Syntactic Structure Optimizer Code Generator.
CS412/413 Introduction to Compilers Radu Rugina Lecture 13 : Static Semantics 18 Feb 02.
Data Types (3) 1 Programming Languages – Principles and Practice by Kenneth C Louden.
CS 330 Programming Languages 10 / 23 / 2007 Instructor: Michael Eckmann.
LECTURE 3 Compiler Phases. COMPILER PHASES Compilation of a program proceeds through a fixed series of phases.  Each phase uses an (intermediate) form.
Prof. Necula CS 164 Lecture 171 Operational Semantics of Cool ICOM 4029 Lecture 10.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
Windows Programming Lecture 06. Data Types Classification Data types are classified in two categories that is, – those data types which stores decimal.
Dr. M. Al-Mulhem Introduction 1 Chapter 6 Type Systems.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
LECTURE 10 Semantic Analysis. REVIEW So far, we’ve covered the following: Compilation methods: compilation vs. interpretation. The overall compilation.
Heath Carroll Bill Hanczaryk Rich Porter.  A Theory of Type Polymorphism in Programming ◦ Robin Milner (1977)  Milner credited with introducing the.
Compilers Principles, Techniques, & Tools Taught by Jing Zhang
Types Type Errors Static and Dynamic Typing Basic Types NonBasic Types
Type Checking and Type Inference
Lecture 4: Type Systems.
Semantic Analysis with Emphasis on Name Analysis
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Compiler Construction
Compilers Principles, Techniques, & Tools Taught by Jing Zhang
Java’s Central Casting
Compiler Construction
Presentation transcript:

CS536 Types 1

Roadmap Back from our LR Parsing Detour Name analysis – Static v dynamic – Scope Today – Type checking 2 Scanner Parser Tokens Semantic Anlaysis Parse Tree AST IR Codegen Optimizer MC Codegen Scanner Parser LR Parser Symbol table

Lecture Outline Type Safari – Type system concepts – Type system vocab YES – Type rules – How to apply type rules Data representation – Moving towards actual code generation – Brief comments about types in memory 3

Say, What is a Type? Short for “data type” – Classification identifying kinds of data – A set of possible values which a variable can possess – Operations that can be done on member values – A representation (perhaps in memory) 4

Type Intuition You can’t do this: int a = 0; int * pointer = &a; float fraction = 1.2; a = pointer + fraction; 5 … or can you?

Components of a type system Primitive types + means of building aggregate types – int, bool, void, class, function, struct Means of determining if types are compatible – Can disparate types be combined? How? Rules for inferring type of an expression 6

Type Rules For every operator (including assignment) – What types can the operand have? – What type is the result? Examples double a; int b; a = b; b = a; 7 Legal in Java, C++ Legal in C++, not in Java

Type Coercion Implicit cast from one data type to another – Float to int – Narrow form: type promotion When the destination type can represent the source type float to double 8

Types of Typing I: When do we check? Static typing – Type checks are made before execution of the program (compile-time) Dynamic typing – Type checks are made during execution (runtime) Combination of the two – Java (downcasting v cross-casting) 9

Example: Casting Cross-casting (static check) Apple a = new Apple(); Orange o = (Orange)a; Downcasting (dynamic check) Fruit f = new Apple(); if ( … ) { f = new Orange(); } Apple two = (Apple)f; 10 Fruit AppleOrange

Static v Dynamic Tradeoffs 11 Statically typed – Compile-time optimization – Compile-time error checking Dynamically typed – Avoid dealing with errors that don’t matter – Some added flexibility

Duck Typing 12 Type is defined by the methods and properties class bird: def quack(): print(“quack!”) class mechaBird: def quack(): print(“101011…”) Duck Punching – Runtime modifications to allow duck typing

Types of Typing II: What do we check? Strong vs weak typing – Degree to which type checks are performed – Degree to which type errors are allowed to happen at runtime – Continuum without precise definitions 13

Strong v Weak No universal definitions but… – Statically typed is often considered stronger (fewer type errors possible) – The more implicit casts allowed the weaker the type system – The fewer checks performed at runtime the weaker 14

Strong v Weak Example C (weaker) union either{ int i; float f; } u; u.i = 12; float val = u.f; 15 SML (stronger) real(2) + 2.0

Type Safety Type safety – All successful operations must be allowed by the type system – Java was explicitly designed to be type safe If you have a variable with some type, it is guaranteed to be of that type – C is not – C++ is a little better 16

Type Safety Violations C – Format specifier printf(“%s”, 1); – Memory safety struct big{ int a[100000]; }; struct big * b = malloc(1); 17 C++ – Unchecked casts class T1{ char a}; class T2{ int b; }; int main{ T1 * myT1 = new T1(); T2 * myT2 = new T2(); myT1 = (T1*)myT2; }

Type System of YES 18 YES

YES type system Primitive types – int, bool, string, void Type constructors – struct Coercion – bool cannot be used as an int in our language (nor vice-versa) 19

YES Type Errors I Arithmetic operators must have int operands Equality operators == and != – Operands must have same type – Can’t be applied to Functions (but CAN be applied to function results) struct name struct variables Other relational operators must have int operands Logical operators must have bool operands 20

YES Type Errors II Assignment operator – Must have operands of the same type – Can’t be applied to Functions (but CAN be applied to function results) struct name struct variables For cin >> x; – x cannot be function struct name, struct variable For cout << x; x cannot be function struct name, struct variable Condition of if, while must be boolean 21

YES Type Errors III Invoking (aka calling) something that’s not a function Invoking a function with – Wrong number of args – Wrong types of args Also will not allow struct or functions as args Returning a value from a void function Not returning a value in a non-void function function Returning wrong type of value in a non-void function 22

Type Checking Structurally similar to nameAnalysis – Historically, intermingled with nameAnalysis and done as part of attribute “decoration” Add a typeCheck method to AST nodes – Recursively walk the AST checking subtypes – Let’s look at a couple of examples 23

Type Checking: Binary Operator Get the type of the LHS Get the type of the RHS Check that the types are compatible for the operator Set the kind of the node be a value Set the type of the node to be the type of the operation’s result 24 PlusNode (int) lhs rhs (int)

Type “Checking”: Literal Cannot be wrong – Just pass the type of the literal up the tree 25 IntLitNode (int)

Type Checking: IdNode Look up the type of the declaration – There should be a symbol “linked” to the node Pass symbol type up the tree 26 IdNode mySymbol (int) type: int

Type Checking: IdNode Look up the type of the declaration 27 PlusNode (int) lhs rhs (int)

Type Checking: Others Other node types follow these same principles – Function calls Get type of each actual argument – Match against the formal argument (check symbol) Send the return type up the tree – Statement No type 28

Type Checking: Errors We’d like all distinct errors at the same time – Don’t give up at the first error – Don’t report the same error multiple times Introduce an internal error type – When type incompatibility is discovered Report the error Pass error up the tree – When you get error as an operand Don’t (re)report an error Again, pass error up the tree 29

Error Example int a; bool b; a = true b; b = 2; 30 BoolLit true IntLit 1 Plus IntLit 2 Plus IdNode type: bool name: b symbol AssignExp IdNode type: int name: a symbol AssignStmt AssignExp IdNode symbol IntLit StmtList bool int errorint REPORT error bool error int error bool int error REPORT

Looking Towards Next Lecture Starting Tuesday – Look at data (and therefore types) is represented in the machine – Start very abstract, won’t talk about an actual architecture for awhile – Assembly has no intrinsic notion of types. We’ll have to add code for type checking ourselves 31