ICS 313 1 2 Lecture #7 Lecture #7 Data Types Data Types - - PDF document

ics 313
SMART_READER_LITE
LIVE PREVIEW

ICS 313 1 2 Lecture #7 Lecture #7 Data Types Data Types - - PDF document

ICS 313 1 2 Lecture #7 Lecture #7 Data Types Data Types Programming Language Theory Programming Language Theory Primitive Data Types ICS313 ICS313 Character String Types Fall 2007 Fall 2007 User-Defined Ordinal Types


slide-1
SLIDE 1

ICS 313 1

1

Programming Language Theory Programming Language Theory ICS313 ICS313 Fall 2007 Fall 2007

Nancy E. Reed nreed@hawaii.edu

2

Lecture #7 Lecture #7 Data Types Data Types Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer Types Ref: Chapter 6 in text

3

Memory Layout : Overview Memory Layout : Overview

  • Text

Text: : code, constant data

  • Data

Data: :

  • initialized global & static

variables

  • global & static variables – 0

initialized or un-initialized (blank)

  • Heap

Heap: : dynamic memory

  • Stack

Stack: : dynamic - local variables

xxxxxxxx Text Data Heap Stack Stack

4

Data Types Data Types

Data type - defines

  • a collection of data objects and
  • a set of predefined operations on those objects

Evolution of data types:

  • FORTRAN I (1957) - INTEGER, REAL, arrays
  • Ada (1983) - User can create unique types and system enforces the

types

Descriptor - collection of the attributes of a variable Design issues for all data types:

  • 1. Syntax of references to variables
  • 2. Operations defined and how to specify

What is the mapping to computer representation?

5

Primitive Data Types Primitive Data Types Not defined in terms of other data types

  • 1. Integer
  • Almost always an exact reflection of the

hardware, so the mapping is trivial

  • There may be as many as eight different integer

types in a language (size, signed/unsigned)

  • 2. Floating Point
  • Model real numbers, but only as approximations
  • Languages for scientific use support at least two

floating-point types; sometimes more

  • Usually exactly like the hardware, but not always

6

IEEE Floating Point Format Standards IEEE Floating Point Format Standards

Single precision Double precision

slide-2
SLIDE 2

ICS 313 2

7

Primitive Data Types Primitive Data Types

  • 3. Decimal – base 10
  • For business applications (usually money)
  • Store a fixed number of decimal digits - coded, not as

floating point.

  • Advantage: accuracy – no round off error, no exponent,

binary representation can’t do this

  • Disadvantages: limited range, takes more memory
  • Example: binary coded decimal (BCD) – use 4 bits per

decimal digit – takes as much space as hexadecimal

  • 4. Boolean (true/false)
  • Could be implemented as bits, but often as bytes or words
  • Advantage: readability
  • 5. Character
  • Stored as numeric codes (e.g., ASCII, EBCDIC, Unicode)

8

Character String Types Character String Types Sequences of characters Design issues:

  • 1. Is it a primitive type or just a special kind of array?
  • 2. Is the length of objects static or dynamic?

Operations:

  • Assignment
  • Comparison (=, >, etc.)
  • Concatenation
  • Substring reference
  • Pattern matching

9

Character String Types Character String Types

Pascal

  • Not primitive type;
  • assignment and comparison only (of packed arrays)

Ada, FORTRAN 90, and BASIC

  • Somewhat primitive
  • Assignment, comparison, concatenation, substring reference
  • FORTRAN has an intrinsic for pattern matching

e.g. (Ada)

N := N1 & N2 (concatenation) N(2..4) (substring reference) C and C++

  • Not primitive
  • Use char arrays and a library of functions that provide operations

10

Character String Type Examples Character String Type Examples

Java

  • String class (not arrays of char)
  • Objects cannot be changed (immutable)
  • StringBuffer is a class for changeable string objects

Perl and JavaScript

  • Patterns are defined in terms of regular expressions
  • A very powerful facility
  • e.g.,

/[A-Za-z][A-Za-z\d]+/ SNOBOL4 (string manipulation language)

  • Primitive string type
  • Many operations, including elaborate pattern matching

predefined

11

Character String Length Options Character String Length Options

  • 1. Static - FORTRAN 77, Ada, COBOL

e.g. (FORTRAN 90) CHARACTER (LEN = 15) NAME;

  • 2. Limited Dynamic Length - C and C++

actual length is indicated by a null character

  • 3. Dynamic - SNOBOL4, Perl,

JavaScript, Common Lisp

12

Character String Type Evaluation Character String Type Evaluation

Strings aid writability and readability Static length primitive type

  • Inexpensive to provide, why not include them?

Dynamic length

  • Weigh flexibility vs. cost to provide

Implementation:

  • Static length - compile-time descriptor
  • Limited dynamic length - may need a run-time descriptor

for length (but not in C and C++)

  • Dynamic length - need run-time descriptor; allocation/de-

allocation is the biggest implementation problem

slide-3
SLIDE 3

ICS 313 3

13

Character String Types Character String Types

Compile-time descriptor for static strings Run-time descriptor for limited dynamic strings

*

14

User User-

  • Defined Ordinal Types

Defined Ordinal Types

Ordinal type - the range of possible values = the set of positive integers (or can be easily associated with them) Enumeration Types - user enumerates all possible values, which are symbolic constants

  • Represented with ordinal numbers

Design Issues

  • Can symbolic constants be in more than one type definition?
  • hair = {red,brown,blonde},
  • cat = {brown,striped,black}
  • Can they be read/written as symbols?
  • Allowed as array indices, subranges?

15

User User-

  • Defined Ordinal Type Examples

Defined Ordinal Type Examples

Pascal

  • cannot reuse values, no input or output of values
  • can be used for array subscripts, for variables, case

selectors

  • can be compared

Ada

  • constants can be reused (overloaded literals)
  • can be used as in Pascal; CAN be input and output

C and C++ -

  • like Pascal, except they can be input and output as integers

Java does not include an enumeration type,

  • but provides the Enumeration interface

16

Evaluation of User Evaluation of User-

  • Defined Ordinal Types

Defined Ordinal Types

  • 1. Aid to readability
  • e.g. no need to code a color as a number
  • 2. Aid to reliability
  • e.g. compiler can check
  • 3. Operations specified (don’t allow

colors to be added, for example)

  • 4. Ranges of values can be checked
  • 1. E. g. if you have 7 colors, code them as integers

(1..7), 9 is a legal integer (and thus a `legal color’)!

17

Subrange Subrange Types Types

An ordered contiguous subsequence of an ordinal type Design Issue: How can they be used? Pascal

  • Sub-range types behave as their parent types; can be used as for

variables and array indices

e.g. type pos = 0 .. MAXINT; Ada

  • Subtypes are not new types, just constrained existing types (so they are

compatible); can be used as in Pascal, plus case constants

e.g. subtype POS_TYPE is INTEGER range 0..INTEGER'LAST;

18

Evaluation and Implementation of Evaluation and Implementation of Sub Sub-

  • range Types

range Types

Aid to readability Reliability - restricted ranges adds error detection Enumeration types are implemented as integers Sub-range types are the parent types with code inserted (by the compiler) to restrict assignments to sub-range variables

slide-4
SLIDE 4

ICS 313 4

19

Arrays Arrays

  • An aggregate of homogeneous data elements
  • individual elements are identified by their position relative to the

first element (index)

  • Design issues

1. What types are legal for subscripts? 2. Range checked on subscripting expressions in references? 3. When does binding of subscript ranges happen? 4. When does allocation take place? 5. What is the maximum number of subscripts? 6. Can array objects be initialized? 7. Are any kind of slices allowed?

20

Array Indexing Array Indexing

Mapping from indices to elements

map (array_name, index_value_list) → an element

Index Syntax

  • FORTRAN, PL/I, Ada use parentheses
  • Most other languages use brackets

Subscript types

  • FORTRAN, C - integer only
  • Pascal - any ordinal type (integer, boolean, char, enum)
  • Ada - integer or enum (includes boolean and char)
  • Java - integer types only

21

Static and Fixed Stack Dynamic Arrays Static and Fixed Stack Dynamic Arrays Type based on subscript binding and binding to storage

  • 1. Static - range of subscripts and storage

bindings are static

e.g. FORTRAN 77, some arrays in Ada

  • Advantage: execution efficiency (no allocation or de-

allocation)

  • 2. Fixed stack dynamic - range of subscripts is

statically bound, but storage is bound at elaboration time

  • e.g. Most Java locals, and C locals that are not static
  • Advantage: space efficiency

22

Dynamic Arrays Dynamic Arrays

  • 3. Stack-dynamic - range and storage are

dynamic, but fixed from then on for the variable’s lifetime

  • Advantage: flexibility - size need not be known until the array is about

to be used

  • 4. Heap-dynamic - subscript range and storage

bindings are dynamic and not fixed

e.g. (FORTRAN 90)

INTEGER, ALLOCATABLE, ARRAY (:,:) :: MAT

(Declares MAT to be a dynamic 2-dim array) In APL, Perl, and JavaScript, arrays grow and shrink as needed In Java, all arrays are objects (heap-dynamic)

23

Array Subscripts and Initialization Array Subscripts and Initialization

  • Number of subscripts
  • FORTRAN I allowed up to three
  • FORTRAN 77 allows up to seven
  • Others - no limit
  • Array Initialization
  • Usually just a list of values that are put in the array in the order in which the

array elements are stored in memory

Example Initialization 1. FORTRAN - uses the DATA statement, or in / ... / 2. C and C++ - put the values in braces;

  • int stuff [] = {2, 4, 6, 8};

3. Ada - positions for the values can be specified

  • SCORE : array (1..14, 1..2) :=

(1 => (24, 10), 2 => (10, 7), 3 =>(12, 30), others => (0, 0));

4. Pascal does not allow array initialization

24

Built Built-

  • in Array Operations

in Array Operations

  • 1. APL - many, (text p. 240-241)
  • 2. Ada
  • Assignment; RHS can be an aggregate constant
  • r an array name
  • Catenation; for all single-dimensioned arrays
  • Relational operators (= and /= only)
  • 3. FORTRAN 90
  • Intrinsic definitions for a wide variety of array
  • perations (e.g., matrix multiplication, vector

dot product)

slide-5
SLIDE 5

ICS 313 5

25

Array Slices Array Slices

  • A slice is some substructure of an array;

nothing more than a referencing mechanism

  • Slices are only useful in languages that have

array operations 1. Example: FORTRAN 90 INTEGER MAT (1:4, 1:4) MAT(1:4, 1) - the first column MAT(2, 1:4) - the second row 2. Ada - single-dimensioned arrays only

LIST(4..10)

26

Example Slices in FORTRAN 90 Example Slices in FORTRAN 90

27

Implementation of Arrays Implementation of Arrays Access function maps subscript expressions to an address in the array Row major order (by rows) Column major order (by columns)

28

Locating an Element Locating an Element

I J Row major = (1,1) (1,2) (1,3) … (m, n-1) (m,n) where (I,j) = (i-1) * n + j Column major = (1,1) (1,2) (1,3) … (m-1, n) (m, n) Where (I,j) = (j-1) * m + i

29

Array Compile Array Compile-

  • Time Descriptors

Time Descriptors

Single-dimensioned array Multi-dimensional array

30

Associative Arrays Associative Arrays Associative array –

  • an unordered collection of data elements that are
  • indexed by keys
  • Perl – example next
  • Implemented using hash tables

Design Issues

  • What is the form of references to elements?
  • Is the size static or dynamic?
slide-6
SLIDE 6

ICS 313 6

31

Associative Arrays Associative Arrays Structure and Operations in Perl

  • Names begin with %
  • Literals are delimited by parentheses

e.g., declaration with initialization %hi_temps = ("Monday" => 77, "Tuesday" => 79,…);

  • Subscripting is done using braces and keys

e.g., access using key $hi_temps{"Wednesday"} = 83;

  • Elements can be removed with delete

e.g., delete using key delete $hi_temps{"Tuesday"};

32

Records Records Record aggregate of data elements

  • Possibly heterogeneous
  • Individual elements/slots are identified by names
  • Elements in same fixed order for all records

Design Issues:

  • 1. What is the form of references?
  • 2. What unit operations are defined?

33

Record References Record References Record Definition Syntax

  • COBOL uses level numbers to show nested

records; others use recursive definition

Record Field References

  • 1. COBOL

field_name OF record_name_1 OF ... OF record_name_n

  • 2. Others (dot notation)

record_name_1.record_name_2. ... record_name_n.field_name

34

Record References, cont. Record References, cont. Fully qualified references must include all record names Elliptical references allow leaving out record names as long as the reference is unambiguous Pascal provides a with clause to abbreviate references

35

Record Compile Record Compile-

  • Time Descriptor

Time Descriptor A compile-time descriptor for a record

36

Operations on Records Operations on Records

1. Assignment

  • Pascal, Ada, and C allow it if the types are identical
  • In Ada, the RHS can be an aggregate constant

2. Initialization

  • Allowed in Ada, using an aggregate constant
  • 3. Comparison
  • In Ada, = and /=; one operand can be an aggregate

constant

  • 3. MOVE CORRESPONDING
  • In COBOL - it moves all fields in the source record to

fields with the same names in the destination record

  • Note: the fields may not be in the same order in the different

record types!

slide-7
SLIDE 7

ICS 313 7

37

Comparing Records and Arrays Comparing Records and Arrays

  • 1. Access to array elements is slower than access to

record fields, because subscripts are dynamic (field names are static)

  • 2. Dynamic subscripts could be used with record

field access, but it would disallow type checking and it would be much slower

38

Unions Unions A union is a type whose variables are allowed to store different type values at different times during execution Discriminated union – has tags for indicating types for type checking Free union – no type checking is possible Design Issues for unions:

  • What kind of type checking, if any, must be done?
  • Should unions be integrated with records?

39

Examples of Unions Examples of Unions

  • 1. FORTRAN - with EQUIVALENCE
  • No type checking
  • 2. Pascal - both discriminated and non-

discriminated unions

40

Unions Unions

A discriminated union of three shape variables

  • determines which fields have data values

Common fields: Common fields: Different fields: Different fields:

41

Type Checking of Unions Type Checking of Unions Pascal’s can’t be type checked effectively:

  • a. User can create inconsistent unions (because the tag can be

individually assigned)

var blurb : intreal; x : real; blurb.tagg := true; { an integer } blurb.blint := 47; { ok } blurb.tagg := false; { it is a real } x := blurb.blreal; { assigns an integer to real }

  • b. The tag is optional!

Now, only the declaration and the second and last assignments are required to cause trouble!

42

Union Examples, cont. Union Examples, cont.

Ada - discriminated unions

Reasons they are safer than Pascal:

  • a. Tag must be present
  • b. It is impossible for the user to create an inconsistent

union because tag cannot be assigned by itself--All assignments to the union must include the tag value, because they are aggregate values

C and C++ - free unions (no tags)

  • Not part of their records
  • No type checking of reference

Java has neither records nor unions Evaluation - potentially unsafe in most languages (not Ada)

slide-8
SLIDE 8

ICS 313 8

43

Sets Sets Set type - stores unordered collections of distinct values from some ordinal type Operations:

  • Union
  • Intersection
  • Difference

Design Issue:

  • What is the maximum number of elements in any

set base type?

44

Pointers and References Pointers and References Pointers – access to dynamic storage

  • E.g. C/C++
  • The address of the data – a number
  • Flexible – you can do arithmetic on the addresses!
  • Few, if any safety checks on access using pointers

References – access to dynamic storage

  • E.g. Java, Lisp
  • Points to the data
  • Not possible to do arithmetic
  • Much safer

45

Heap Storage Heap Storage

xxxxxxxx Text Data Heap Stack Stack

Implicit Implicit – automatic Explicit Explicit – programmer’s instructions

46

Problems with Pointers Problems with Pointers

  • 1. Dangling pointers (dangerous)
  • A pointer points to a heap-dynamic variable that

has been de-allocated

  • Creating one (with explicit deallocation):
  • 1. Allocate a heap-dynamic variable and set a

pointer to point at it

  • 2. Set a second pointer to the value of the first

pointer

  • 3. De-allocate the heap-dynamic variable, using the

first pointer

47

Problems with Pointers, cont. Problems with Pointers, cont.

  • 2. Lost Heap-Dynamic Variables (wasteful)
  • A heap-dynamic variable that is no longer referenced

by any program pointer

  • Creating one:
  • 1. Pointer p1 is set to point to a newly created heap-

dynamic variable

  • 2. p1 is later set to point to another newly created heap-

dynamic variable

  • The process of losing heap-dynamic variables is

called memory leakage

48

Pascal and Ada Pointer Implementations Pascal and Ada Pointer Implementations

  • 1. Pascal: used for dynamic storage management
  • nly
  • Explicit dereferencing necessary (postfix ^)
  • Dangling pointers are possible (dispose)
  • Dangling objects are also possible
  • 2. Ada: a little better than Pascal
  • Some dangling pointers are disallowed because dynamic
  • bjects can be automatically de-allocated at the end of

pointer's type scope

  • All pointers are initialized to null
  • Similar dangling object problem (but rarely happens,

because explicit deallocation is rarely done)

slide-9
SLIDE 9

ICS 313 9

49

C and C++ Pointers C and C++ Pointers

  • 3. C and C++
  • Used for dynamic storage management and addressing
  • Explicit dereferencing and address-of operator
  • Domain type need not be fixed (void *)
  • void * - Can point to any type and can be type checked (cannot be

de-referenced)

  • Can do address arithmetic in restricted forms, e.g.:

float stuff[100]; float *p; p = stuff; *(p+5) is equivalent to stuff[5] and p[5] *(p+i) is equivalent to stuff[i] and p[i] (Implicit scaling)

50

Pointers Pointers The assignment operation j = *ptr

51

FORTRAN Pointers FORTRAN Pointers

4.FORTRAN 90 Pointers

  • Can point to heap and non-heap variables
  • Implicit dereferencing
  • Pointers can only point to variables that have the TARGET attribute
  • The TARGET attribute is assigned in the declaration, as in:

INTEGER, TARGET :: NODE

  • A special assignment operator is used for non-dereferenced references,

e.g.:

REAL, POINTER :: ptr (POINTER is an attribute) ptr => target (where target is either a pointer

  • r a non-pointer with the TARGET attribute)
  • This sets ptr to have the same value as target

52

C++ and Java Pointer/References C++ and Java Pointer/References

  • 5. C++ Reference Types
  • Constant pointers that are implicitly de-referenced
  • Used for parameters
  • Advantages of both pass-by-reference and pass-by-value

6. Java - Only references, no pointers

  • No pointer arithmetic
  • Can only point at objects (which are all on the heap)
  • No explicit deallocator (garbage collection is used)
  • Means there can be no dangling references
  • Dereferencing is always implicit

7. Lisp - ?

53

Pointer Representation and References Pointer Representation and References

  • Large computers use single values
  • Intel microprocessors use segment and offset
  • Dangling pointer problem solutions
  • 1. Tombstone: extra heap cell that is a pointer

to the heap-dynamic variable

  • The actual pointer variable points only at tombstones
  • When heap-dynamic variable is deallocated, tombstone

remains but set to nil

  • 2. Locks and keys: Pointer values are represented

as (key, address) pairs

  • Heap-dynamic variables are represented as variable plus

cell for integer lock value

  • When heap-dynamic variable allocated, lock value is

created and placed in lock cell and key cell of pointer

54

Implementing Dynamic Variables Implementing Dynamic Variables

slide-10
SLIDE 10

ICS 313 10

55

Heap Management Heap Management Single-size cells vs. variable-size cells Reference counters (eager approach) vs. garbage collection (lazy approach)

  • Reference counters: maintain a counter in every

cell that store the number of pointers currently pointing at the cell

  • Disadvantages: space required, execution time

required, complications for cells connected circularly

56

Heap Management Heap Management

Garbage collection

  • allocate and disconnect until all available cells allocated; then begin

gathering all garbage

Every heap cell has an extra bit used by collection algorithm

  • All cells initially set to garbage
  • All pointers traced into heap, and reachable cells marked as not

garbage

  • All garbage cells returned to list of available cells

Garbage collection

  • Disadvantages: when you need it most, it works worst (takes most

time when program needs most of cells in heap)

  • More efficient methods don’t wait until absolutely necessary

57

Marking Algorithm Marking Algorithm

58

Evaluation of Pointers Evaluation of Pointers

  • 1. Dangling pointers and dangling objects

are problems, as is heap management

  • 2. Pointers are like goto's--they widen the

range of cells that can be accessed by a variable

  • 3. Pointers or references are necessary for

dynamic data structures--so we can't design a language without them

59

Summary Summary Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer Types Ref: Chapter 6 in text