TYPES, VALUES AND DECLARATIONS

Similar documents
22c:111 Programming Language Concepts. Fall Types I

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CSCI312 Principles of Programming Languages!

CPSC 3740 Programming Languages University of Lethbridge. Data Types

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

HANDLING NONLOCAL REFERENCES

Data Types. Outline. In Text: Chapter 6. What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers 5-1. Chapter 6: Data Types 2

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result.

Data Types In Text: Ch C apter 6 1

Programming Languages Third Edition. Chapter 7 Basic Semantics

Chapter 5 Names, Binding, Type Checking and Scopes

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Programming Languages

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking

Names, Bindings, Scopes

Lecture 12: Data Types (and Some Leftover ML)

Introduction. Primitive Data Types: Integer. Primitive Data Types. ICOM 4036 Programming Languages

Types. What is a type?

Fundamentals of Programming Languages. Data Types Lecture 07 sl. dr. ing. Ciprian-Bogdan Chirila

Programming Languages

G Programming Languages - Fall 2012

COSC252: Programming Languages: Basic Semantics: Data Types. Jeremy Bolton, PhD Asst Teaching Professor

Attributes, Bindings, and Semantic Functions Declarations, Blocks, Scope, and the Symbol Table Name Resolution and Overloading Allocation, Lifetimes,

Programming Languages, Summary CSC419; Odelia Schwartz

Data Types. (with Examples In Haskell) COMP 524: Programming Languages Srinivas Krishnan March 22, 2011

CSE 452: Programming Languages. Where are we? Types: Intuitive Perspective. Data Types. High-level Programming Languages.

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

9/7/17. Outline. Name, Scope and Binding. Names. Introduction. Names (continued) Names (continued) In Text: Chapter 5

Data Types (cont.) Subset. subtype in Ada. Powerset. set of in Pascal. implementations. CSE 3302 Programming Languages 10/1/2007

For each of the following variables named x, specify whether they are static, stack-dynamic, or heapdynamic:

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Chapter 6 part 1. Data Types. (updated based on 11th edition) ISBN

CS 230 Programming Languages

Chapter 6. Data Types ISBN

Data Types. Data Types. Introduction. Data Types. Data Types. Data Types. Introduction

COS 140: Foundations of Computer Science

CSC 533: Organization of Programming Languages. Spring 2005

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]

PROCEDURES, METHODS AND FUNCTIONS

Informatica 3 Syntax and Semantics

Types and Type Inference

Organization of Programming Languages CS3200 / 5200N. Lecture 06

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

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

Pierce Ch. 3, 8, 11, 15. Type Systems

SE352b: Roadmap. SE352b Software Engineering Design Tools. W3: Programming Paradigms

CSE 307: Principles of Programming Languages

Chapter 6. Structured Data Types. Topics. Structured Data Types. Vectors and Arrays. Vectors. Vectors: subscripts

Chapter 5. Names, Bindings, and Scopes

Lecture 3: C Programm

CS349/SE382 A1 C Programming Tutorial

G Programming Languages - Fall 2012

6. Names, Scopes, and Bindings

Topic 9: Type Checking

Topic 9: Type Checking

Type Bindings. Static Type Binding

LECTURE 18. Control Flow

Tokens, Expressions and Control Structures

G Programming Languages - Fall 2012

COS 140: Foundations of Computer Science

Imperative Programming

Names, Scopes, and Bindings II. Hwansoo Han

Note 3. Types. Yunheung Paek. Associate Professor Software Optimizations and Restructuring Lab. Seoul National University

Chapter 6. Data Types ISBN

Chapter 5. Variables. Topics. Imperative Paradigm. Von Neumann Architecture

CS201 - Introduction to Programming Glossary By

Programmiersprachen (Programming Languages)

Types. Chapter Six Modern Programming Languages, 2nd ed. 1

CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:

Fundamentals of Programming Languages

CMSC 331 Final Exam Section 0201 December 18, 2000

The New C Standard (Excerpted material)

Compiler Construction

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

Contents of Lecture 3

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Short Notes of CS201

Final-Term Papers Solved MCQS with Reference

References and pointers

PROGRAMMING IN C++ COURSE CONTENT

LECTURE 17. Expressions and Assignment

Types and Type Inference

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

Chapter 6. Data Types

CS558 Programming Languages

Chapter 7:: Data Types. Mid-Term Test. Mid-Term Test (cont.) Administrative Notes

Class Information ANNOUCEMENTS

Zheng-Liang Lu Java Programming 45 / 79

Properties of an identifier (and the object it represents) may be set at

Chapter 5 Names, Bindings, Type Checking, and Scopes

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

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

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

NOTE: Answer ANY FOUR of the following 6 sections:

CS558 Programming Languages

Concepts Introduced in Chapter 7

Lecture Notes on Programming Languages

Intro to C: Pointers and Arrays

Transcription:

COSC 2P90 TYPES, VALUES AND DECLARATIONS (c) S. Thompson, M. Winters 1

Names, References, Values & Types data items have a value and a type type determines set of operations variables Have an identifier (name) Have a storage location Has attributes binding diagram (Barron) name reference value identifiers allowable characters E.g. Perls $,@,% (scalar, array, hash) prefixes length case sensitivity naming conventions Underscore (buffer_size) vscapitlization (buffersize) (c) S. Thompson, M. Winters 2

Binding Association of one property with another choice of a property from a set of possible properties name-declaration binding connection between identifier and declaration name-type binding choose type for a variable identified by a name declaration-reference binding storage allocation reference-value binding storing value of a variable (c) S. Thompson, M. Winters 3

Binding Time time at which binding occurs alternatives compile-time (e.g. name-type binding in Java) load-time (e.g. declaration-reference binding for non-local variables in C) run-time at block entry (e.g. declaration-reference binding for local variables in Java) at statement execution (e.g. reference-value binding for variables) early early error detection and efficient execution late flexibility (c) S. Thompson, M. Winters 4

Name-Declaration Binding declaration Binding Explicit variables have to be declared prior to use { int a; a = 4 + b; } Implicit - declaration occurs at first usage { a = 4; print( a ); } Connection between name and its declaration Rules for binding are referred to as scope rules (c) S. Thompson, M. Winters 5

Scope Rules Static scope at compile-time can be determined from static program text block structure block, scope, hole-in-scope local variable, non-local variable, global variable e.g. Pascal, Java Dynamic scope - at run-time Depends on the order of execution Uses a binding stack Rarely used in practice (Common lisp & perl give the choice to use it) (c) S. Thompson, M. Winters 6

Static Scope Example - Pascal program Example(input, output) var x, y : Real; Visible to entire program # procedure op1; var y, z : Integer; Visible to op1 procedure * begin... y := 34; refers to the y in * x := 27.4;... end{op1}; begin... x := 3.768; y := x; refers to the y in #... end{example}. (c) S. Thompson, M. Winters 7

Static Scope Example - Java class Example { private double x, y; public void op1() { int y, z; y := 34; x := 27.4;... } // op1 public void op2() { x := 3.768; y := x;... } // op2 } // Example (c) S. Thompson, M. Winters 8

Dynamic Scope Example (Pascal syntax) program Dynamic(input, output); var x : Integer; procedure a; begin... write(x);... end{a}; procedure b; var x : Real; begin... x := 2.0;... a;... end{b}; begin... x := 1;... b;... a;... end{dynamic}. (c) S. Thompson, M. Winters 9

Dynamic Scope Example - Perl Static Scope prints 0 $a = 0; sub b { return $a; } sub c { my $a = 1; return b(); } print c(); Dynamic scope prints 1 $a = 0; sub b { return $a; } sub c { local $a = 1; return b(); } print c(); (c) S. Thompson, M. Winters 10

Name-Type Binding specification of type for variable statically typed type is known at compile-time advantages Reliable errors are detected at compile time Efficient no type checks required at runtime Understandable type is obvious to human reader strongly-typed Variables always used in proper context weakly-typed Implicit type conversion occurs usually causes confusion on the result (c) S. Thompson, M. Winters 11

Name-Type Binding dynamically typed run-time variables don t have types, values do advantage flexibility type discovery polymorphic variables in object-oriented languages only subclass values assignable static type checking with flexibility of dynamic typing type inference (ML, Haskell) The ability to deduce a type Available commonly in functional languages (also C# 3.0 & Perl 6) (c) S. Thompson, M. Winters 12

Type Inference Example - C# class Example { void SomeMethod() { var i = 1; i is an integer var mystr = a string ; } } var is also known as an anonymous type (c) S. Thompson, M. Winters 13

Declaration-Reference Binding Refers to when the storage location for a variable is assigned 3 times when a variable can be assigned storage Load time Block entry Statement execution Lifetime (a.k.a. extent) of a variable refers to when during a program execution a variable has storage allocated to it Local variables Lifetime is only during block (method) execution void f() { int i = 0; print(i); } i only has storage while f is executed (c) S. Thompson, M. Winters 14

Declaration-Reference Binding instance variables O-O languages think member variables of a class allocated at statement execution (new) as part of object Lifetime is determined by object lifetime void f() { MyClass obj = new MyClass(1,2); } (c) S. Thompson, M. Winters 15

Declaration-Reference Binding global variables allocated at load time class variables (static in Java) allocated at load time, one occurrence per class /* C */ int somevalue = 1; void SomeFunc() { somevalue = 2; } // Java class someclass { static int somevalue = 1; void SomeFunc() { somevalue = 2; } (c) S. Thompson, M. Winters 16

Declaration-Reference Binding static and own variables procedure memory allocated at load time, but local scope void func() { static int i = 0; printf( %d, i++ ); } int main() { func(); func(); func(); Displays 0 1 2 } (c) S. Thompson, M. Winters 17

Reference-Value Binding Refers to assigning a value to a storage location Run-time at input, assignment or parameter passing Assignment ( y = y + 1 ) 3 bindings involved: name-declaration, declaration-reference, referencevalue dereferencing l-value (can store) vs r-value (read only) Language without an assignment statement it may have immediate name-value binding pure functional languages (c) S. Thompson, M. Winters 18

Reference-Value Binding Uninitialized variables How to deal with this problem? Initialize during declaration Error to use an uninitialized variable Constants name-value binding at compile time Pascal vs Ada vs Java May be delayed until runtime (complex assignment) (c) S. Thompson, M. Winters 19

Types Everything is represented as bits The type gives interpretation A set of values and operations Three common types: scalar, structured and reference Scalar types single values Numeric (e.g. integer, floating point) Logical Character Numeric Types are either Discrete (unique successor & predecessor) Non-discrete (e.g. Real/Double) built-in/primitive types defined in language E.g. int in Java is not an object programmer-defined types type declarations (e.g. Pascal, Ada, C) class declarations (e.g. Java) (c) S. Thompson, M. Winters 20

Specifying Types Very common in languages for variables to be declared before use To either built-in or user-defined Implicit declaration Name of variable implies type (Fortran I-N prefix are Ints) Easy to make type errors through typos Type declarations associate a name with a set of type attributes modifiability, type-checking Type declarations Ada: a,b: Integer C: int a; Derived Types: Same representation but different meaning Ada: Type List is array(1..10) of Integer C: typedef List int[10]; (c) S. Thompson, M. Winters 21

Specifying Types Ada also uses subtypes Subtype is a subset of values E.g. subtype Index is Integer range 1...10; Subtypes & derived types allow programmer to reuse existing representation for new meaning Type equivalence Ada: Name Equivalence To be of the same type, the type of two variables must have the same name Each type has unique operators associated C: Structure Equivalence To be of the same type, the type of two variables must represent the same type abstract data types A type and the operations on that type Operations can be defined through functions (e.g. push & pop) O-O classes encapsulate these together modules contain type declaration class is type declaration (c) S. Thompson, M. Winters 22

Numeric Types machine representation vs standard model efficiency vs compatibility E.g. different floating point answers on different machines operators overloading: effect depends on type of operands 2+3 integer addition 2.3+4.5 floating-point addition div vs / Exponentiation Expensive omitted in some languages to emphasize this Logical results relational operators: <, >=, etc. equality operators: == or = inequality operators:!= or <> or /= integer vs fixed-point vs floating-point impact on equality (c) S. Thompson, M. Winters 23

Integer Types uses as models of Integer in Mathematics vs counting two s complement Range -2 (n-1) to 2 (n-1) -1 where n is the number of bits available Explicit vs. machine dependent ranges larger and smaller ranges C char, short, int, long (& long long) Java byte, short, int, long Pascal subranges Ada Short_Integer, Integer, Long_Integer and subranges Used in derived types and let compiler pick most appropriate (c) S. Thompson, M. Winters 24

Integer Types fixed-point types COBOL & PL/I for currency values Used on hardware with no floating-point support Useful on graphics hardware! Of N bits, M are used to represent the integral component and (N-M) are used to represent the fractional portion (c) S. Thompson, M. Winters 25

Floating-Point Types For mathematical and scientific calculations Supports a wider range of values than integers approximations: range, precision determined by implementation equality representation: sign, exponent, mantissa real number = sign * mantissa * 2^exponent Example 32-bit float (a.k.a. Real) 1 bit sign 7 bits exponent (-64 to +63) Mantissa (.5 <= m < 1) double precision double in Java, C complex numbers pair of floats class definition (c) S. Thompson, M. Winters 26

Logical Types truth values often called Boolean representation bit vs byte literals C & C++ Book is incorrect. Both C & C++ support bool type. (as of 1999) Can use int in C for logical evaluation 0 = false, non-zero = true assignment vs equality test problem e.g. if(a=3) is always true! operations and, or, not short circuit (&&, ) (c) S. Thompson, M. Winters 27

Character Types operations relational and equality a < b < c Equivalent integer value coding scheme unspecified, e.g. Pascal ASCII, e.g. Ada Unicode, e.g. Java char in C 1 byte integer signed & unsigned compiler dependent wchar_t type (wide character) (c) S. Thompson, M. Winters 28

Character Types Unicode Originally was 16-bit (Java 1.0) Standard is at Unicode 5 UTF-8, UTF-16, UTF-32 Multi-byte representation Strings array of char, e.g. Pascal, C, Ada library class, e.g. Java built-in type, e.g. Perl, SNOBOL (c) S. Thompson, M. Winters 29

Enumeration Types User-defined types Used to improve readability named values mapped to integers but not integers e.g. days of the week Pascal: type Days = (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday) C/C++: enum Days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; operations relational operators Predecessor & successor Integer representation advantages with switch statements (c) S. Thompson, M. Winters 30

Enumerated Types unnamed enums used in C as a replacement for #define Classic enum trick in C++; overloading enumerands e.g. Ada type Light is (red, amber, green); type Flag is (red, white); not allowed in Pascal, C, C++ boolean (Pascal/Ada) and char(ada) as enumerated type (Pascal, Ada) type Boolean = { false, true } Displaying (and inputting) enumerated values Requires switches & string manipulation (In C) always required by the programmer (c) S. Thompson, M. Winters 31

Enumerated Types C# & Java (1.5 & up) treat enumerations as classes Going to and from String form is supported by defaulted (same in Ada) Is much more typesafe Before 1.5, Java could use the enum pattern to emulate integer based enums class Days { public static final int Sunday = 1; public static final int Monday = 2;. } Referencing enums is much cleaner in C#/Java Uses the enum name as a prefix (like a static class member) E.g. Day d = Days.Sunday; (c) S. Thompson, M. Winters 32

Enumerated Types (java) See Examples: JavaEnumExamples.java (c) S. Thompson, M. Winters 33

Reference Types The value of the variable of a reference type is a memory location The type of value pointed to is specified at declaration Allows for type checking e.g. C/C++ : int ci = 4; int* cipoint; C/C++ has the addressof operator(&) (@ in delphi) cipoint = &ci; ci reference 34 cipoint reference copy dereferencing operator (* in C/C++) x = *cipoint; (c) S. Thompson, M. Winters 34

Reference Types Arithmetic operation using pointers C, C++ - yes e.g. cipoint++; Pascal, Ada, Java - no Special representation to represent invalid address NULL (or null, or nil) low level programming Aliases Pointers & pointer arithmetic are why C/C++ dominate system programming When there are more than one way of referring to an object Considered bad (although.) From previous slide (*cipoint) = 27; changes the value of ci to 27 as well. Can make state change non-obvious or dangerous parameter passing danger (c) S. Thompson, M. Winters 35

Dynamic Variables Some languages with pointers restrict them to following operations to control their use Dereferencing Equality operators Assignment Cannot assign address of an existing integer, can only refer to a dynamically created variable Example: Pascal type Integerpt = ^Integer; declare pointer type itself var pipoint: Integerpt; declares pointer variables new(pipoint); use dynamic storage allocation to bind pipoint^ = 17; assign a value (using dereferencing) reference pipoint reference copy (c) S. Thompson, M. Winters 36

Dynamic Variables C C++ int *cipoint; cipoint = (int *) malloc(sizeof(int)); cipoint = new int(); *cipoint = 17; C++ vs Java C++: Stype* spoint = new Stype(); Java: Stype spoint = new Stype(); Stype s; explicit pointer variable declaration and explicit dereferencing operator C, Pascal - yes Java - no (c) S. Thompson, M. Winters 37

Aliasing of References (Pascal) var another: Integerpt; declare another ptr another := pipoint; reference 17 pipoint reference another reference copy (c) S. Thompson, M. Winters 38

Garbage Creation after new(pipoint) reference copy pipoint reference reference 17 another reference after new(another)? (c) S. Thompson, M. Winters 39

Garbage explicit deallocation dispose (Pascal), delete (C++) e.g. dispose(pipoint); knowing what to dispose memory leaks dangling reference Reference counting Cyclic issues Still prone to leaks garbage collection Java efficiency (c) S. Thompson, M. Winters 40