Docsity

Types and Type Systems in CSCI 4430: Understanding Types, Type Checking, and Equivalence -, Study Guides, Projects, Research of Programming Languages

Toggle sidebar
bg1
1
Spring 09 CSCI 4430, A Milanova/BG Ryder 1
Announcements
๎˜Project 2
๎˜Due today
๎˜HW4
๎˜Will be posted on Friday, April 3
Spring 09 CSCI 4430, A Milanova/BG Ryder 2
Last Class
๎˜Lambda Calculus
๎˜Applied lambda calculus
๎˜Typed lambda calculus
๎˜Types
๎˜Types and type systems
๎˜Type checking (started)
Spring 09 CSCI 4430, A Milanova/BG Ryder 3
Types and Type Systems
๎˜What is a type?
๎˜A set of values and the valid operations on those values
๎˜E.g., Integers: +, -, *, /, <, <=, ==, >=, >
๎˜Provide semantic correctness checking
๎˜What is a type system?
๎˜A mechanism to define types and associate them with
certain language constructs
๎˜Type expressions
๎˜Type judgments
๎˜(Complex) algorithm for associating types with constructs
๎˜Additional rules for type equivalence, type compatibility
Spring 09 CSCI 4430, A Milanova/BG Ryder 4
Type Checking
๎˜The process of ensuring that the program obeys
the language type rules
๎˜Strongly typed languages
๎˜Term applied to (mostly) statically typed languages
๎˜Scott: A language is said to be strongly typed if the type
system prohibits application of an operation on an object
that is not intended to support that operation
๎˜Cardelliโ€™s type terminology:
๎˜Forbidden error: the occurrence of one of a predetermined class
of execution errors (e.g., logical-not applied to 3)
๎˜A language is said to be strongly typed if it prohibits the
execution of one of the predetermined forbidden errors
5
Type Checking (ii)
๎˜Design choices: weak vs. strong typing
๎˜One forbidden error: applying a method mon
an object of class Athat does not provide
method m
void* x = (void *) new A;
B* q = (B *) x; // a safe downcast?
int case3 = q->foo(66);
C++ (weakly typed): q->foo(66) executesโ€ฆ
Java (strongly typed): q.foo(66) would never
execute
A
B
foo()
foo()
foo(int)
Spring 09 CSCI 4430, A Milanova/BG Ryder 6
Type Checking (iii)
๎˜Design choices: static vs. dynamic checks
๎˜Another forbidden error: indexing out of bounds
๎˜a[i]
๎˜Weak typing โ€“ C++
๎˜0<=i and i<Bound donโ€™t have to be checked
๎˜What is the problem here?
๎˜Strong typing with static checks only - Pascal
๎˜0<=i and i<Bound must be checked at compile time
๎˜What is the problem here?
๎˜Strong typing with static and dynamic checks - Java
๎˜0<=i and i<Bound must be checked at run time
๎˜What is the problem here?
pf3
pf4
pf5

Partial preview of the text

Download Types and Type Systems in CSCI 4430: Understanding Types, Type Checking, and Equivalence - and more Study Guides, Projects, Research Programming Languages in PDF only on Docsity!

Spring 09 CSCI 4430, A Milanova/BG Ryder 1

Announcements

 Project 2

 Due today

 HW

 Will be posted on Friday, April 3

Spring 09 CSCI 4430, A Milanova/BG Ryder 2

Last Class

 Lambda Calculus

 Applied lambda calculus

 Typed lambda calculus

 Types

 Types and type systems

 Type checking (started)

Spring 09 CSCI 4430, A Milanova/BG Ryder 3

Types and Type Systems

 What is a type?

 A set of values and the valid operations on those values  E.g., Integers: +, -, *, /, <, <=, ==, >=, >  Provide semantic correctness checking

 What is a type system?

 A mechanism to define types and associate them with certain language constructs  Type expressions  Type judgments  (Complex) algorithm for associating types with constructs  Additional rules for type equivalence, type compatibility

Spring 09 CSCI 4430, A Milanova/BG Ryder 4

Type Checking

 The process of ensuring that the program obeys

the language type rules

 Strongly typed languages

 Term applied to (mostly) statically typed languages  Scott: A language is said to be strongly typed if the type system prohibits application of an operation on an object that is not intended to support that operation  Cardelliโ€™s type terminology:  Forbidden error: the occurrence of one of a predetermined class of execution errors (e.g., logical-not applied to 3)  A language is said to be strongly typed if it prohibits the execution of one of the predetermined forbidden errors

5

Type Checking (ii)

 Design choices: weak vs. strong typing

 One forbidden error: applying a method m on

an object of class A that does not provide

method m

void x = (void ) new A; B q = (B ) x; // a safe downcast? int case3 = q->foo(66);

C++ (weakly typed): q->foo(66) executesโ€ฆ Java (strongly typed): q.foo(66) would never execute

A

B

foo()

foo() foo(int)

Spring 09 CSCI 4430, A Milanova/BG Ryder 6

Type Checking (iii)

 Design choices: static vs. dynamic checks

 Another forbidden error: indexing out of bounds

 a[i]  Weak typing โ€“ C++  0<=i and **i Spring 09 CSCI 4430, A Milanova/BG Ryder 7

Type Checking (iv)

 Statically-typed languages

 Typically require type annotations (e.g., A a, List l)  Type checking is performed (mostly) statically (that is, at compile-time)  Ada, Pascal, Java, C++  A form of early binding

 Dynamically-typed languages

 Typically require no type annotations!  All type checking is performed dynamically (at run-time)  Smalltalk, Lisp and Scheme, Python  A form of late binding

Types

Read: Scott, Chapter 7.2-7.

8

Spring 09 CSCI 4430, A Milanova/BG Ryder 9

Topics

 Types

 Type checking (continue)

 Type equivalence  Type compatibility

 Primitive types

 Composite types

 Structures and variants  Arrays  Strings

Spring 09 CSCI 4430, A Milanova/BG Ryder 10

Type Equivalence and Type Compatibility

 Questions:

e := expression Are e and expression of same type?

a + b Are a and b of types that support +?

foo(arg1, arg2, โ€ฆ,argN) Do the types of the arguments match the types of the formal parameters?

Spring 09 CSCI 4430, A Milanova/BG Ryder 11

Type Equivalence

 Two principle ways of defining type

equivalence

 Structural equivalence: based on โ€œshapeโ€

 Roughly, two types are the same if they have the same components

 Name equivalence: based on lexical occurrence

of the type name

 Roughly, each type definition introduces a new type

Spring 09 CSCI 4430, A Milanova/BG Ryder 12

Structural equivalence

 A type name is structurally equivalent to

itself

 Two types are structurally equivalent if they

are formed by applying the same type

constructor to two structurally equivalent

types

 After type declaration type n = T the type

name n is structurally equivalent to T

19

Type Equivalence in C (iv)

 C uses structural equivalence for everything except unions and structs, for which it uses name equivalence

*struct A struct B { char x; { char x; int y; int y; } } typedef struct A C; typedef C P; typedef struct B Q; typedef struct A R; typedef int Age; int (F) (int); Age (G) (Age); Spring 09 CSCI 4430, A Milanova/BG Ryder^20

Type Equivalence in C (v)

int main(){

**struct B { char x; int y;}; typedef struct B A; struct { A a; A *next;} aa; struct { struct B a; struct B next;} bb; struct { struct B a; struct B next;} cc;

A a; struct B b; a = b; aa = bb; bb = cc; }

Spring 09 CSCI 4430, A Milanova/BG Ryder 21

Type Conversion

 Implicit conversion - coercion

 In C, mixed mode numerical operations

 double d,e;โ€ฆ e=d+2; //2 coerced to 2.

 Usually can use widening or conversion without

loss of precision

 integer โ†’ double, float โ†’ double  But real โ†’ int may lose precision and therefore cannot be coerced!

 Cannot coerce user-defined types or structures

Spring 09 CSCI 4430, A Milanova/BG Ryder 22

Type Conversion (ii)

 Explicit conversion

 In Pascal, can explicitly convert types which may lose precision (narrowing)  round(s) real โ†’ int by rounding  trunc(s) real โ†’ int by truncating  In C, type casting typically is explicit conversion  dqstr((double) n) where n is declared to be an int  **freelist s; ... (char )s; forces s to be considered as pointing to a char for the purposes of pointer arithmetic

Spring 09 CSCI 4430, A Milanova/BG Ryder 23

Overloading Operators

 Primitive form of polymorphism

 An operator allows operands of more than one type, in different contexts

 Examples

 Addition operator  Integer addition: 2+3 is 5  Real addition: 2.+3. is 5.  String concatenation: โ€œabcโ€+โ€defโ€ is โ€œabcdefโ€  Comparison operator  Integer comparison: 2 == 3  String comparison: โ€œabcโ€ == โ€œdefโ€

Spring 09 CSCI 4430, A Milanova/BG Ryder 24

Primitive Types

 Design choices

 Boolean: use integer 0/non-0 vs. true/false

 char[] vs. String type

 Implementation issues: representation in

the machine

 Integer

 Length fixed by standards or implementation (portability issues)  Multiple lengths (C: short, int, long)  Signs

 Float/real (all issues of integers plus)

 Should value comparison be allowed?  Representation: sign(1 bit)/mantissa(23 bits)/exponent(8 bits)

Spring 09 CSCI 4430, A Milanova/BG Ryder 25

Composite Types: Structure (Record)

 Heterogeneous collections of fields

 Operations

 Selection through field names (s.num, p->next)  Assignment  Example: structures in C *typedef struct cell listcell; struct cell { int num; listcell next; } s,t; s.num = 0; s.next = 0; t = s; Spring 09 CSCI 4430, A Milanova/BG Ryder 26

Structure (ii)

 Definition of type. What is part of the type?

 order/type of fields  name/type of fields  order/name/type of fields

 Implementation issues: memory layout

 Successive memory locations at offset from first byte  Sometimes packing needed for alignment typedef struct { char name[10]; int age; } Person;

Person p;

name

age

4 bytes/32 bits

โ€œholesโ€

Spring 09 CSCI 4430, A Milanova/BG Ryder 27

Unions (Variant)

 Allow a collection of alternative fields; only one

alternative is valid during execution

 Fortran: equivalence  Algol68 and C: unions  Pascal: variant records

 Problem: how can we assure type-safety?

 Pascal and C are not type-safe  Algol68 is type-safe! Uses run-time checks

 Usually alternatives use same storage

 Mutually exclusive value access

Spring 09 CSCI 4430, A Milanova/BG Ryder 28

Unions (ii)

 Example: unions in C

union data { int k; char c; } d1,d2;  Operations  Assignment d1.k=3; d2=d1; d2.c=โ€˜bโ€™;  Type checking if (n>0) d1.k=5 else d1.c=โ€˜aโ€™; if (d1.k<10)โ€ฆ/meaningful?

Spring 09 CSCI 4430, A Milanova/BG Ryder 29

Pascal variant record

program main(input,output); type paytype = (salaried,hourly); var employee : record id : integer; dept: integer; age : integer; case payclass: paytype of salaried: (monthlyrate real; startdate : integer); hourly: (rateperhour : real; reghours : integer; overtime : integer); end;

begin employee.id:=001234; employee.dept:=12; employee.age:=38; employee.payclass:=hourly; employee.rateperhour:= 2.75; employee.reghours := 40; employee.overtime:=3; writeln(employee.rateperhour, employee.reghours, employee.overtime); {this should bomb as there is no monthlyrate because payclass=hourly} writeln(employee.monthlyrate);

Type tag

Output: 2.750000E+00 40 3 2.750000E+00 Spring 09 CSCI 4430, A Milanova/BG Ryder^30

Pascal variant record (ii)

type paytype = (salaried,hourly); var employee : record id : integer; dept: integer; age : integer; case payclass: paytype of salaried:( monthlyrate :real; startdate : integer); hourly: ( rateperhour : real; reghours : integer; overtime : integer); end;

employee.payclass:=salaried; employee.monthlyrate:=575.0; employee.startdate:=13085; {this should bomb as there are no rateperhour, etc. because payclass=salaried} writeln(employee.rateperhour, employee.reghours employee.overtime); writeln(employee.monthlyrate); end.

Output: 5.750000E+02 13085 3 5.750000E+

Spring 09 CSCI 4430, A Milanova/BG Ryder 37

Example: Array Addressing (ii)

 Memory is a sequence of contiguous locations

 Two memory layouts for n-dimensional arrays:

 Row-major order and column-major order

 Row-major order:

 y[0,0], y[0,1], y[0,2], โ€ฆ, y[1,], y[2,],โ€ฆ**

 y[low1:hi1,low2:hi2] in Algol68, location

y[j,k] is

addr( y[low1,low2] ) + ( hi2-low2 +1)E( j-low1 )+( k-low2 )*E #locs per row #rows in front # elements in row j in of row j front of element [j,k] Spring 09 CSCI 4430, A Milanova/BG Ryder 38

Example: Array Addressing (iii)

Consider y[0:2, 0:5] int matrix. Assume row-major order and find the address of y[1,3]. address of y[1,3] = addr( y[0,0] )+(5-0+1)4(1-0)+(3-0)* 6 elements per row 1 row before row 1 3 elements in row 1 before 3 = addr( y[0,0] )+24+ = addr( y[0,0] )+

 Analogous formula holds for column-major order

Spring 09 CSCI 4430, A Milanova/BG Ryder 39

Composite Types: String

 Two choices

 Include Strings type (Algol68, Java) or

 Build a string as an array from char (Pascal, C)

 Choice dictates

 There are String operations in the PL or

 There are calls to a standard library of string

manipulation functions

Spring 09 CSCI 4430, A Milanova/BG Ryder 40

String: String type

 Length

 Can be declared with a maximum length  Can have unlimited length (Algol68)

 Usually allow lexicographic comparison

 Operations allow string decomposition into

substrings and combination (PL/I examples)

 โ€œagoโ€|โ€œbeโ€ โ†’โ†’โ†’โ†’ โ€œagobeโ€, concatenation  index(โ€œabcโ€,โ€xyabcdโ€) โ†’โ†’โ†’โ†’ 2, returns start position in 2nd string argument of the 1st string argument  substr(a,j,k) returns substring of a starting at position j of k characters in length

Spring 09 CSCI 4430, A Milanova/BG Ryder 41

String: String Built as Char Array

 Pascal: strings are arrays of char

 Max length fixed at compile-time  packed array[1..n] of char  Used in assignments and relational compares  Operations: pack and unpack to get at individual chars with function call overhead

 C: string is sequence of zero or more charโ€™s

followed by a โ€œ\0โ€

 Length is number of charโ€™s contained ( strlen )  strcpy(), strcat(), strstr(), etc.