Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer



Similar documents
Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Lecture 9. Semantic Analysis Scoping and Symbol Table

Semantic Analysis: Types and Type Checking

Chapter 5 Names, Bindings, Type Checking, and Scopes

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

CSCI 3136 Principles of Programming Languages

Introduction to Python

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Moving from CS 61A Scheme to CS 61B Java

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Introduction. Compiler Design CSE 504. Overview. Programming problems are easier to solve in high-level languages

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Introduction to Object-Oriented Programming

Programming Language Rankings. Lecture 15: Type Inference, polymorphism & Type Classes. Top Combined. Tiobe Index. CSC 131! Fall, 2014!

The C Programming Language course syllabus associate level

Semester Review. CSC 301, Fall 2015

Programming Languages

Lecture 1: Introduction

Compiler Construction

Glossary of Object Oriented Terms

Symbol Tables. Introduction

03 - Lexical Analysis

Context free grammars and predictive parsing

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

Principles of Programming Languages Topic: Introduction Professor Louis Steinberg

CSE 307: Principles of Programming Languages

Class 16: Function Parameters and Polymorphism

Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

C Compiler Targeting the Java Virtual Machine

Flex/Bison Tutorial. Aaron Myles Landwehr CAPSL 2/17/2012

Programming Language Features (cont.) CMSC 330: Organization of Programming Languages. Parameter Passing in OCaml. Call-by-Value

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

COMP 356 Programming Language Structures Notes for Chapter 4 of Concepts of Programming Languages Scanning and Parsing

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Lexical Analysis and Scanning. Honors Compilers Feb 5 th 2001 Robert Dewar

Chapter 7: Functional Programming Languages

Semantic Checker (Part I)

AP Computer Science Java Subset

CS143 Handout 18 Summer 2012 July 16 th, 2012 Semantic Analysis

Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Programming Languages CIS 443

Lexical analysis FORMAL LANGUAGES AND COMPILERS. Floriano Scioscia. Formal Languages and Compilers A.Y. 2015/2016

Generalizing Overloading for C++2000

PostgreSQL Functions By Example

Python 2 and 3 compatibility testing via optional run-time type checking

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Advanced compiler construction. General course information. Teacher & assistant. Course goals. Evaluation. Grading scheme. Michel Schinz

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Install Java Development Kit (JDK) 1.8

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Objects and classes. Objects and classes. Jarkko Toivonen (CS Department) Programming in Python 1

Parameter passing in LISP

Scanning and parsing. Topics. Announcements Pick a partner by Monday Makeup lecture will be on Monday August 29th at 3pm

Computer Programming. Course Details An Introduction to Computational Tools. Prof. Mauro Gaspari:

Java Interview Questions and Answers

Introduction to the course, Eclipse and Python

Habanero Extreme Scale Software Research Project

Functional Programming. Functional Programming Languages. Chapter 14. Introduction

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Chapter 2: Elements of Java

Object Oriented Software Design

Getting Started with the Internet Communications Engine

Design Patterns in Parsing

Sources: On the Web: Slides will be available on:

CS 106 Introduction to Computer Science I

Object Oriented Software Design

n Introduction n Art of programming language design n Programming language spectrum n Why study programming languages? n Overview of compilation

Parsing Technology and its role in Legacy Modernization. A Metaware White Paper

An Incomplete C++ Primer. University of Wyoming MA 5310

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Parameter Passing Methods

History OOP languages Year Language 1967 Simula Smalltalk

Compiler Construction

University of Toronto Department of Electrical and Computer Engineering. Midterm Examination. CSC467 Compilers and Interpreters Fall Semester, 2005

Introduction to Java

Computer Programming I

Java (12 Weeks) Introduction to Java Programming Language

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Java Application Developer Certificate Program Competencies

Introduction to Programming

Chapter 15 Functional Programming Languages

The previous chapter provided a definition of the semantics of a programming

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Recovering Business Rules from Legacy Source Code for System Modernization

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

GENERIC and GIMPLE: A New Tree Representation for Entire Functions

Calculator. Introduction. Requirements. Design. The calculator control system. F. Wagner August 2009

Chapter One Introduction to Programming

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Compilation 2012 Domain-Specific Languages and Syntax Extensions

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

COMPUTER SCIENCE. 1. Computer Fundamentals and Applications

C++ Overloading, Constructors, Assignment operator

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Theory of Compilation

Transcription:

Lecture 10: Static Semantics Overview 1 Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces trees Detects & eliminates ill-formed parse trees Static semantic analysis = we are here Produces decorated tree with additional information attached Detects & eliminates remaining static errors Static vs. Dynamic Weusethetermstaticto describepropertiesthatthecompilercan determine without considering any particular execution. E.g., in def f(x) : x + 1 Both uses of x refer to same variable Dynamic properties are those that depend on particular executions in general. E.g., will x = x/y cause an arithmetic exception? Actually, distinction is not that simple. E.g., after y = x + 2 compiler could deduce that x and y are integers. But languages often designed to require that we treat variables only according to explicitly declared types, because deductions are difficult or impossible in general. 1 From material by R. Bodik and P. Hilfinger Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 1 Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 2 Typical Tasks of the Semantic Analyzer Find the declaration that defines each identifier instance Determine the static types of expressions Perform re-organizations of the AST that were inconvenient in parser, or required semantic information Detect errors and fix to allow further processing Typical Semantic Errors: Java, C++ Multiple declarations: a variable should be declared (in the same region) at most once Undeclared variable: a variable should not be used without being declared. Type mismatch: e.g., type of the left-hand side of an assignment should match the type of the right-hand side. Wrong arguments: methods should be called with the right number and types of arguments. Definite-assignment check (Java): conservative check that simple variables assigned to before use. Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 3 Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 4

Output from Static Semantic Analysis Input is AST; output is an annotated tree: identifiers decorated with declarations, other expressions with type information. def f (x): stmt list return x+y y = 2 = def = x:#1 3:Int f:#2 id list return y:#4 2:Int Output from Static Semantic Analysis (II) Analysis has added objects we ll call symbol entries to hold information about instances of identifiers. In this example, #1: x, Any, 0 denotes an entry for something named x occurring at the outer lexical level (level 0) and having static type Any. For other expressions, we annotate with static type information. x:#3 +:Any Id Type Nesting #1: x, Any, 0 #2: f, Any->Any, 0 #3: x, Any, 1 #4: y, Any, 0 x:#3 y:#4 Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 5 Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 6 Output from Static Semantic Analysis: Classes In Python (dynamically typed), can write class A(object): def f(self): return self.x a1 = A(); a2 = A() # Create two As a1.; print a1.x # OK print a2.x # Error; there is no x so can t say much about attributes (fields) of A. In Java, C, C++ (statically typed), analogous program is illegal, even without second print (the class definition itself is illegal). So in statically typed languages, symbol entries for classes would contain dictionaries mapping attribute names to types. Scope Rules: Binding Names to Symbol Entries Scope of a declaration: section of text or program execution in which declaration applies Declarative region: section of text or program execution that bounds scopes of declarations (we ll say region for short). If scope of a declaration defined entirely according to its position in source text of a program, we say language is statically scoped. If scope of a declaration depends on what statements get executed during a particular run of the program, we say language has dynamically scoped. Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 7 Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 8

Scope Rules: Name= Declaration is Many-to-One In most languages, can declare the same name multiple times, if its declarations occur in different declarative regions, or involve different kinds of names. Examples from Java?, C++? Scope Rules: Nesting Most statically scoped languages (including C, C++, Java) use: Algol scope rule: Where multiple declarations might apply, choose the one defined in the innermost (most deeply nested) declarative region. Often expressed as inner declarations hide outer ones. Variations on this: Java disallows attempts to hide local variables and parameters. Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 9 Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 10 Scope Rules: Declarative Regions Languages differ in their definitions of declarative regions. In Java, variable declaration s effect stops at the closing }, that is, each function body is a declarative region. What others? In Python, function header and body make up a declarative region, as does a lambda expression. But nothing smaller. Just one x in this program: def f(x): L = [x for x in xrange(0,10)] Scope Rules: Use Before Definition Languages have taken various decisions on where scopes start. In Java, C++, scope of a member (field or method) includes the entire class (textual uses may precede declaration). But scope of a local variable starts at its declaration. As for non-member and class declarations in C++: must write extern int f(int); // Forward declarations class C; int x = f(3) // Would be illegal w/o forward decls. void g(c* x) {... } int f (int x) {... } // Full definitions class C {... } Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 11 Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 12

Scope Rules: Overloading In Java or C++ (not Python or C), can use the same name for more than one method, as long as the number or types of parameters are unique. int add(int a, int b); float add(float a, float b); The declaration applies to the signature name + argument types not just name. But return type not part of signature, so this won t work: int add (int a, int b); float add (int a, int b) In Ada, it will, because the return type is part of signature. Dynamic Scoping Original Lisp, APL, Snobol use dynamic scoping, rather than static: Use of a variable refers to most recently executed, and still active, declaration of that variable. Makes static determination of declaration generally impossible. Example: void main() { f1(); f2(); } void f1() { int x = 10; g(); } void f2() { String x = "hello"; f3();g(); } void f3() { double 0.5; } void g() { print(x); } With static scoping, illegal. With dynamic scoping, prints 10 and hello Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 13 Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 14 Explicit vs. Implicit Declaration Java, C++ require explicit declarations of things. C is lenient: if you write foo(3) with no declaration of foo in scope, C will supply one. Python implicitly declares variables you assign to in a function to be local variables. Fortran implicitly declares any variables you use, and gives them a type depending on their first letter. But in all these cases, there is a declaration as far as the compiler is concerned. So How Do We Annotate with Declarations? Idea is to recursively navigate the AST, in effect executing the program in simplified fashion, extracting information that isn t data dependent. You saw it in CS61A (sort of). Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 15 Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 16

Environment Diagrams and Symbol Entries In Scheme, executing (set! x 7) (define (f x) (let ((y (+ x 39)) (+ x y))) (f 3) would eventually give this environment at (+ x y): global environment x: 7 f:... x: 3 y: 42 current environment Now abstract away values in favor of static type info: #1. x: Any #2. f: Any Any #3. x: Any #4. y: Any and voila! A data structure for mapping names to current declarations: a block-structured symbol table. Last modified: Mon Feb 23 14:39:08 2009 CS164: Lecture #10 17