Types Chapter SixModern Programming Languages 1. Elements of a Type Its set of values Its operations How its stored internally How its presented externally.

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms
Advertisements

Names and Bindings.
Chapter 7:: Data Types Programming Language Pragmatics
1 Introduction to Data Types (Section 7.1) CSCI 431 Programming Languages Fall 2003 A compilation of material developed by Felix Hernandez-Campos and Michael.
INF 212 ANALYSIS OF PROG. LANGS Type Systems Instructors: Crista Lopes Copyright © Instructors.
Elementary Data Types Prof. Alamdeep Singh. Scalar Data Types Scalar data types represent a single object, i.e. only one value can be derived. In general,
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
CSCI 330: Programming Language Concepts Instructor: Pranava K. Jha
Chapter 5: Elementary Data Types Properties of types and objects –Data objects, variables and constants –Data types –Declarations –Type checking –Assignment.
Type Checking.
Compiler Construction
Chapter 9 Imperative and object-oriented languages 1.
Chapter 6 Structured Data Types Arrays Records. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Definitions data type –collection of data objects.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 5 Types Types are the leaven of computer programming;
1 Names, Scopes and Bindings. 2 Names Kinds of names Kinds of names Variables, functions, classes, types, labels, blocks, operators, tasks, etc. Variables,
ISBN Chapter 6 Data Types: Structured types.
G. Levine Chapter 6 Chapter 6 Encapsulation –Why do we want encapsulation? Programmer friendliness- programmer need not know about these details –Easier.
Primitive Data Types: Numbers Strings Ordinal Types Pointers
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.
Chapter 6 Structured Data Types Arrays Records. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Definitions data type –collection of data objects.
String Escape Sequences
MT311 Java Application Programming and Programming Languages Li Tak Sing ( 李德成 )
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
1 Adapted from slides for COMP 144 Programming Language Concepts Spring 2002 by Felix Hernandez-Campos The University of North Carolina at Chapel Hill.
Types Chapter SixModern Programming Languages, 2nd ed.1.
ISBN 0-321— Chapter 6 sections 1-4, 9 Primitive Data Types Numbers Strings Ordinal Types Pointers.
Names Variables Type Checking Strong Typing Type Compatibility 1.
5-1 Chapter 5: Names, Bindings, Type Checking, and Scopes Variables The Concept of Binding Type Checking Strong Typing Type Compatibility Scope and Lifetime.
CSE 425: Data Types II Survey of Common Types I Records –E.g., structs in C++ –If elements are named, a record is projected into its fields (e.g., via.
March 12, ICE 1341 – Programming Languages (Lecture #6) In-Young Ko Programming Languages (ICE 1341) Lecture #6 Programming Languages (ICE 1341)
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter SixModern Programming Languages1 Types. Chapter SixModern Programming Languages2 A Type Is A Set n When you declare that a variable has a certain.
Chapter SixModern Programming Languages1 Types. Chapter SixModern Programming Languages2 A Type Is A Set Declaring a variable as a certain type restricts.
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.
TYPES Chapter Six Modern Programming Languages 1.
10/31/2015IT 3271 A Type is a Set 1. A set of values 2. A low-level representation 3. A collection of operations on those values int n; Chapter 6: Types.
ISBN Chapter 6 Data Types Introduction Primitive Data Types User-Defined Ordinal Types.
Types in programming languages1 What are types, and why do we need them?
Types(1). Lecture 52 Type(1)  A type is a collection of values and operations on those values. Integer type  values..., -2, -1, 0, 1, 2,...  operations.
Homogeneous tuples What are they? –S 2 = S x S –S n = S x S x … x S Cardinalities –#(S 2 )= (#S) 2 –#(S n )= (#S) n –#(S 0 )= (#S) 0 =1 What is S 0 ? –It.
ISBN Chapter 6 Structured Data Types Array Types Associative Arrays Record Types Union Types.
ISBN Chapter 6 Data Types. Copyright © 2006 Addison-Wesley. All rights reserved. 6-2 Chapter 6 Topics Introduction Primitive Data Types.
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.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
Semantic Analysis II Type Checking EECS 483 – Lecture 12 University of Michigan Wednesday, October 18, 2006.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
CS 330 Programming Languages 10 / 23 / 2007 Instructor: Michael Eckmann.
Names, Scope, and Bindings Programming Languages and Paradigms.
 Data Type is a basic classification which identifies different types of data.  Data Types helps in: › Determining the possible values of a variable.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
Types Chapter SixModern Programming Languages 1. Elements of a Type Its set of values Its operations How its stored internally How its presented externally.
CSI 3125, Data Types, page 1 Data types Outline Primitive data types Structured data types Strings Enumerated types Arrays Records Pointers Reading assignment.
Dr. M. Al-Mulhem Introduction 1 Chapter 6 Type Systems.
Data Types In Text: Chapter 6.
Chapter 6 – Data Types CSCE 343.
CSE 3302 Programming Languages
Type Checking Generalizes the concept of operands and operators to include subprograms and assignments Type checking is the activity of ensuring that the.
Lecture 4: Type Systems.
Lecture 16: Introduction to Data Types
CS 326 Programming Languages, Concepts and Implementation
Instructor : Ahmed Alalawi Slides from Chung –Ta King
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
CS 363 – Chapter 7 Chapter 7 – type systems Types that are supported
Introduction to Data Structure
Java Programming Language
Types and Related Issues
Lecture 7: Types (Revised based on the Tucker’s slides) 10/4/2019
CSE 3302 Programming Languages
Presentation transcript:

Types Chapter SixModern Programming Languages 1

Elements of a Type Its set of values Its operations How its stored internally How its presented externally (printed) (Abstract Types just specify operations) Chapter SixModern Programming Languages2

A Type Is A Set When you declare that a variable has a certain type, you are saying that the values the variable can have are elements of a certain set A type is a set of values ◦ with a low-level representation ◦ and an associated collection of operations that can be applied to those values Chapter SixModern Programming Languages 3 int n;

Primitive vs. Constructed Types Any type that a program can use but cannot define for itself is a primitive type in the language Any type that a program can define for itself (using the primitive types) is a constructed (or structured) type Some primitive types in ML: int, real, char An ML program cannot define a type named int that works like the predefined int A constructed type: int list Defined using the primitive type int and the list type constructor Chapter SixModern Programming Languages 4

Primitive Types The definition of a language says what the primitive types are Some languages define the primitive types more strictly than others: ◦ Some define the primitive types exactly (Java) ◦ Others leave some wiggle room—the primitive types may be different sets in different implementations of the language (C, ML) Chapter SixModern Programming Languages 5

Comparing Integral Types Chapter SixModern Programming Languages 6 C: char unsigned char short int unsigned short int int unsigned int long int unsigned long int No standard implementation, but longer sizes must provide at least as much range as shorter sizes. Java: byte (1-byte signed) char (2-byte unsigned) short (2-byte signed) int (4-byte signed) long (8-byte signed) Scheme: integer Integers of unbounded range

Issues What sets do the primitive types signify? ◦ How much is part of the language specification, how much left up to the implementation? ◦ If necessary, how can a program find out? ( INT_MAX in C, Int.maxInt in ML, etc.) What operations are supported? ◦ Detailed definitions: rounding, exceptions, etc. The choice of representation is a critical part of these decisions Chapter SixModern Programming Languages 7

Constructed Types Additional types defined using the language This chapter: enumerations, tuples, arrays, strings, lists, unions, subtypes, and function types For each one, there is connection between how sets are defined mathematically (in the abstract), and how types are defined in programming languages Chapter SixModern Programming Languages 8

Making Sets by Enumeration Mathematically, we can construct sets by just listing all the elements: Chapter SixModern Programming Languages 9

Making Types by Enumeration Many languages support enumerated types: These define a new type (= set) They also define a collection of named constants of that type (= elements) Chapter SixModern Programming Languages 10 C: enum coin {penny, nickel, dime, quarter}; Ada: type GENDER is (MALE, FEMALE); Pascal: type primaryColors = (red, green, blue); ML: datatype day = M | Tu | W | Th | F | Sa | Su;

Representing Enumeration Values A common representation is to treat the values of an enumeration as small integers This may even be exposed to the programmer, as it is in C: Chapter SixModern Programming Languages 11 enum coin { penny = 1, nickel = 5, dime = 10, quarter = 25 }; enum escapes { BELL = '\a', BACKSPACE = '\b', TAB = '\t', NEWLINE = '\n', VTAB = '\v', RETURN = '\r' };

Operations on Enumeration Values Equality test: If the integer nature of the representation is exposed, a language will allow some or all integer operations: Chapter SixModern Programming Languages 12 fun isWeekend x = (x = Sa orelse x = Su); Pascal: for C := red to blue do P(C) C: int x = penny + nickel + dime;

Making Sets by Tupling The Cartesian product of two or more sets defines sets of tuples: Chapter SixModern Programming Languages 13

Making Types by Tupling Some languages support pure tuples: Many others support record types, which are just tuples with named fields: Chapter SixModern Programming Languages 14 fun get1 (x : real * real) = #1 x; C: struct complex { double rp; double ip; }; ML: type complex = { rp:real, ip:real }; fun getip (x : complex) = #ip x;

Representing Tuple Values A common representation is to just place the elements side-by-side in memory But there are lots of details: ◦ in what order? ◦ with “holes” to align elements (e.g. on word boundaries) in memory? ◦ is any or all of this visible to the programmer? ◦ See alignment.cpp Chapter SixModern Programming Languages 15

Example: ANSI C Chapter SixModern Programming Languages 16 The members of a structure have addresses increasing in the order of their declarations. A non-field member of a structure is aligned at an addressing boundary depending on its type; therefore, there may be unnamed holes in a structure. If a pointer to a structure is cast to the type of a pointer to its first member, the result refers to the first member… Adjacent field members of structures are packed into implementation-dependent storage units in an implementation- dependent direction... The C Programming Language, 2nd ed. Brian W. Kernighan and Dennis M. Ritchie

Operations on Tuple Values Selection, of course: Other operations depending on how much of the representation is exposed: Chapter SixModern Programming Languages 17 C: x.ip ML: #ip x C: double y = *((double *) &x); struct person { char *firstname; char *lastname; } p1 = {"marcia","brady"};

Vectors Fixed-size vectors (arrays): Arbitrary-size vectors: Chapter SixModern Programming Languages 18

Types Related To Vectors Arrays, strings and lists Like tuples, but with many variations One example: indexes ◦ What are the index values? ◦ Is the array size fixed at compile time? Chapter SixModern Programming Languages 19

Index Values Java, C, C++: ◦ First element of an array a is a[0] ◦ Indexes are always integers starting from 0 Pascal is more flexible: ◦ Various index types are possible: integers, characters, enumerations, subranges ◦ Starting index chosen by the programmer ◦ Ending index too: size is fixed at compile time Chapter SixModern Programming Languages 20

Pascal Array Example Chapter SixModern Programming Languages 21 type LetterCount = array['a'..'z'] of Integer; var Counts: LetterCount; begin Counts['a'] = 1 etc. Note: This is not a map!

Types Related To Vectors Many variations on vector-related types: Chapter SixModern Programming Languages 22 What are the index values? Is array size fixed at compile time (i.e., part of static type)? What operations are supported? Is re-dimensioning possible at runtime? Is it transparent? Are multiple dimensions allowed? Is a higher-dimensional array the same as an array of arrays? (C#) What is the order of elements in memory? (row vs. column) Is there a separate type for strings (not just array of characters)? Is there a separate type for lists (vs. arrays)?

Making Sets by Union We can make a new set by taking the union of existing sets: Holds only one at a time. Chapter SixModern Programming Languages 23

Making Types by Union Many languages support union types: Chapter SixModern Programming Languages 24 C: union element { int i; float f; }; ML: datatype element = I of int | F of real;

Representing Union Values You can have the two representations overlap each other in memory This representation may or may not be exposed to the programmer See also union.cpp Chapter SixModern Programming Languages 25 union element { int i; char *p; } u; /* sizeof(u) == max(sizeof(u.i),sizeof(u.p)) */

Strictly Typed Unions In ML, all you can do with a union is extract the current contents And you have to say what to do with each type of value in the union: Chapter SixModern Programming Languages 26 datatype element = I of int | F of real; fun getReal (F x) = x | getReal (I x) = real x;

Loosely Typed Unions Some languages expose the details of union implementation Programs can take advantage of the fact that the specific type of a value is lost: Chapter SixModern Programming Languages 27 union element { int i; float f; }; union element e; e.i = 100; float x = e.f;

What ANSI C Says About This Chapter SixModern Programming Languages 28 A union may be thought of as a structure all of whose members begin at offset 0 and whose size is sufficient to contain any of its members. At most one of the members can be stored in a union at any time. If a pointer to a union is cast to the type of a pointer to a member, the result refers to that member. In general, a member of a union may not be inspected unless the value of the union has been assigned using that same member. The C Programming Language, 2nd ed. Brian W. Kernighan and Dennis M. Ritchie

C Bit Fields struct Date { unsigned int day: 5; unsigned int mon: 4; unsigned int year: 7; }; See bit.cpp Chapter SixModern Programming Languages 29

A Middle Way: Variant Records Union where specific type is linked to the value of a field (“discriminated union”) A variety of languages including Ada and Modula-2 Chapter SixModern Programming Languages 30

Ada Variant Record Example Chapter SixModern Programming Languages 31 type DEVICE is (PRINTER, DISK); type PERIPHERAL(Unit: DEVICE) is record HoursWorking: INTEGER; case Unit is when PRINTER => Line_count: INTEGER; when DISK => Cylinder: INTEGER; Track: INTEGER; end case; end record;

Making Subsets We can define the subset selected by any predicate P: Chapter SixModern Programming Languages 32

Subtypes A type B is a subtype of another type A if: ◦ 1) Its values are a subset of the values of A ◦ 2) It supports all the same operations as A Another perspective: ◦ If elements of type B can be meaningfully substituted for elements of type A in all contexts requiring elements of A (Public) Inheritance is only one manifestation of subtyping Chapter SixModern Programming Languages33

Making Subtypes Some languages support subtypes, with more or less generality ◦ Less general: Pascal subranges type digit = 0..9; ◦ More general: Ada subtypes subtype DIGIT is INTEGER range 0..9; subtype WEEKDAY is DAY range MON..FRI; ◦ Most general: Lisp types with predicates Chapter SixModern Programming Languages 34

Example: Ada Subtypes Chapter SixModern Programming Languages 35 type DEVICE is (PRINTER, DISK); type PERIPHERAL(Unit: DEVICE) is record HoursWorking: INTEGER; case Unit is when PRINTER => Line_count: INTEGER; when DISK => Cylinder: INTEGER; Track: INTEGER; end case; end record; subtype DISK_UNIT is PERIPHERAL(DISK);

Example: Lisp Types with Predicates Chapter SixModern Programming Languages 36 (declare (type integer x)) (declare (type (or null cons) x)) (declare (type (and number (not integer)) x)) (declare (type (and integer (satisfies evenp)) x))

Representing Subtype Values Usually, we just use the same representation for the subtype as for the supertype Questions: ◦ Do you try to shorten it if you can? Does X: 1..9 take the same space as X: Integer ? ◦ Do you enforce the subtyping? Is X := 10 legal? What about X := X + 1 ? Chapter SixModern Programming Languages 37

Operations on Subtype Values Usually, supports all the same operations that are supported on the supertype And perhaps additional operations that would not make sense on the supertype: function toDigit(X: Digit): Char; Important meditation: Chapter SixModern Programming Languages 38 A subtype is a subset of values, but it can support a superset of operations.

A Word About Classes In class-based object-oriented languages, a class can be a type: data and operations on that data are bundled together A subclass is a subtype: it includes a subset of the objects, but supports a superset of the operations Chapter SixModern Programming Languages 39

Intrinsic Types Some languages use naming conventions to declare the types of variables ◦ Dialects of BASIC: S$ is a string ◦ Dialects of Fortran: I is an integer Like explicit annotations, these supply static type information to the language system and the human reader Chapter SixModern Programming Languages 40

Extreme Type Inference ML takes type inference to extremes Infers a static type for every expression and for every function Usually requires no annotations Chapter SixModern Programming Languages 41

Simple Type Inference Most languages require some simple kinds of type inference Constants usually have static types ◦ Java: 10 has type int, 10L has type long Expressions may have static types, inferred from operators and types of operands ◦ Java: if a is double, a*0 is double ( 0.0 ) Chapter SixModern Programming Languages 42

Type Systems Have a set of rules for defining new types Have a set of rules that enforce correct behavior: ◦ type equivalence ◦ type compatibility  e.g., integers passed to real parameters  subtypes passed to supertype parameters ◦ type inference Chapter SixModern Programming Languages43

Type Equivalence Name equivalence: types are the same if and only if they have the same name Structural equivalence: types are the same if and only if they are built from the same primitive types using the same type constructors in the same order (i.e., same layout) Not the only two ways to decide equivalence, just the two easiest to explain Languages often use odd variations or combinations Chapter SixModern Programming Languages, 2nd ed.44

Type Equivalence Example What happens if you try to pass f a parameter of type irpair2 ? ◦ Name equivalence does not permit this: irpair2 and irpair1 are different names ◦ Structural equivalence does permit this, since the types are constructed identically ML does permit it Chapter SixModern Programming Languages, 2nd ed.45 type irpair1 = int * real; type irpair2 = int * real; fun f(x:irpair1) = #1 x;

Type Checking Type checking ensures that a program obeys a language’s type compatibility rules Strong vs. weak type checking ◦ Strong typing means that no type violations are allowed Static vs. dynamic type checking ◦ Dynamic type checking happens at runtime ◦ Static type checking happens at compile time ◦ Some languages do both (Java, C#, C++) Chapter SixModern Programming Languages46

Static Type Checking Static type checking determines a type for everything before running the program: variables, functions, expressions, everything Compile-time error messages when static types are not consistent: ◦ Operators: 1+"abc" ◦ Functions: round("abc") ◦ Statements: if "abc" then … Many modern languages are statically typed Chapter SixModern Programming Languages 47

Dynamic Typing In some languages, programs are not statically type-checked before being run They are usually still dynamically type- checked ◦ At runtime, the language system checks that operands are of suitable types for operators Chapter SixModern Programming Languages 48

Example: Lisp This Lisp function adds two numbers: It won’t work if a or b is not a number An improper call, like (f nil nil), is not caught at compile time It is caught at runtime – that is dynamic typing Chapter SixModern Programming Languages 49 (defun f (a b) (+ a b))

It Still Uses Types Although dynamic typing does not type everything at compile time, it still uses types In a way, it uses them even more than static typing It needs to have types to check at runtime So the language system must store type information with values in memory Chapter SixModern Programming Languages 50

Duck Typing “If it quacks like a duck…” Found in dynamically-typed languages and C++ templates ◦ Python, Ruby, Perl, PHP, JavaScript, etc. If a type has the needed operations in its context, then all is well ◦ Independent of type name or class hierarchy ◦ aka “structural equivalence” Chapter SixModern Programming Languages 51

Static vs. Dynamic Typing Which is better? What types of programs are more suitable for one or the other? Chapter SixModern Programming Languages 52

Static vs. Dynamic Typing Not quite a black-and-white picture Statically typed languages often use some dynamic typing ◦ Subtypes can cause this ◦ Everything is typed at compile time, but compile-time type may have subtypes ◦ At runtime, it may be necessary to check a value’s membership in a subtype ◦ This problem arises in object-oriented languages especially Chapter SixModern Programming Languages 53

Explicit Runtime Type Tests Some languages allow explicit runtime type tests: ◦ Java: test object type with instanceof operator ◦ C++: dynamic_cast These require type information to be present at runtime, even when the language is mostly statically typed Chapter SixModern Programming Languages 54

Strong Typing, Weak Typing The purpose of type-checking is to prevent the application of operations to incorrect types of operands In some languages, like ML and Java, the type- checking is thorough enough to guarantee this—that’s strong typing Many languages (like C) fall short of this: there are holes in the type system that add flexibility but weaken the guarantee: ◦ unions, varargs, pointer-array interoperability, reinterpret_cast Chapter SixModern Programming Languages 55

Conclusion A key question for type systems: how much of the representation is exposed? Some programmers prefer languages like C that expose many implementation details ◦ They offer the power to cut through type abstractions, when it is useful or efficient or fun to do so Others prefer languages like ML that hide all implementation details (abstract types) ◦ Clean, mathematical interfaces make it easier to write correct programs, and to prove them correct Chapter SixModern Programming Languages 56