chapter 4 of programming languages by ravi sethi

22
Chapter 4 Chapter 4 of Programming of Programming Languages Languages by by Ravi Sethi Ravi Sethi

Upload: walter-payne

Post on 20-Jan-2016

237 views

Category:

Documents


9 download

TRANSCRIPT

Page 1: Chapter 4 of Programming Languages by Ravi Sethi

Chapter 4Chapter 4of Programming of Programming

LanguagesLanguagesbyby

Ravi SethiRavi Sethi

Page 2: Chapter 4 of Programming Languages by Ravi Sethi

TYPES:DATA REPRESENTATIONTYPES:DATA REPRESENTATION

• The Role of TypesThe Role of Types

• Basic TypesBasic Types

• Arrays: Sequences of ElementsArrays: Sequences of Elements

• Records: Named FieldsRecords: Named Fields

• Unions and Variant RecordsUnions and Variant Records

• SetsSets

• Pointers: Efficiency and Dynamic AllocationPointers: Efficiency and Dynamic Allocation

• Two String TablesTwo String Tables

• Types and Error CheckingTypes and Error Checking

Page 3: Chapter 4 of Programming Languages by Ravi Sethi

THE ROLE OF TYPESTHE ROLE OF TYPES• Data objects and Data representation Data objects and Data representation

Objects in an application have corresponding representations Objects in an application have corresponding representations in a program.in a program.

Example: correspondence between application and Example: correspondence between application and programprogram

application programapplication program

data January 31 31 data January 31 31

data May 6 126data May 6 126

variable d n(integer #)variable d n(integer #)

operation tomorrow (d) n+1operation tomorrow (d) n+1

• Values and Their TypesValues and Their Types

1. Basic type1. Basic type

2. Constructed type2. Constructed type

Page 4: Chapter 4 of Programming Languages by Ravi Sethi

THE ROLE OF TYPES(cont’d)THE ROLE OF TYPES(cont’d)

• Type ExpressionType Expression

a) Describes how a data representation is built upa) Describes how a data representation is built up

B) Can be used toB) Can be used to

1. Represent data objects1. Represent data objects

2. Lay out values in the underlying machine2. Lay out values in the underlying machine

3. Check that operators are applied properly within 3. Check that operators are applied properly within expressionexpression

• Static Layout DecisionStatic Layout Decision

(next slide) (next slide)

• A Preview of Type Names, Arrays, and RecordsA Preview of Type Names, Arrays, and Records

1. Type names: boolean, char, integer, real1. Type names: boolean, char, integer, real

2. Arrays: a sequence of elements2. Arrays: a sequence of elements

3. Records: a set of components, each with its own 3. Records: a set of components, each with its own typetype

Page 5: Chapter 4 of Programming Languages by Ravi Sethi

THE ROLE OF TYPES(cont’d)THE ROLE OF TYPES(cont’d)

Page 6: Chapter 4 of Programming Languages by Ravi Sethi

BASIC TYPESBASIC TYPES

• Enumeration : a finite sequence of names written between Enumeration : a finite sequence of names written between parenthesesparentheses

type type day = (Mon, Tue, Wed, Thu, Fir, Sat, Sun);day = (Mon, Tue, Wed, Thu, Fir, Sat, Sun);

• Integers and RealsIntegers and Reals

• Short-Circuit Evaluation of Boolean ExpressionsShort-Circuit Evaluation of Boolean Expressions

Example : While (i >= 0 && x != A[ i ]) i = i-1 ;Example : While (i >= 0 && x != A[ i ]) i = i-1 ;

• Subranges : a special case of basic types that restrict the range Subranges : a special case of basic types that restrict the range of values of an existing type - weekends, weekdaysof values of an existing type - weekends, weekdays

Page 7: Chapter 4 of Programming Languages by Ravi Sethi

BASIC TYPES (cont’d)BASIC TYPES (cont’d)

• Programming Style: Characters and Type ConversionProgramming Style: Characters and Type Conversion

Example :Example :

C : characters are implicitly coerced to integersC : characters are implicitly coerced to integers

int c;int c;

c = getchar(); -> coerced to an intc = getchar(); -> coerced to an int

Pascal : Conversion will be done explicitly Pascal : Conversion will be done explicitly

c = chr(ord(c))c = chr(ord(c))

i = ord(chr(i))i = ord(chr(i))

Page 8: Chapter 4 of Programming Languages by Ravi Sethi

ARRAYS: SEQUENCES OF ELEMENTSARRAYS: SEQUENCES OF ELEMENTS

• Efficient access and storage allocationEfficient access and storage allocation

• Indexed by integers or enumerationsIndexed by integers or enumerations

• Array layoutArray layout

1. Elements appear in consecutive location in the underlying 1. Elements appear in consecutive location in the underlying machinemachine

2. Elements can be computed in two parts2. Elements can be computed in two parts

a) Pre-computationa) Pre-computation

b) Run timeb) Run time

3. Arrays of Arrays : row-major layout, column-major layout3. Arrays of Arrays : row-major layout, column-major layout

Page 9: Chapter 4 of Programming Languages by Ravi Sethi

ARRAYS: SEQUENCES OF ELEMENTS ARRAYS: SEQUENCES OF ELEMENTS (cont’d)(cont’d)

• Array BoundsArray Bounds

a) Computed at compile time (Static evaluation)a) Computed at compile time (Static evaluation)

b) Computed at run time (Dynamic evaluation)b) Computed at run time (Dynamic evaluation)

• Array Values and Initialization : a sequence of values for array Array Values and Initialization : a sequence of values for array elementselements

Example: int coin[] = { 1, 5, 10, 25, 50, 100 }; Example: int coin[] = { 1, 5, 10, 25, 50, 100 };

Page 10: Chapter 4 of Programming Languages by Ravi Sethi

RECORDS: NAMED FIELDSRECORDS: NAMED FIELDS

• A record type is a templateA record type is a template

• A Variable declaration allocates storageA Variable declaration allocates storage

• Operations on RecordsOperations on Records

Example : z. re := x. re + y. reExample : z. re := x. re + y. re

• A comparison of Arrays and RecordsA comparison of Arrays and Records

arraysarrays recordsrecords

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

component typescomponent types homogeneous homogeneous heterogeneousheterogeneous

component selectors expressions evaluatedcomponent selectors expressions evaluated names names known at known at

at run time compile timeat run time compile time

Page 11: Chapter 4 of Programming Languages by Ravi Sethi

UNIONS AND VARIANT RECORDSUNIONS AND VARIANT RECORDS

• Union : a special case of a variant record with an Union : a special case of a variant record with an empty common partempty common part

• Variant record : a part common to all records of that Variant record : a part common to all records of that type and a variant parttype and a variant part

• figure 4.7 (next slide)figure 4.7 (next slide)

Page 12: Chapter 4 of Programming Languages by Ravi Sethi

UNIONS AND VARIANT RECORDS(cont’d)UNIONS AND VARIANT RECORDS(cont’d)

Page 13: Chapter 4 of Programming Languages by Ravi Sethi

UNIONS AND VARIANT RECORDS(cont’d)UNIONS AND VARIANT RECORDS(cont’d)

• Layout of Variant RecordsLayout of Variant Records

1. Fixed Part1. Fixed Part

2. Tag Field2. Tag Field

3. Variant Part3. Variant Part

• Variant Records compromise type safetyVariant Records compromise type safety

Page 14: Chapter 4 of Programming Languages by Ravi Sethi

SETSSETS

• Set Values:in Pascal, All elements must be of the same Set Values:in Pascal, All elements must be of the same simple type simple type

• Set Types: Type set of S represents subsets of SSet Types: Type set of S represents subsets of S

Example: var A : set of [1..3]Example: var A : set of [1..3]

A can denote one of the following sets:A can denote one of the following sets:

[ ],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3][ ],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]

• A set of n elements: implemented as a bit vector of A set of n elements: implemented as a bit vector of length nlength n

• The basic operation on set is a membership testThe basic operation on set is a membership test

Page 15: Chapter 4 of Programming Languages by Ravi Sethi

POINTERS: EFFICIENCY AND DYNAMIC POINTERS: EFFICIENCY AND DYNAMIC ALLOCATIONALLOCATION

• More efficient to move or copy a pointer to the data More efficient to move or copy a pointer to the data structurestructure

• Dynamically Implemented to use in data structureDynamically Implemented to use in data structure

• First-class citizensFirst-class citizens

• Pointer type must be declared before usedPointer type must be declared before used

• Dereferencing operation : indirect accessDereferencing operation : indirect access

Example Pascal: dynamic allocation on the heap, Example Pascal: dynamic allocation on the heap, dereferencing, assignment, equality testing, dereferencing, assignment, equality testing, deallocationdeallocation

• Serve as links between cells (linked lists)Serve as links between cells (linked lists)

• Type and layout of storage are known statically before a Type and layout of storage are known statically before a program runsprogram runs

Page 16: Chapter 4 of Programming Languages by Ravi Sethi

POINTERS: EFFICIENCY AND DYNAMIC POINTERS: EFFICIENCY AND DYNAMIC ALLOCATION(cont’d)ALLOCATION(cont’d)

• The pointer operations affect access to storage The pointer operations affect access to storage

• Dangling pointer is a pointer to storage that is being used for Dangling pointer is a pointer to storage that is being used for another purpose (deallocate the storage, but the reference another purpose (deallocate the storage, but the reference to the pointer is still there)to the pointer is still there)

• Pascal restricts pointer operations (only new and dispose); C Pascal restricts pointer operations (only new and dispose); C stresses flexibility stresses flexibility

• Rearranged inexpensivelyRearranged inexpensively

Page 17: Chapter 4 of Programming Languages by Ravi Sethi

TWO STRING TABLESTWO STRING TABLES

• From a distance, types in Pascal and C are very similar, both have arrays, From a distance, types in Pascal and C are very similar, both have arrays, records and pointers. Differences in the treatment of pointers, lead to records and pointers. Differences in the treatment of pointers, lead to differences in style. The variable-length string application is famous and is differences in style. The variable-length string application is famous and is used to show the differences (section 4.8)used to show the differences (section 4.8)

• PascalPascal

• TeXTeX

• trofftroff

• WordWord

• all the words are in a pool (buffer), the words are index through an array called all the words are in a pool (buffer), the words are index through an array called start which contains the beginning position of the word in the pool starting at 0 start which contains the beginning position of the word in the pool starting at 0 so start[0] = 0 and pool[start[0]] is the ’T’so start[0] = 0 and pool[start[0]] is the ’T’

Indirect access through an arrayIndirect access through an array

Integers as pointers - disadvantage compiler cannot check that it is a character Integers as pointers - disadvantage compiler cannot check that it is a character

Page 18: Chapter 4 of Programming Languages by Ravi Sethi

TWO STRING TABLESTWO STRING TABLES

• From Yacc - Yet another Compiler CompilerFrom Yacc - Yet another Compiler Compiler

• start is the actual pointer address in pool not just an indexstart is the actual pointer address in pool not just an index

• CC

1. Indirect access through pointers1. Indirect access through pointers

2. Array name : pointer to a zeroth element - operations on 2. Array name : pointer to a zeroth element - operations on pointers in C allow successive characters in a string to be pointers in C allow successive characters in a string to be accessedaccessed

3. Dereferencing and yielding operators3. Dereferencing and yielding operators

Example: p = &x;Example: p = &x;

*p = *p + 1; is same as x = x + 1;*p = *p + 1; is same as x = x + 1;

Page 19: Chapter 4 of Programming Languages by Ravi Sethi

TYPES AND ERROR CHECKINGTYPES AND ERROR CHECKING• Types extend from values to expressions, the type of an expression Types extend from values to expressions, the type of an expression

x + y can be inferred from the types x and yx + y can be inferred from the types x and y

• Types of variable bindingsTypes of variable bindings

1. Static or early bindings 1. Static or early bindings

2. Dynamic or late bindings2. Dynamic or late bindings

Pascal has static bindings of types and dynamic Pascal has static bindings of types and dynamic bindings of values to variables. Lisp has dynamic binding of both bindings of values to variables. Lisp has dynamic binding of both values and typesvalues and types

• Type systems : a set of rulesType systems : a set of rules

• Basic rule of type checking Basic rule of type checking

1. Overloading : Multiple Meanings1. Overloading : Multiple Meanings

2. Coercion : conversion from one type to another2. Coercion : conversion from one type to another

3. Polymorphism : parameterized type3. Polymorphism : parameterized type

Page 20: Chapter 4 of Programming Languages by Ravi Sethi

TYPES AND ERROR CHECKING(cont’d)TYPES AND ERROR CHECKING(cont’d)

• Type names and type equivalenceType names and type equivalence

Example :Example :

x, y : array [0..9] of integerx, y : array [0..9] of integer

z : array [0..9] of integerz : array [0..9] of integer

In Pascal, x and y have the same type, but z does notIn Pascal, x and y have the same type, but z does not

* Structural Equivalence* Structural Equivalence

1. A type name is structurally equivalent to itself1. A type name is structurally equivalent to itself

2. Two types are formed by applying the same type constructor2. Two types are formed by applying the same type constructor

3. After a type declaration, type n = T3. After a type declaration, type n = T

Page 21: Chapter 4 of Programming Languages by Ravi Sethi

TYPES AND ERROR CHECKING(cont’d)TYPES AND ERROR CHECKING(cont’d)

* Forms of Name Equivalence* Forms of Name Equivalence

1. Pure name equivalence1. Pure name equivalence

2. Transitive name equivalence, type S = integer; T = S; U = integer;2. Transitive name equivalence, type S = integer; T = S; U = integer;

3. Type expression equivalence 3. Type expression equivalence

* Type Equivalence - sometimes left ambiguous in Pascal, sometimes given rules like * Type Equivalence - sometimes left ambiguous in Pascal, sometimes given rules like Modula-2 Modula-2

* Circular Types : linked data structures give rise to recursive or circular* Circular Types : linked data structures give rise to recursive or circular

types types struct x {struct x {

int p;int p;

struct x *next;struct x *next;

};};

Page 22: Chapter 4 of Programming Languages by Ravi Sethi

TYPES AND ERROR TYPES AND ERROR CHECKING(cont’d)CHECKING(cont’d)

• Static and Dynamic CheckingStatic and Dynamic Checking

1. Type error occurs if an operation is improperly 1. Type error occurs if an operation is improperly appliedapplied

2. Programs are checked statically2. Programs are checked statically

3. Dynamic checking is done during program 3. Dynamic checking is done during program executionexecution

4. Strong type ensures freedom from type errors4. Strong type ensures freedom from type errors