Programming Language Theory

1 Lecture #6 2 Data Types Theory ICS313 ƒ Primitive Data Types ƒ Character String Types ƒ User-Defined Ordinal Types ƒ Arrays and Associative Arrays ƒ Record Types Nancy E. Reed ƒ Union Types

[email protected] ƒ Pointer Types ƒ Type Checking ƒ Ref: Chapter 6 in Sebesta

3 4 Data Types Primitive Data Types ƒ Data type - defines Not defined in terms of other data types • a collection of data objects and • a set of predefined operations on those objects ƒ 1. Integer ƒ Evolution of data types: • Almost always an exact reflection of the • FORTRAN I (1957) - INTEGER, REAL, arrays hardware, so the mapping is trivial • Ada (1983) - User can create unique types and system enforces the types • There may be as many as eight different integer ƒ Descriptor - collection of the attributes of a variable types in a language (diff. size, signed/unsigned) ƒ Design issues for all data types: ƒ 2. Floating Point 1. Syntax of references to variables • Model real numbers, but only as approximations 2. Operations defined and how to specify • Languages for scientific use support at least two ƒ What is the mapping to computer representation? floating-point types; sometimes more • Usually exactly like the hardware, but not always

5 6 IEEE Floating Point Format Standards Primitive Data Types 3. Decimal – base 10 • For business applications (usually money) • Store a fixed number of decimal digits - coded, not as Single precision floating point. • Advantage: accuracy – no round off error, no exponent, binary representation can’t do this • Disadvantages: limited range, takes more memory Double precision • 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

1 Programming Language Theory

7 8 Character & String Types Character & String Types 5. Characters & Strings ƒ Ada, FORTRAN 90, and BASIC ƒ Stored as numeric codes (e.g., ASCII, EBCDIC, • Somewhat primitive Unicode) • Assignment, comparison, concatenation, substring ƒ String = Sequences of characters? reference • FORTRAN has an intrinsic for pattern matching ƒ Design issues: Example in Ada 1. Is it a primitive type or just an array of characters? 2. Is the length of strings static or dynamic? N := N1 & N2 (concatenation) ƒ Operations: N(2..4) (substring reference) • Assignment ƒ and C++ • Comparison (=, >, etc.) • Not primitive • Concatenation • Substring reference • Use char arrays and a library of functions that provide operations • Pattern matching

9 10 Character String Type Examples Character String Length Options ƒ Java 1. Static - FORTRAN 77, Ada, COBOL class (not arrays of ) • String char e.g. (FORTRAN 90) • Objects cannot be changed (immutable) CHARACTER (LEN = 15) NAME; • StringBuffer is a class for changeable string objects ƒ Perl and JavaScript 2. Limited Dynamic Length - C and C++ • Patterns are defined in terms of reggpular expressions actual length is indicated by a null • A very powerful facility • e.g., character /[A-Za-z][A-Za-z\d]+/ 3. Dynamic - SNOBOL4, Perl, ƒ SNOBOL4 (string manipulation language) JavaScript, Common Lisp • Primitive string type • Many operations, including elaborate pattern matching Dynamic storage, thus ‘no limit’ on predefined length

11 12 Character & String Type Evaluation Character & String Types ƒ Strings aid writability and readability ƒ Static length primitive type • Inexpensive to provide, why not include them? (in most languages) ƒ Dynamic length • Weig h fle xib ility vs. cost to p rov ide – flexib ility ove r * length of strings (don’t need to know at compile time), but need dynamic storage ƒ Implementation: • Static length - compile-time descriptor Compile-time Run-time descriptor • Limited dynamic length - may need a run-time descriptor descriptor for for length (but not in C and C++) for limited dynamic • Dynamic length - need run-time descriptor; allocation/de- static strings strings allocation is the biggest implementation task

2 Programming Language Theory

13 14 UserUser--DefinedDefined Ordinal Types UserUser--DefinedDefined Ordinal Type Examples

ƒ Ordinal type – ƒ Ada • cannot reuse values • has a range of possible values, e.g. the set of positive integers • can be used for array subscripts, for variables, case selectors • or can be easily associated with integers, e.g. fruit • can be compared ƒ Enumeration Types -user enumerates all • constants can be reused (overloaded literals) • can be input and output possible values,,y which are symbolic constants ƒ CandC++C and C++ - • Represented with ordinal numbers • cannot reuse values ƒ Design Issues • can be used for array subscripts, for variables, case selectors • Can symbolic constants be in more than one type definition? • can be compared • can be input and output as integers - hair = {red,brown,blonde}, - cat = {brown,striped,black} ƒ Java does not include an enumeration type, • Can OTs be read/written as symbols? • but provides the Enumeration interface • Are they allowed as array indices, subranges?

15 16 Evaluation of User-User-DefinedDefined Ordinal Types Subrange Types 1. Aid to readability ƒ An ordered contiguous subsequence of an ordinal type ƒ e.g. no need to code a color as a number ƒ Design Issue: How can they be used? (statements) 2. Aid to reliability ƒ Pascal • Sub-range types behave as their parent types; can be used as for ƒ e.g. compiler can check variables and array indices 3. Operations specified e.g. type pos = 0 .. MAXINT; ƒ don’t allow colors to be added, for example ƒ Ada • Subtypes are not new types, just constrained existing types (so they are 4. Ranges of values can be checked compatible); can be used as in Pascal, plus case constants e.g. ƒ E. g. if you have 7 colors, code them as integers (1..7), without enforcement, 9 is a legal integer subtype POS_TYPE is and thus a `legal color’! INTEGER range 0..INTEGER'LAST;

Evaluation and Implementation of 17 18 Multiple Concurrent Jobs SubSub--rangerange Types ƒ Aid to readability ƒ : 0 ƒ Reliability - restricted ranges adds error Control program and OS resource manager detection Job 1 ƒ Job 1: Data, Code, Stack Job 2 ƒ Enumeration types are im plemented as & Heap integers ƒ Job 2: ditto Job 3 ƒ Sub-range types are the parent types with ƒ Job 3: ditto Job 4 code inserted (by the compiler) to restrict ƒ Job 4: ditto assignments to sub-range variables ƒ Etc.. FFFF

3 Programming Language Theory

19 20 Each Job in Memory Arrays ƒ Text: code, constant data 0 ƒ An aggregate of homogeneous data elements • individual elements are identified by their position relative to the ƒ Data: Text first element (index) • initialized global & static Data ƒ Design issues variables 1. What types are legal for subscripts? • global & static variables – 0 Heap 2. Range checked on subscript expressions in references? initialized or un-initialized 3. When does binding of subscript ranges happen? (blank) 4. When does allocation take place? ƒ Heap: dynamic memory 5. What is the maximum number of subscripts? 6. Can array objects be initialized? ƒ Stack: dynamic - local Stack 7. Are any kind of slices allowed? variables, state of 82472 program FFFF 16 48 144 32 96 288

21 22 Array Indexing Static and Fixed Stack Dynamic Arrays ƒ Mapping from indices to elements Type based on subscript binding and binding to storage map (array_name, index_value_list) → an element ƒ Index Syntax 1. Static - range of subscripts and storage • FORTRAN, PL/I, Ada use parentheses bindings are static e.gg,y. FORTRAN 77, some arrays in Ada • MtthlMost other languages use b rack ktets • Advantage: execution efficiency (no allocation or de- ƒ Subscript types allocation) • FORTRAN, C - integer only 2. Fixed stack dynamic - range of subscripts is • Pascal - any ordinal type (integer, boolean, char, enum) statically bound, but storage is bound at • Ada - integer or enum (includes boolean and char) elaboration time • Java - integer types only • e.g. Most Java locals, and C locals that are not static • Advantage: space efficiency

23 24 Dynamic Arrays Array Subscripts and Initialization 3. Stack-dynamic - range and storage are ƒ Number of subscripts • FORTRAN I allowed up to three dynamic, but fixed from then on for the • FORTRAN 77 allows up to seven variable’s lifetime • Most languages have no limit ƒ Array Initialization • Advantage: flexibility - size need not be known until the array is about • Usually just a list of values that are put in the array in the order in which the to be used array elements are stored in memory 4. Heap-dynamic - subscript range and storage Example Initialization bindings are dynamic and not fixed 1. FORTRAN - uses the DATA statement, or in / ... / • e.g. (FORTRAN 90) 2. C and C++ - put the values in braces; INTEGER, ALLOCATABLE, ARRAY (:,:) :: MAT • int stuff [] = {2, 4, 6, 8}; (Declares MAT to be a dynamic 2-dimensional array) 3. Ada - positions for the values can be specified • In APL, Perl, and JavaScript, arrays grow and shrink as needed • SCORE : array (1..14, 1..2) := (1 => (24, 10), 2 => (10, 7), • In Java, all arrays are objects (heap-dynamic) 3 =>(12, 30), others => (0, 0)); 4. Pascal does not allow array initialization

4 Programming Language Theory

25 26 BuiltBuilt--inin Array Operations Array Slices 1. APL - many, ƒ A slice is some substructure of an array; See text 7th. Ed p. 240-241, 9th Ed p. 270-272 nothing more than a referencing mechanism 2. Ada ƒ Slices are only useful in languages that have • Assignment; RHS can be an aggregate constant array operations or an array name 1. Exampl e: FORTRAN 90 • Catenation; for all single-dimensioned arrays • Relational operators (= and /= only) INTEGER MAT (1:4, 1:4) 3. FORTRAN 90 MAT(1:4, 1) - the first column • Intrinsic definitions for a wide variety of array MAT(2, 1:4) - the second row operations (e.g., matrix multiplication, vector 2. Ada - single-dimensioned arrays only dot product) LIST(4..10)

27 28 Example Slices in FORTRAN 90 Implementation of Arrays ƒ Access function maps subscript expressions to an address in the array ƒ Row major order (by rows) - most languages ƒ Column major order (by columns) - Fortran

29 30

Array Access Function I Locating an Element

J ƒ Maps subscripts to an address in the Row major = array (1,1) (1,2) (1,3) • hardware contains 1 d array – programmer treats … (m, n-1) (m,n) 1d as multi-dim using virtual rows and columns where ƒ Access function, 1-dimensioned arrays: (I,j) = (i-1) * n + j address (lis t[k]) = address (list[lower_bound]) Column major = + ((k-lower_bound) * element_size) (1,1) (1,2) (1,3) … Geneneral format (m-1, n) (m, n) Location (a[i,j]) = address of a[1,1] {base of array} Where th + (((i - 1) * n) {num rows above the i row * row size} (I,j) = (j-1) * m + i + (j - 1)) * element_size {number of elements left of the jth column * element size}

5 Programming Language Theory

31 32 Array Compile-Compile-TimeTime Descriptors Associative Arrays ƒ Associative Array – • an unordered collection of data elements that are • indexed by keys • Perl – you have seen them implemented using hash tables ƒ Design Issues • What is the form of references to elements? • Is the size static or dynamic? Single-dimensioned array Multi-dimensional array Cats Dogs Frogs Turtles 63104

33 34 Associative Arrays Records ƒ Structure and Operations in Perl ƒ Record = an aggregate of data elements • Names begin with % • Possibly multiple data types (heterogeneous) • Literals are delimited by parentheses • Individual elements/slots are identified by names e.g., declaration with initialization • Same structure - elements in same fixed order for %hi_temps = ("Monday" => 77, all records "Tuesday" => 79,…); • Subscripting is done using braces and keys ƒ Design Issues: e.g., access using key 1. What is the form of references? $hi_temps{"Wednesday"} = 83; 2. What unit operations are defined? • Elements can be removed with delete e.g., delete using key Name Major ID number GPA Kris Alec Student Computer Science 1234-5678 3.98 delete $hi_temps{"Tuesday"};

35 36 Record References Record References, cont. ƒ Record Definition Syntax ƒ Fully qualified references must include • COBOL uses level numbers to show nested all record names records; others use recursive definition ƒ Elliptical references allow leaving out ƒ Cobol example record names as long as the reference is 01 EMP-REC. unambiguous 02 EMP-NAME. 05 FIRST PIC X(20). 05 MID PIC X(10). 05 LAST PIC X(20). 02 HOURLY-RATE PIC 99V99.

6 Programming Language Theory

37 38 Record CompileCompile--TimeTime Descriptor 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 4. 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 different record A compile-time descriptor for a record types!

39 40 Record and Array Access Unions 1. Once the base index to an array or record is ƒ A union is a type whose variables are found, access to array elements is slower than allowed to store different type values at access to record fields, because array subscripts are dynamic (field names are static) different times during execution 2. Dynamic subscripts could be used with record ƒ Discriminated union – has tags for field access, b ut i t would di sall ow type ch ecki ng indicating types for type checking and it would be much slower ƒ 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?

41 42 Examples of Unions Unions 1. FORTRAN - with EQUIVALENCE Common fields: Different fields: • No type checking 2. Pascal - both discriminated and non- discriminated unions

A discriminated union of three shape variables - determines which fields have data values

7 Programming Language Theory

43 44 Type Checking of Unions Union Examples, cont. ƒ Pascal’s can’t be type checked effectively: ƒ Ada - discriminated unions a. User can create inconsistent unions (because the tag can be Reasons they are safer than Pascal: individually assigned) • a. Tag must be present var blurb : intreal; • b. It is impossible for the user to create an inconsistent x : real; union because tag cannot be assigned by itself--All blurb.tagg := true ;{; { an inte g}ger } assignments to the union must include the tag value, blurb.blint := 47; { ok } because they are aggregate values blurb.tagg := false; { it is a real } ƒ C and C++ - free unions (no tags) x := blurb.blreal; { assigns an • Not part of their records integer to real } • No type checking of reference b. The tag is optional! ƒ Java has neither records nor unions ƒ Now, only the declaration and the second and last assignments are required to cause trouble! ƒ Evaluation - potentially unsafe in most languages (not Ada)

45 46 Sets Pointers and References ƒ Set type - stores unordered collections of ƒ Pointers – access to dynamic storage distinct values from some ordinal type • E.g. C/C++ ƒ Operations: • The address of the data – a number • Flexible – you can do arithmetic on the addresses! • Union 189993645618 9 99 36 45 6 • FiffthkFew, if any safety checks on access usi ng poi itnters • Intersection 81 3 27 • Difference ƒ References – access to dynamic storage ƒ Design Issue: • E.g. Java, Lisp • Points to the data • What is the maximum • Not possible to do arithmetic number of elements in • Much safer any set base type?

47 48 Heap Storage Problems with Pointers

Implicit – 0 1. Dangling pointers (dangerous) automatic Text • A pointer points to a heap-dynamic variable that has been de-allocated Data • Creating one (with explicit de-allocation): Heap 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 Explicit – pointer programmer’ 3. De-allocate the heap-dynamic variable, using the s instructions Stack first pointer

FFFF

8 Programming Language Theory

49 50 Problems with Pointers, cont. C and C++ Pointers 2. Lost Heap-Dynamic Variables (wasteful) C and C++ • Used for dynamic storage management and addressing • A heap-dynamic variable that is no longer referenced • Explicit dereferencing and address-of operator by any program pointer • Domain type need not be fixed (void *) • Creating one: • void * - Can point to any type and can be type checked (cannot be de-referenced) 1. Pointer p1 is set to point to a newly created heap- • Can do address arithmetic in restricted forms, e.g.: dynamic variable float stuff[100]; 2. p1 is later set to point to another newly created heap- float *p; dynamic variable p = stuff; • The process of losing heap-dynamic variables is called memory leakage *(p+5) is equivalent to stuff[5] and p[5] *(p+i) is equivalent to stuff[i] and p[i] (Implicit scaling)

51 52 Pointers C++ and Java Pointer/References C++ Reference Types • Constant pointers that are implicitly de-referenced • Used for parameters - Advantages of both pass-by-reference and pass-by-value 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 The assignment operation j = *ptr Lisp - ?

53 54 Pointer Representation and References Implementing Dynamic Variables ƒ Large computers use single values ƒ Intel microprocessors use segment and offset ƒ problem solutions 1. Tombstone: extra heap cell that is a pointer to the heap-dynamic variable • The act ual poi nt er vari abl e poi nt s onl y at t omb st ones • 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

9 Programming Language Theory

55 56 Heap Management Heap Management ƒ Single-size cells vs. variable-size cells ƒ Garbage collection • allocate and disconnect until all available cells allocated; then begin ƒ Reference counters (eager approach) vs. gathering all garbage ƒ Every heap cell has an extra bit used by collection garbage collection (lazy approach) algorithm • Reference counters: maintain a counter in every • All cells initially set to garbage • All poi nt ers t raced i nt o h eap, and reach abl e cell s mark ed as not cell that store the number of pointers currently garbage pointing at the cell • All garbage cells returned to list of available cells • Disadvantages: space required, execution time ƒ Garbage collection required, complications for cells connected • Disadvantages: when you need it most, it works worst (takes most time when program needs most of cells in heap) circularly • More efficient methods don’t wait until absolutely necessary

57 58 Garbage Collection Evaluation of Pointers Marking Algorithm 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 Type Checking Type Checking (continued) ƒ Include subprograms and assignments as ƒ If all type bindings are static, nearly all operands and operators type checking can be static ƒ Type checking -- ensuring that the operands of an operator are of compatible types ƒ If type bindings are dynamic, type ƒ A compatible type is checking must be dynamic • llfhlegal for the operator, or ƒ AiliA programming language is strongly • allowed under language rules to be implicitly converted, by compiler- generated code, to a legal typed if type errors are always detected type ƒ Advantage of strong typing: allows the ƒ Automatic conversion = coercion detection of the misuses of variables that ƒ A type error occurs when an operator is result in type errors applied to an operand of an inappropriate type ƒ Does strong typing catch all errors?

10 Programming Language Theory

Strong Typing Strong Typing (continued) Language examples: ƒ Coercion rules strongly affect strong ƒ FORTRAN 95 is not: due to parameters, typing--they can weaken it considerably EQUIVALENCE (C++ versus Ada) ƒ C and C++ are not: ppyparameter type checking can be avoided; unions are not ƒ Although Java has about half the type checked assignment coercions of C++, its strong ƒ Ada is, almost (UNCHECKED typing is still far less effective than that CONVERSION is loophole) of Ada ƒ Java and C# are similar to Ada

64 Name Type Equivalence Structure type equivalence Two variables have equivalent types if they are either in ƒ Two variables have equivalent types if • the same declaration or their types have identical structures • a declaration that uses the same type name ƒ More flexible, but harder to implement ƒ Easy to implement ƒ Highly restrictive: - A sub range of integers is not equivalent to an integer type! Formal parameters must be the same type as their corresponding actual parameters 63

65 66 Theory and Data Types Theory and Data Types (2) ƒ Type theory is a broad area of study in ƒ Formal model of a type system is a set of mathematics, logic, computer science, types and a collection of functions that and philosophy define the type rules ƒ Two branches of type theory in computer • Either an attribute grammar or a type map could science: bdfthftibe used for the functions • Finite mappings – model arrays and functions • Practical – data types in commercial languages • Cartesian products – model tuples and records • Abstract – typed lambda calculus • Set unions – model union types ƒ A type system is a set of types and the • Subsets – model subtypes rules that govern their use in programs

11 Programming Language Theory

67 68 Summary Questions ƒ Primitive Data Types ƒ Character String Types ƒ User-Defined Ordinal Types ƒ Array Types ƒ Associative Arra ys ƒ Record Types ƒ Union Types ƒ Pointer Types ƒ Type Checking ƒ Ref: Chapter 6

12