CSE 4102 Chapter 6 Exploring Types and Equivalence


































































































































































![Name Equivalence a: array [0. . 4] of int; b: array [0. . 4] Name Equivalence a: array [0. . 4] of int; b: array [0. . 4]](https://slidetodoc.com/presentation_image_h/c5dda6a96f8e17a57a175640463db8f4/image-163.jpg)
![Name Equivalence a, b: array [0. . 4] of int; • a = b? Name Equivalence a, b: array [0. . 4] of int; • a = b?](https://slidetodoc.com/presentation_image_h/c5dda6a96f8e17a57a175640463db8f4/image-164.jpg)
![Name Equivalence Type A: array [0. . 4] of int; a: A; b: A; Name Equivalence Type A: array [0. . 4] of int; a: A; b: A;](https://slidetodoc.com/presentation_image_h/c5dda6a96f8e17a57a175640463db8f4/image-165.jpg)









- Slides: 174
CSE 4102 Chapter 6 Exploring Types and Equivalence Prof. Steven A. Demurjian Computer Science & Engineering Department The University of Connecticut 371 Fairfield Way, Box U-255 Storrs, CT 06269 -3255 Steven. Demurjian@uconn. edu http: //www. engr. uconn. edu/~steve (860) 486– 4818 (Office) (860) 486 -3719 (CSE Office) OV-1
Review a Number of Other PPTs m CSE m 4102 m Org of Programming Languages-Cheng (Fall 2004) Sebesta chapter 6 condensed –easier to follow q Type Systems and Structures- Bermúdez q m m http: //www. cse. msu. edu/~cse 452/Fall 2004/Lectures/06 -data-types-school. ppt https: //www. cise. ufl. edu/class/cop 5556 sp 16/Lecture_22. ppt Steve’s Types and Type Checking Type Systems – Doupé q https: //adamdoupe. com/teaching/classes/cse 340 -principles-ofprogramming-languages-f 15/slides/05 -Type-Systems. pptx OV-2
http: //www. cse. msu. edu/~cse 452/Fall 2004/Lectures/06 -data-types-school. ppt CSE 452: Programming Languages Data Types
Where are we? Machine Language Logic You are here High-level Programming Languages Object Oriented Imperative Concepts • specification (syntax, semantics) • variables (binding, scoping, types, …) Assembly Language Functional Implementation • compilation (lexical & syntax analysis) • statements (control, selection, assignment, …) Organization of Programming Languages-Cheng (Fall 2004) 4
Terminology u Strong typing: language prevents you from applying an operation to data on which it is not appropriate. u Static typing: compiler can do all the checking at compile time. u Examples: l Common Lisp is strongly typed, but not statically typed. l Ada is statically typed. l Pascal is almost statically typed. l Java is strongly typed, with a non-trivial mix of things that can be checked statically and things that have to be checked dynamically. Organization of Programming Languages-Cheng (Fall 2004) 5
Type System Has rules for : u Type equivalence l (when are the types of two values the same? ) u Type compatibility l (when can a value of type A be used in a context that expects type B? ) u Type inference l (what is the type of an expression, given the types of the operands? ) Organization of Programming Languages-Cheng (Fall 2004) 6
Type compatability/equivalence u Compatability: tells you what you can do l More useful concept of the two l Erroneously used interchangeably u Equivalence: l What are important differences between type declarations? l Format does not matter: struct { int a, b; } u Same as struct { int a, b; } struct{ AND int a; int b; } Organization of Programming Languages-Cheng (Fall 2004) 7
Equivalence: two approaches u Two types: name and structural equivalence u Name Equivalence: based on declarations l More commonly used in current practice l Strict name equivalence: u l Types are equivalent if refer to same declaration Loose name equivalence: u Types are equivalent if they refer to same outermost constructor l u (refer to same declaration after factoring out any type aliases) Structural Equivalence: based on meaning/semantics behind the declarations. l Simple comparison of type descritpions l Substitute out all names; l Expand all the way to built-in types Organization of Programming Languages-Cheng (Fall 2004) 8
Data Types u A data type defines l a collection of data objects, and l a set of predefined operations on the objects type: integer operations: +, -, *, /, %, ^ u Evolution of Data Types l Early days: all programming problems had to be modeled using only a few data types u FORTRAN I (1957) provides INTEGER, REAL, arrays u l Current practice: u Users can define abstract data types (representation + operations) Organization of Programming Languages-Cheng (Fall 2004) 9
Character Types u u Characters are stored in computers as numeric codings Traditionally use 8 -bit code ASCII, which uses 0 to 127 to code 128 different characters ISO 8859 -1 also use 8 -bit character code, but allows 256 different characters l Used by Ada 16 -bit character set named Unicode l Includes Cyrillic alphabet used in Serbia, and Thai digits l First 128 characters are identical to ASCII l used by Java and C# Organization of Programming Languages-Cheng (Fall 2004) 10
Character String Types u u Values consist of sequences of characters Design issues: l Is it a primitive type or just a special kind of character array? l Is the length of objects static or dynamic? Operations: l Assignment l Comparison (=, >, etc. ) l Catenation l Substring reference l Pattern matching Examples: l Pascal u l Not primitive; assignment and comparison only Fortran 90 u Somewhat primitive; operations include assignment, comparison, catenation, substring reference, and pattern matching Organization of Programming Languages-Cheng (Fall 2004) 11
Character Strings u Examples l Ada N : = N 1 & N 2 (catenation) N(2. . 4) (substring reference) l C and C++ u l SNOBOL 4 (a string manipulation language) u l Primitive; many operations, including elaborate pattern matching Perl and Java. Script u l Not primitive; use char arrays and a library of functions that provide operations Patterns are defined in terms of regular expressions; a very powerful facility Java String class (not arrays of char); Objects are immutable u String. Buffer is a class for changeable string objects u Organization of Programming Languages-Cheng (Fall 2004) 12
Character Strings u String Length l Static – FORTRAN 77, Ada, COBOL u l e. g. (FORTRAN 90) CHARACTER (LEN = 15) NAME; Limited Dynamic Length – C and C++ u actual length is indicated by a null character Dynamic – SNOBOL 4, Perl, Java. Script Evaluation (of character string types) l Aid to writability l As a primitive type with static length, they are inexpensive to provide l Dynamic length is nice, but is it worth the expense? Implementation l u u Organization of Programming Languages-Cheng (Fall 2004) 13
Ordinal Data Types u Range of possible values can be easily associated with the set of positive integers u Enumeration types l user enumerates all the possible values, which are symbolic constants enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun}; l Design Issue: Should a symbolic constant be allowed to be in more than one type definition? u Type checking l Are enumerated types coerced to integer? l Are any other types coerced to an enumerated type? u Organization of Programming Languages-Cheng (Fall 2004) 14
Enumeration Data Types u Examples l Pascal u l Ada u l constants can be reused (overloaded literals); disambiguate with context or type_name’(one of them) (e. g, Integer’Last) C and C++ u l cannot reuse constants; can be used for array subscripts, for variables, case selectors; can be compared enumeration values are coerced into integers when put in integer context Java u u does not include an enumeration type, but provides the Enumeration interface can implement them as classes class colors { public final int red = 0; public final int blue = 1; } Organization of Programming Languages-Cheng (Fall 2004) 15
Subrange Data Types u An ordered contiguous subsequence of an ordinal type l e. g. , 12. . 14 is a subrange of integer type l Design Issue: How can they be used? l Examples: u Pascal l l u Ada l u subrange types behave as their parent types; can be used as for variables and array indices type pos = 0. . MAXINT; Subtypes are not new types, just constrained existing types (so they are compatible); can be used as in Pascal, plus case constants subtype POS_TYPE is INTEGER range 0. . INTEGER'LAST; Evaluation u Aid to readability - restricted ranges add error detection Organization of Programming Languages-Cheng (Fall 2004) 16
Arrays u Indexing is a mapping from indices to elements l map(array_name, index_value_list) an element u Index Syntax l FORTRAN, PL/I, Ada use parentheses: l most other languages use brackets: u A(3) A[3] Subscript Types: l FORTRAN, C - integer only l Pascal - any ordinal type (integer, boolean, char, enum) l Ada - integer or enum (includes boolean and char) l Java - integer types only Organization of Programming Languages-Cheng (Fall 2004) 17
Arrays u Five Categories of Arrays (based on subscript binding and binding to storage) l Static l Fixed stack dynamic l Stack dynamic l Fixed Heap dynamic l Heap dynamic Organization of Programming Languages-Cheng (Fall 2004) 18
Arrays u Static l range of subscripts and storage bindings are static l e. g. FORTRAN 77, some arrays in Ada l Arrays declared in C and C++ functions that include the static modifier are static l Advantage: execution efficiency (no allocation or deallocation) u Fixed stack dynamic l range of subscripts is statically bound, but storage is bound at elaboration time u l l Elaboration time: when execution reaches the code to which the declaration is attached Most Java locals, and C locals that are not static Advantage: space efficiency Organization of Programming Languages-Cheng (Fall 2004) 19
Arrays u Stack-dynamic l range and storage are dynamic, but fixed from then on for the variable’s lifetime e. g. Ada declare blocks declare STUFF : array (1. . N) of FLOAT; begin. . . end; l Advantage: flexibility - size need not be known until array is about to be used Organization of Programming Languages-Cheng (Fall 2004) 20
Arrays u Fixed Heap dynamic l Binding of subscript ranges and storage are dynamic, but are both fixed after storage is allocated l Binding done when user program requests them, rather than at elaboration time and storage is allocated on the heap, rather than the stack l In Java, all arrays are objects (heap-dynamic) l C# also provides fixed heap-dynamic arrays Organization of Programming Languages-Cheng (Fall 2004) 21
Arrays u Heap-dynamic l subscript range and storage bindings are dynamic and not fixed l e. g. (FORTRAN 90) INTEGER, ALLOCATABLE, ARRAY (: , : ) : : MAT (Declares MAT to be a dynamic 2 -dim array) ALLOCATE (MAT (10, NUMBER_OF_COLS)) (Allocates MAT to have 10 rows and NUMBER_OF_COLS columns) DEALLOCATE MAT (Deallocates MAT’s storage) l Perl and Java. Script support heap-dynamic arrays u u arrays grow whenever assignments are made to elements beyond the last current element Arrays are shrunk by assigning them to empty array Perl: @my. Array = ( ); Organization of Programming Languages-Cheng (Fall 2004) 22
Arrays u u Number of subscripts (dimensions) l FORTRAN I allowed up to three l FORTRAN 77 allows up to seven l Others - no limit Array Initialization l Usually just a list of values that are put in the array in the order in which the array elements are stored in memory l Examples: u FORTRAN - uses the DATA statement Integer List(3) Data List /0, 5, 5/ u C and C++ - put the values in braces; let compiler count them int stuff [] = {2, 4, 6, 8}; u 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)); u Pascal does not allow array initialization Organization of Programming Languages-Cheng (Fall 2004) 23
Arrays: Operations u u Ada l Assignment; RHS can be an aggregate constant or an array name l Catenation between single-dimensioned arrays FORTRAN 95 l Includes a number of array operations called elementals because they are operations between pairs of array elements u u E. g. , add (+) operator between two arrays results in an array of the sums of element pairs of the two arrays Slices l A slice is some substructure of an array l FORTRAN 90 INTEGER MAT (1 : 4, 1 : 4) MAT(1 : 4, 1) - the first column MAT(2, 1 : 4) - the second row l Ada - single-dimensioned arrays only LIST(4. . 10) Organization of Programming Languages-Cheng (Fall 2004) 24
Arrays u Implementation of Arrays l Access function maps subscript expressions to an address in the array l Single-dimensioned array address(list[k]) = address(list[lower_bound]) + (k-1)*element_size = (address[lower_bound] – element_size) + (k * element_size) 3 4 7 l Multi-dimensional arrays Row major order: u Column major order u 3, 4, 7, 6, 2, 5, 1, 3, 8 3, 6, 1, 4, 2, 3, 7, 5, 8 Organization of Programming Languages-Cheng (Fall 2004) 6 2 5 1 3 8 25
Associative Arrays u An unordered collection of data elements that are indexed by an equal number of values called keys l also known as hashes u Design Issues: l What is the form of references to elements? l Is the size static or dynamic? Organization of Programming Languages-Cheng (Fall 2004) 26
Associative Arrays u Structure and Operations in Perl l Names begin with % l Literals are delimited by parentheses l %hi_temps = ("Monday" => 77, "Tuesday" => 79, …); l Subscripting is done using braces and keys l e. g. , $hi_temps{"Wednesday"} = 83; u Elements can be removed with delete l e. g. , delete $hi_temps{"Tuesday"}; Organization of Programming Languages-Cheng (Fall 2004) 27
Records u. A (possibly heterogeneous) aggregate of data elements in which the individual elements are identified by names u Design Issues: l What is the form of references? l What unit operations are defined? Organization of Programming Languages-Cheng (Fall 2004) 28
Records u Record Definition Syntax l COBOL uses level numbers to show nested records; others use recursive definitions l COBOL 01 EMPLOYEE-RECORD. 02 EMPLOYEE-NAME. 05 FIRST 05 MIDDLE 05 LAST 02 HOURLY-RATE PICTURE IS X(20). PICTURE IS X(10). PICTURE IS X(20). PICTURE IS 99 V 99. Level numbers (01, 02, 05) indicate their relative values in the hierarchical structure of the record PICTURE clause show the formats of the field storage locations X(20): 20 alphanumeric characters 99 V 99: four decimal digits with decimal point in the middle Organization of Programming Languages-Cheng (Fall 2004) 29
Records u Ada: Type Employee_Name_Type is record First: String (1. . 20); Middle: String (1. . 10); Last: String (1. . 20); end record; type Employee_Record_Type is record Employee_Name: Employee_Name_Type; Hourly_Rate: Float; end record; Employee_Record: Employee_Record_Type; Organization of Programming Languages-Cheng (Fall 2004) 30
Records u References to Record Fields u COBOL field references field_name OF record_name_1 OF … OF record_name_n e. g. MIDDLE OF EMPLOYEE-NAME OF EMPLOYEE_RECORD u Fully qualified references must include all intermediate record names u Elliptical references allow leaving out record names as long as the reference is unambiguous - e. g. , the following are equivalent: FIRST, FIRST OF EMPLOYEE-NAME, FIRST OF EMPLOYEE-RECORD Organization of Programming Languages-Cheng (Fall 2004) 31
Records u Operations l Assignment u Pascal, l Ada, and C allow it if the types are identical In Ada, the RHS can be an aggregate constant l Initialization u Allowed in Ada, using an aggregate constant l Comparison u In Ada, = and /=; one operand can be an aggregate constant l MOVE CORRESPONDING u In COBOL - it moves all fields in the source record to fields with the same names in the destination record Organization of Programming Languages-Cheng (Fall 2004) 32
Tuple Types • A tuple is a data type that is similar to a record, except that the elements are not named • Used in Python, ML, and F# to allow functions to return multiple values – Python • Closely related to its lists, but immutable • Create with a tuple literal my. Tuple = (3, 5. 8, ′apple′) Referenced with subscripts (begin at 1) Catenation with + and deleted with del Copyright © 2015 Pearson. All rights reserved. 1 -33
Tuple Types (continued) • ML val my. Tuple = (3, 5. 8, ′apple′); - Access as follows: #1(my. Tuple) is the first element - A new tuple type can be defined type int. Real = int * real; • F# let tup = (3, 5, 7) let a, b, c = tup This assigns a tuple to a tuple pattern (a, b, c) Copyright © 2015 Pearson. All rights reserved. 1 -34
List Types • Lists in Lisp and Scheme are delimited by parentheses and use no commas (A B C D) and (A (B C) D) • Data and code have the same form As data, (A B C) is literally what it is As code, (A B C) is the function A applied to the parameters B and C • The interpreter needs to know which a list is, so if it is data, we quote it with an apostrophe ′(A B C) is data Copyright © 2015 Pearson. All rights reserved. 1 -35
List Types (continued) • List Operations in Scheme – CAR returns the first element of its list parameter returns A – CDR returns the remainder of its list parameter after the first element has been removed (CDR ′(A B C)) returns (B C) - CONS puts its first parameter into its second parameter, a list, to make a new list (CONS ′A (B C)) returns (A B C) - LIST returns a new list of its parameters (LIST ′A ′B ′(C D)) returns (A B (C D)) (CAR ′(A B C)) Copyright © 2015 Pearson. All rights reserved. 1 -36
List Types (continued) • List Operations in ML – Lists are written in brackets and the elements are separated by commas – List elements must be of the same type – The Scheme CONS function is a binary operator in ML, : : 3 : : [5, 7, 9] evaluates to [3, 5, 7, 9] – The Scheme CAR and CDR functions are named hd and tl, respectively Copyright © 2015 Pearson. All rights reserved. 1 -37
List Types (continued) • F# Lists – Like those of ML, except elements are separated by semicolons and hd and tl are methods of the List class • Python Lists – The list data type also serves as Python’s arrays – Unlike Scheme, Common Lisp, ML, and F#, Python’s lists are mutable – Elements can be of any type – Create a list with an assignment my. List = [3, 5. 8, "grape"] Copyright © 2015 Pearson. All rights reserved. 1 -38
List Types (continued) • Python Lists (continued) – List elements are referenced with subscripting, with indices beginning at zero x = my. List[1] Sets x to 5. 8 – List elements can be deleted with del my. List[1] – List Comprehensions – derived from set notation [x * x for x in range(6) if x % 3 == 0] creates [0, 1, 2, 3, 4, 5, 6] Constructed list: [0, 9, 36] range(12) Copyright © 2015 Pearson. All rights reserved. 1 -39
List Types (continued) • Haskell’s List Comprehensions – The original [n * n | n <- [1. . 10]] • F#’s List Comprehensions let my. Array = [|for i in 1. . 5 -> [i * i) |] • Both C# and Java supports lists through their generic heap-dynamic collection classes, List and Array. List, respectively Copyright © 2015 Pearson. All rights reserved. 1 -40
Unions u u u A type whose variables are allowed to store different type values at different times during execution Design Issues for unions: l What kind of type checking, if any, must be done? l Should unions be integrated with records? Examples: l FORTRAN - with EQUIVALENCE u l No type checking Pascal u both discriminated and nondiscriminated unions type intreal = record tagg : Boolean of true : (blint : integer); false : (blreal : real); end; u Problem with Pascal’s design: type checking Organization of Programming Languages-Cheng (Fall 2004) is ineffective 41
Unions u Example (Pascal)… l Reasons why Pascal’s unions cannot be type checked effectively: u User can create inconsistent unions (because the tag can be individually assigned) var blurb : intreal; x : real; blurb. tagg : = true; blurb. blint : = 47; blurb. tagg : = false; x : = blurb. blreal; real } { { it is an integer } ok } it is a real } assigns an integer to a The tag is optional! u Now, only the declaration and the second and last assignments are required to cause trouble u Organization of Programming Languages-Cheng (Fall 2004) 42
Unions u Examples… l Ada discriminated unions u Reasons they are safer than Pascal: u l l l Tag must be present 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) u Not part of their records u l l u No type checking of references Java has neither records nor unions Evaluation - potentially unsafe in most languages (not Ada) Organization of Programming Languages-Cheng (Fall 2004) 43
Unions Types • A union is a type whose variables are allowed to store different type values at different times during execution • Design issue – Should type checking be required? Copyright © 2015 Pearson. All rights reserved. 1 -44
Discriminated vs. Free Unions • C and C++ provide union constructs in which there is no language support for type checking; the union in these languages is called free union • Type checking of unions require that each union include a type indicator called a discriminant – Supported by ML, Haskell, and F# Copyright © 2015 Pearson. All rights reserved. 1 -45
Unions in F# • Defined with a type statement using OR type int. Real = | Int. Value of int | Real. Value of float; ; is the new type Int. Value and Real. Value are constructors int. Real To create a value of type int. Real: let ir 1 = Int. Value 17; ; let ir 2 = Real. Value 3. 4; ; Copyright © 2015 Pearson. All rights reserved. 1 -46
Unions in F# (continued) • Accessing the value of a union is done with pattern matching match pattern with | expression_list 1 -> expression 1 | … | expression_listn -> expressionn - Pattern can be any data type - The expression list can have wild cards (_) Copyright © 2015 Pearson. All rights reserved. 1 -47
Unions in F# (continued) Example: let a = 7; ; let b = ″grape″; ; let x = match (a, b) with | 4, ″apple″ -> apple | _, ″grape″ -> grape | _ -> fruit; ; Copyright © 2015 Pearson. All rights reserved. 1 -48
Unions in F# (continued) To display the type of the int. Real union: let print. Type value = match value with | Int. Vale value -> printfn ″int″ | Real. Value value -> printfn ″float″; ; If ir 1 and print. Type are defined as previously, ir 1 returns int ir 2 returns float ir 2 Copyright © 2015 Pearson. All rights reserved. 1 -49
Evaluation of Unions • Free unions are unsafe – Do not allow type checking • Java and C# do not support unions – Reflective of growing concerns for safety in programming language Copyright © 2015 Pearson. All rights reserved. 1 -50
Sets u u u A type whose variables can store unordered collections of distinct values from some ordinal type Design Issue: l What is the maximum number of elements in any set base type? Example l Pascal No maximum size in the language definition (not portable, poor writability if max is too small) u Operations: in, union (+), intersection (*), difference (-), =, <>, superset (>=), subset (<=) u l Ada u l does not include sets, but defines in as set membership operator for all enumeration types Java u includes a class Languages-Cheng for set operations Organization of Programming (Fall 2004) 51
Sets u Evaluation l If a language does not have sets, they must be simulated, either with enumerated types or with arrays l Arrays are more flexible than sets, but have much slower set operations u Implementation l Usually stored as bit strings and use logical operations for the set operations Organization of Programming Languages-Cheng (Fall 2004) 52
Pointers u u A pointer type is a type in which the range of values consists of memory addresses and a special value, nil (or null) Uses: l Addressing flexibility l Dynamic storage management Design Issues: l What is the scope and lifetime of pointer variables? l What is the lifetime of heap-dynamic variables? l Are pointers restricted to pointing at a particular type? l Are pointers used for dynamic storage management, indirect addressing, or both? l Should a language support pointer types, reference types, or both? Fundamental Pointer Operations: l Assignment of an address to a pointer l References (explicit versus implicit dereferencing) Organization of Programming Languages-Cheng (Fall 2004) 53
Pointers u Problems with pointers: l Dangling pointers (dangerous) A pointer points to a heap-dynamic variable that has been deallocated u Creating one (with explicit deallocation): u l l Allocate a heap-dynamic variable and set a pointer to point at it Set a second pointer to the value of the first pointer Deallocate the heap-dynamic variable, using the first pointer Lost Heap-Dynamic Variables ( wasteful) A heap-dynamic variable that is no longer referenced by any program pointer u Creating one: u l l u Pointer p 1 is set to point to a newly created heap-dynamic variable p 1 is later set to point to another newly created heap-dynamic variable The process of losing heap-dynamic variables is called memory leakage Organization of Programming Languages-Cheng (Fall 2004) 54
Pointers u Examples: l Pascal used for dynamic storage management only u Explicit dereferencing (postfix ^) u Dangling pointers are possible (dispose) u Dangling objects are also possible u l Ada a little better than Pascal u Some dangling pointers are disallowed because dynamic objects can be automatically deallocated at the end of pointer's type scope u All pointers are initialized to null u Similar dangling object problem (but rarely happens, because explicit deallocation is rarely done) u Organization of Programming Languages-Cheng (Fall 2004) 55
Pointers u Examples… l C and C++ Used for dynamic storage management and addressing u Explicit dereferencing and address-of operator u Can do address arithmetic in restricted forms u Domain type need not be fixed (void * ) float stuff[100]; float *p; p = stuff; u *(p+5) is equivalent to stuff[5] and p[5] *(p+i) is equivalent to stuff[i] and p[i] (Implicit scaling) void * - Can point to any type and can be type checked (cannot be dereferenced) Organization of Programming Languages-Cheng (Fall 2004) 56
Pointers u Examples… l FORTRAN 90 Pointers Can point to heap and non-heap variables u Implicit dereferencing u Pointers can only point to variables that have the TARGET attribute u The TARGET attribute is assigned in the declaration, as in: INTEGER, TARGET : : NODE u A special assignment operator is used for non-dereferenced references REAL, POINTER : : ptr (POINTER is an attribute) ptr => target (where target is either a pointer or a nonpointer with the TARGET attribute)) This sets ptr to have the same value as target u Organization of Programming Languages-Cheng (Fall 2004) 57
Pointers u Examples… l C++ Reference Types Constant pointers that are implicitly dereferenced u Used for parameters u Advantages of both pass-by-reference and pass-by-value u l Java Only references u No pointer arithmetic u Can only point at objects (which are all on the heap) u No explicit deallocator (garbage collection is used) u Means there can be no dangling references u Dereferencing is always implicit u Organization of Programming Languages-Cheng (Fall 2004) 58
Pointers u Evaluation l Dangling pointers and dangling objects are problems, as is heap management l Pointers are like goto's--they widen the range of cells that can be accessed by a variable l Pointers or references are necessary for dynamic data structures--so we can't design a language without them Organization of Programming Languages-Cheng (Fall 2004) 59
https: //www. cise. ufl. edu/class/cop 5556 sp 16/Lecture_22. ppt& Type Systems and Structures Programming Language Principles Lecture 22 Prepared by Manuel E. Bermúdez, Ph. D. Associate Professor University of Florida
Type Systems (cont’d) • Statically typed language: strongly typed, with enforcement occurring at compile time. Examples: ANSI C (more so than classic C), Pascal (almost, untagged variant records) • Some (few) languages are completely untyped: Bliss, assembly language. • Dynamic (run-time) type checking: RPAL, Lisp, Scheme, Smalltalk. • Other languages (ML, Miranda, Haskell) are polymorphic, but use significant type inference at compile time.
Type Definitions (cont’d) • Three approaches to describe types: 1. Denotational. • A type is a set of values (domain). • An object has a type if its value is in the set. 2. Constructive: • A type is either atomic (int, float, bool, etc. ) or is built (constructed) from atomic types, i. e. arrays, records, sets, etc. 3. Abstraction: • A type is an interface: a set of operations upon certain objects.
Classification of Types • Scalar (a. k. a. discrete, ordinal) types: • The terminology varies (bool, logical, truthvalue). • Scalars sometimes come in several widths (short, int, long in C, float and double, too). • Integers sometimes come "signed" and "unsigned. "
Classification of Types (cont’d) Enumerations: • Pascal: type day = (yesterday, tomorrow) • A newly defined type, so: var d: day; for d : = today to tomorrow do. . . • Can also use to index arrays: var profits: array[day] of real; In Pascal, enumeration is a full-fledged type.
Classification of Types (cont’d) • C: enum day {yesterday, tomorrow }; equivalent to: typedef int day; const day yesterday=0; today=1; tomorrow=2;
Classification of Types (cont’d) • Subrange types. • Values are a contiguous subset of the base type values. The range imposes a type constraint. Pascal: type water_temp = 32. . 212;
Type Equivalence • Structural equivalence: Two types are equivalent if they contain the same components. • Varies from one language to another.
Type Equivalence (cont’d) Example: type r 1 = record a, b: integer; end; type r 2 = record b: integer; a: integer; end; var v 1: r 1; v 2: r 2; v 1 : = v 2; • Are these types compatible ? • What if a and b are reversed ? • In most languages, no. In ML, yes.
Type Equivalence (cont’d) • Name equivalence: based on type definitions: usually same name. • Assumption: named types are intended to be different. • Alias types: definition of one type is the name of another. • Question: Should aliased types be the same type?
Type Equivalence (cont’d) • In Modula-2: TYPE stack_element = INTEGER; MODULE stack; IMPORT stack_element; EXPORT push, pop; procedure push (e: stack_element); procedure pop ( ): stack_element; • Stack module cannot be reused for other types.
Type Equivalence (cont’d) • Strict name equivalence: aliased types are equivalent. • type a = b considered both declaration and definition. • Loose name equivalence: aliased types not equivalent. • type a = b considered a declaration; a and b share the definition.
Type Equivalence (cont’d) In Ada: compromise, allows programmer to indicate: • alias is a subtype (compatible with base type) subtype stack_element is integer;
Type Equivalence (cont’d) • In Ada, an alias is a derived type (not compatible) subtype stack_element is integer; type celsius is new REAL; type fahrenh is new REAL; • Now the stack is reusable, and celsius is not compatible with fahrenh.
Type Conversion and Casts • Many contexts in which types are expected: • assignments, unary and binary operators, parameters. • If types are different, programmer must convert the type (conversion or casting).
Three Situations 1. Types are structurally equivalent, but language requires name equivalence. Conversion is trivial. • Example (in C): typedef number int; typedef quantity int; number n; quantity m; n = m;
Three Situations (cont’d) 2. Different sets of values, but same representation. • Example: subrange 3. . 7 of int. • Generate run-time code to check for appropriate values (range check).
Three Situations (cont’d) 3. Different representations. • Example (in C): int n; float x; n = x; • Generate code to perform conversion at run-time.
Type Conversions • Ada: name of type used as a pseudofunction: • Example: n = integer(r); • C, C++, Java: Name of type used as prefix operator, in ()s. • Example: n = (int) r;
Type Conversions (cont’d) • If conversion not supported in the language, convert to pointer, cast, and dereference (ack!): r = *((float *) &n); • Re-interpret bits in n as a float.
Type Conversions (cont’d) • OK in C, as long as • n has an address (won't work with expressions) • n and r occupy the same amount of storage. • programmer doesn't expect runtime overflow checks !
Type Compatibility and Coercions • Coercion: implicit conversion. • Rules vary greatly from one language to another.
Type Compatibility and Coercions (cont’d) • Ada: Types T and S are compatible (coercible) if either 1. T and S are equivalent. 2. One is a subtype of the other (or both subtypes of the same base type). 3. Both are arrays (same numbers, and same type of elements). • Pascal: same as Ada, but allows coercion from integer to real.
Type Compatibility and Coercions (cont’d) • C: Many coercions allowed. General idea: convert to narrowest type that will accommodate both types. 1. Promote char (or short int) to int, guaranteeing neither is char or short. 2. If one operand is a floating type, convert the narrower one: float -> double -> long double
Type Compatibility and Coercions (cont’d) • Note: this accommodates mixtures of integer and floating types. 3. If neither type is a floating type, convert the narrower one: int-> unsigned int-> long int-> unsigned long int
Examples char c; /* signed or unsigned -- implementation? */ short int s; unsigned int u; int i; long int l; unsigned long int ul; float f; double d; long double ld;
Examples (cont’d) i + c; i + s; u + i; l + u; ul + l; f + ul; d + f; ld + d; /* /* c converted to int s converted to int i converted to unsigned int u converted to long int l converted to unsigned long int ul converted to float f converted to double d converted to long double */ */
Type Compatibility and Coercions (cont’d) • Conversion during assignment. • usual arithmetic conversions don't apply. • simply convert from type on the right, to type on the left.
Examples char c; /* signed or unsigned -- implementation? */ short int s; unsigned int u; int i; long int l; unsigned long int ul; float f; double d; long double ld;
Examples s = l; /* l's low-order bits -> signed number s = ul; /* ditto l = s; /* s signed-extended to longer length ul = s: /* ditto, ul's high-bit affected ? s = c; /* c extended (signed or not) to /* s's length, interpreted as signed f = l; /* l converted to float, precision lost d = f: /* f converted, no precision lost. f = d; /* d converted, precision lost /* result may be undefined */ */ */
Type Inference • Usually easy. • Type of assignment is type of left-side. • Type of operation is (common) type of operands.
Type Inference (cont’d) • Not always easy. Pascal: type A: 0. . 20; B: 10. . 20: var a: A; b: B; • What is the type of a+b ? In Pascal, it's the base type (integer).
Type Inference (cont’d) • Ada: • The type of the result would be an anonymous type 0. . 40. • The compiler would generate run-time checks for values out of bounds. • Curbing unnecessary run-time checks is a major problem.
Type Inference (cont’d) • Pascal allows operations on sets: var A: B: C; i: set of 1. . 10; set of 10. . 20; set of 1. . 15; 1. . 30; C : = A + B * [1. . 5, i]; • The type of the expression is set of integer (the base type). Range check is required when assigning to C.
Type Inference (cont’d) • Type safety in Java
Records (structs) and Variants (unions) • In Pascal,
Records (structs) and Variants (unions) • Representation in Pascal:
Records (structs) and Variants (unions, cont’d) • Usage: var copper: element; copper. name : = 'Cu'; • Record can be "packed", filing in holes, but forcing compiler to generate code that can access fields using multiinstruction sequences (less efficient).
Records (structs) and Variants (unions, cont’d) • Packed Representation
Records (structs) and Variants (unions, cont’d) • Usage: element copper; strcpy(copper. name, "Cu");
Records (structs) and Variants (unions, cont’d) • Most languages allow assignment of one record to another, but if not, a "block_copy" routine can solve the problem. • Most languages don't allow equality comparison. A "block_compare" routine might have problems with garbage in the holes.
Records (structs) and Variants (unions, cont’d) • Compilers often rearrange fields to reduce space:
Records (structs) and Variants (unions) • In Pascal,
Pascal with Statements • Introduce a nested scope, in which record fields are visible without record name. • Useful for deeply nested structures. • Example: with copper do begin name : = 'Cu'; atomic_number : = 29; atomic_weight : = 63. 546 metallic : = true; end;
Pascal with Statements (cont’d) • Problems with Pascal's with statement: 1. Can only manipulate fields of ONE record, not two. Not a shortcut for copying fields from one record to another. 2. Local names that match field name become inaccessible. 3. Can be difficult to read, especially in long or deeply nested with statements.
Pascal with Statements (cont’d) • Module-2 allows aliases for complicated expressions: WITH e=copper DO BEGIN e. name : = 'Cu'; e. atomic_number : = 29; e. atomic_weight : = 63. 546 e. metallic: = true; END;
Pascal with Statements (cont’d) • Can access one than one record at a time: WITH e=copper, f=iron DO e. metallic : = f. metallic; END;
Pascal with Statements (cont’d) • In Modula-3, the with statement goes further: WITH d = (. . . ) DO IF d <> 0 THEN val : = n/d ELSE val : = 0;
Pascal with Statements (cont’d) • C gets around this using the conditional expression: { double d = (. . . ); val = (d ? n/d : 0); }
Pascal with Statements (cont’d) • C has no need for a with statement, just use pointers: element *e = {. . . } element *f = {. . . } e->name = f->name; e->atomic_number = f. atomic_number; e->atomic_weight = f. atomic_weight; e->metallic = f. metallic ;
Variant Records • Choice between alternative fields. • Only one is valid at any given time.
Example (Pascal)
Example (Pascal, cont’d) • "naturally_occuring" is the "tag", which indicates whether the element contains 1. A source and a prevalence, or 2. A half_life.
Example (Pascal, cont’d)
In C
Variant Records (cont’d) • Unions are not integrated with structs, so there additional names: element e; e. extra_fields. natural_info. source = 3; e. extra_fields. half_life = 3. 5;
Variant Records (cont’d) • In general, type safety is compromised: type tag = (is_int, is_real, is_bool); var irb: record case which: tag of is_int: (i: integer); is_real: (r: real); is_bool: (b: Boolean); end;
Variant Records (cont’d) • Usage: irb. which : = is_real; irb. r : = 3. 0; irb. i : = 7; (* run-time error *)
Variant Records (cont’d) • Changing the tag field should make all other fields in the variant uninitialized, but it's very expensive to keep track of at run-time. Most compilers won't catch this: irb. which : = is_real; irb. r : = 3. 0; irb. which : = is_int; writeln(irb. i); (* uninitialized, or worse, shares space with irb. r *)
Variant Records (cont’d) • Worse yet, the tag field is optional: type tag = (is_int, is_real, is_bool); var irb: record case tag of is_int: (* 'which' field is gone ! *) (i: integer); is_real: (i: real); is_bool: (i: Boolean); end;
Variant Records (cont’d) • No way to catch irb. r : = 3. 0; writeln(irb. i); • Designers of Modula-3 dropped variant records, for these safety reasons. • Similarly, designers of Java dropped union of C and C++.
Variants in Ada • Must have a tag (discriminant). • If tag changes, all fields in the variant must be changed, by • assigning a whole record (A : = B; ), or • assigning an aggregate.
Example (with discriminant default value)
Variants in Ada (cont’d) • Declaration can use the default: copper: element; • Declaration can override the default: plutonium: element (false); americium: element (naturally_occuring => false);
Variants in Ada (cont’d) • The type declaration may: • provide a default (constrained discriminant), which cannot be changed. • not provide a default (unconstrained discriminant); then every variable declaration must do so, and the tag may be changed.
Variants in Ada (cont’d) • In short, discriminants are never uninitialized. • In Ada, variants are required to appear at the end of the record. • The compiler assigns a constant address to every field.
Variants in Modula-2 • In Modula-2, this restriction is dropped. Usually, a fixed address is assigned to each field, leaving holes where variants differ in size.
Variants in Modula-2 (cont’d)
What are Main Issues in Type Checking? m CSE m 4102 m m m A Higher Level View Type Equivalence: q Conditions under which Types are the Same Tracking of Scoping – Nested Declarations Type Compatibility q Conversion/casting, Nonconverting casts, Coercion Type Inference q Determining the Type of a Complex Expression Reviewing Remaining Concepts of Note q Overloading, Polymorphism, Generics From: Chapter 6 of Compilers: Principles, Techniques and Tools, Aho, et al. , Addison-Wesley OV-128
Structural vs. Name Equivalence of Types m CSE 4102 m Two Types are “Structurally Equivalent” iff they are Equivalent Under Following 3 Rules: q SE 1: A Type Name is Structurally Equivalent to Itself q SE 2: T 1 and T 2 are Structurally Equivalent if they are Formed by Applying the Same Type Constructors to Structurally Equivalent Types q SE 3: After a Type Declaration: Type n=T, the Type Name n is Structurally Equivalent to T q SE 3 is “Name Equivalence” What Do Programming Languages Use? q C: All Three Rules q Pascal: Omits SE 2 and Restricts SE 3 to be a Type Name can only be Structurally Equivalent to Other Type Names OV-129
Type Equivalence m CSE 4102 m m Structural equivalence: equivalent if built in the same way (same parts, same order) Name equivalence: distinctly named types are always different Structural equivalence questions q What parts constitute a structural difference? Ø Storage: record fields, array size Ø Naming of storage: field names, array indices Ø Field order q q How to distinguish between intentional vs. incidental structural similarities? An argument for name equivalence: “They’re different because the programmer said so; if they’re OV-130
Type Equivalence Records and Arrays m CSE 4102 Would record types with identical fields, but different name order, be structurally equivalent? type Pascal. Rec = record a : integer; b : integer end; val MLRec = { a = 1, b = 2 }; val Other. Rec = { b = 2, a = 1 }; m When are arrays with the same number of elements structurally equivalent? type str = array [1. . 10] of integer; type str = array [1. . 2 * 5] of integer; type str = array [0. . 9] of integer; OV-131
Consider Name Equivalence in Pascal m CSE m 4102 m type link = cell; How are Following Compared: var next : link; By Rules SE 1, SE 2, SE 3, all last : link; are Equivalent! p : cell; However: q, r : cell; q Some Implementations of Pascal Ø next, last – Equivalent Ø p, q, r, - Equivalent q Other Implementations of Pascal Ø next, last – Equivalent Ø q, r, - Equivalent m How is Following Interpreted? type var link = cell; npr = cell; next : link; last : link; p : np; q, r : npr; OV-132
What about Classes and Equivalence? m CSE 4102 Are these SE 1? SE 2? Or SE 3? public class person { public class user { private String lastname, firstname; private String login. ID; private String password; }; m }; What Does Java Require? OV-133
Alias Types and Name Equivalence m CSE 4102 Alias types are types that purely consist of a different name for another type TYPE Stack_Element = INTEGER; Level = INTEGER; Celsius = REAL; Fahrenheit = REAL; Is Integer assignable to a Stack_Element? Levels? q Can a Celsius and Fahrenheit be assigned to each other? Strict name equivalence: aliased types are distinct Loose name equivalence: aliased types are equivalence Ada allows additional explicit equivalence control: q m m m subtype Stack_Element is integer; type Celsius is new real; type Fahrenheit is new real; OV-134
Why is Degree of Type Equivalence Critical? CSE 4102 m Governs how Software Engineers Develop Code… Why? m SE 2 Alone Doesn’t Promote Well Designed, Thought Out, Software … Why? m Impacts on Team-Oriented Software Development… How? m With SE 2 Alone, Errors are Harder to Locate and Correct… Why? OV-135
Type Conversion m CSE 4102 m Certain contexts in certain languages may require exact matches with respect to types: q a. Var : = an. Expression q value 1 + value 2 q foo(arg 1, arg 2, arg 3, … , arg. N) Type conversion seeks to follow these exact match rules while allowing programmers some flexibility in the values used q Using structurally-equivalent types in a nameequivalent language q Types whose value ranges may be distinct but intersect (e. g. subranges) q Distinct types with sensible/meaningful corresponding values (e. g. integers and floats) OV-136
Type Conversion m CSE 4102 m m m Refers to the Conversion Between Different Types to Carry out Some Action in a Program Often Abused within a Programming Language (C) Typically Used in Arithmetic/Boolean Expressions q r : = i + r; (Pascal) q f : = i + c; (C) Two Kinds of Conversion: q Implicit: Automatically done by Compiler q Explicit: Type-Casts: Programmer Initiated (Ord, Chr, Trunc) If X is a real array, which works faster? Why q for I: =1 to N do X[I] : = 1; q for I: =1 to N do X[I] : = 1. 0; A Good Optimizing Compiler will Convert 1 st option! OV-137
Type Casting Syntax m Ada n : integer; r : real; . . . r : = real(n); CSE 4102 m C/C++/Java // Sample is specific to Java, but shares common syntax. Object n; String s; . . . s = (String)n; m Some SQLs -- Timestamp is a built-in data type; char. Field is -- a varchar (string) field of some table. select char. Field: : timestamp from… OV-138
Non-Converting Type Casts m CSE 4102 m Type casts that explicitly preserve the internal bitlevel representation of values Common in manipulating allocated blocks of memory q Same block of memory may be viewed as arrays of characters, integers, or even records/structures q Block of memory may be read from a file or other external source that is initially viewed as a “raw” set of bytes OV-139
Non-Converting Type Casts - Examples m CSE 4102 Ada – Explicit Unchecked Conversion Subroutine function cast_float_to_int is new unchecked_conversion(float, integer); m C/C++ (Not Java): Pointer Games void *block; // Gets loaded up with some datafrom a file. Record *header = (Record *)block; // Record is struct. m • C++: explicit cast types static_cast, reinterpret_cast dynamic_cast int i = static_cast<int>(d); // Assume d is double. Record *header = reinterpret_cast<Record *>(block); Derived *d. Obj = dynamic_cast<Derived *>(base. Obj); // Derived is a subclass of Base. OV-140
Type Coercion m CSE 4102 Sometimes absolute type equivalence is too strict; type compatibility is sufficient q Type equivalence vs. type compatibility in Ada (strict): Ø Types must be equivalent Ø One type must be a subtype of another, or both are subtypes of the same base type Ø Types are arrays with the same sizes and element types in each dimension m m Pascal extends slightly, also allowing: q Base and subrange types are cross-compatible q Integers may be used where a real is expected Type coercion is an implicit type conversion between compatible but not necessarily equivalent types OV-141
Type Coercion Issues m CSE 4102 Sometimes viewed as a weakening of type securit. Y q Mixing of types without explicit indication of intent q Opposite end of the spectrum: C and Fortran Ø Allow interchangeable use of numeric types Ø Fortran: arithmetic can be performed on entire arrays Ø C: arrays and pointers are roughly interchangeable m C++ Add Programmer Extensible Coercion Rules class ctr { public: ctr(int i = 0, char* x = "ctr") { n = i; strcpy(s, x); } ctr& operator++(int) { n++; return *this; } operator int() { return n; } // Coercion to int operator char*() { return s; } // Coercion to char * private: int n; char s[64]; }; OV-142
Type Inference m CSE 4102 m m m Type inference refers to the process of determining the type of an arbitrarily complex expression Generally not a huge issue — most of the time, the type for the result of a given operation or function is clearly known, and you just “build up” to the final type as you evaluate the expression In languages where an assignment is also an expression, the convention is to have the “result” type be the type of the lefthandside But, there are occasional issues, specifically with subrange and composite types OV-143
Examples of Type Inference m CSE 4102 Subranges — in languages that can define types as subranges of base types (Ada, Pascal), type inference can be an issue: type Atype = 0. . 20; Btype = 10. . 20; var a : Atype; b : Btype; c : ? ? ; c : = a + b; m What should c’s type be? q Easy answer: always go back to the base type (integer in this case) OV-144
Examples of Type Inference m CSE 4102 What if the result of an expression is assigned to a subrange? q a : = 5 + b; (* a and b are defined on last slide *) q The primary question is bounds checking — operations on subranges can certainly produce results that break away from their defined bounds q Static checks: include code that infers the lowest and highest possible results from an expression q Dynamic check: static checks are not always possible, so the last resort is to check the result at runtime OV-145
Examples of Type Inference m CSE 4102 m Composite types q What is the type of operators on arrays? q We know it’s an array, but what specifically? (particularly for languages where the index range is part of the array definition) Examples: q Strings in languages where strings are exactly character arrays (Pascal, Ada) OV-146
Examples of Type Inference m CSE 4102 m Sets q In languages that encode a base type with a set (e. g. set of integer), what is the “type” of unions, intersections, and differences of sets? Examples: q Particularly tricky when a set is combined with a subrange q Same as subrange handling: static checks are possible in some cases, but dynamic checks are not completely avoidable var A : set of 1. . 10; B : set of 10. . 20; C : set of 1. . 15; i : 1. . 30; . . . C : = A + B * [1. . 5, i]; OV-147
Overloading m CSE 4102 m m The Same Symbol has Different Meanings in Different Contexts Many Examples: q + : int q + : real q + : set (union) q + : string (concatenate) q == (compares multiple types) q … >> cout (outputs multiple types) Impacts on Conversion since During Code Generation we must Choose “Correct” Option based on Type OV-148
Overloading m CSE 4102 m Coercion Requires the Need to Convert Expression Before Generating Code q real : = real * int – need to use real * q real : = real * int_to_real(int) – do the conversion q After Conversion, Code Generation can Occur Overloading has Increased Attention with Emergence of Object-Oriented Langauges q C++ and Java Allow User Defined Overloaded Definitions for +, -, *, etc. q Programmer Definable Routines (e. g. , SORT) can be Overloaded based on Type OV-149
Overloading m CSE 4102 m m A very handy mechanism q Available in C++/Java/. . . What is it? q Provide multiple definition of the same function over different types. Example [C++] int operator+(int a, int b); float operator+(float a, float b); float operator+(float a, int b); float operator+(int a, float b); Complex operator+(Complex a, Complex b); . . OV-150
Polymorphism m CSE 4102 m m Essential Concept: A Function is Polymorphic if it can be Utilized with Arguments/Parameters of More than 1 Type The EXACT, SAME, Piece of Code is being Utilized Why is Polymorphism Important? q Consider a List of Items in C: struct item { int info; struct item *next; } q Write a Length Function function LEN(list: *item) : integer; In theory – only need to access *next … q However, in C, you can’t reuse this Length Function for Different Structures q Write a Similar Version for Each Different Structure OV-151
Polymorphism m CSE m 4102 m m m Allows us to write Type Independent Code Polymorphism is Supported in ML, a Strongly Type Functional Programming Language: fun length (lptr) = if null (lptr) then 0 else length(tail(lptr)) + 1; Overloading is an Example of ad-hoc Polymorphism Parametric Polymorphism Essentially has Type as a Parameter to Function q Stack Operations: Create (T: stack_type) q Arithmetic Operations: Plus (X, Y: T: T is a type) This leads to Generics! OV-152
Generics CSE 4102 m m m Classic Programming Problem q Develop Stack or List Code in C that Applies to a Single Type (e. g. , List of Deli. Items) q Need Same Code for Produce. Items, Meat. Items, etc. , Copy and Edit Original Code q Minimal Reuse, Error Prone, Time Consuming What do Generics Offer? q A Type-Parameterizable Class q Abstracts Similar Behavior into a Common Interface q Reusable and Consistent Class Illustrate via C++ OV-153
A Generic Stack Class CSE 4102 template <class T> stack { private: T* st, int top; int size; public: void stack(int x) {st = new T[x]; top = 0; size = x; } stack() {st = new T[100]; top = 0; size = 100; } ~stack() {delete st; } push(T entry) { st[top++] = entry; } }; main() { stack<int> S 1(10); // Creates int Stack with 10 Slots stack<char> S 2; // Creates char Stack with 100 Slots stack<Item> Item. DB(10000); // Stack of Grocery Items } OV-154
A Generic Set Class CSE 4102 template <class Item. Type> class Set { DLList<Item. Type>* _members; // Set Templates Uses Double-Linked List Template public: Set() { _members = new DLList<Item. Type>(); } void Add(Item. Type* member) {_members->queue(member); } void Remove(Item. Type* member) {_members->remove(member); } int Member(Item. Type* member) {return _members->is. Member(member); } int Null. Set(){return _members->is. Empty(); } } main() { Set<int> Int. Set; // Creates an Integer Set<Item> Item. DB; // Creates an Item Set } OV-155
Generics m CSE 4102 Imagine a code fragment that q Computes the length of a list q Java-style class List. Node<T> { T data; Node<T> next; Node<T>(T d, Node<T> n) { data = d; next = n; } int length() { if (next != null) return 1 + next. length(); else return 1; } } This does not refer to T at all, it can be implemented only once! So. . . What is the type of this method ? OV-156
Benefits of Generics m CSE 4102 m m Strong Promotion of Reuse q Develop Once, Use Often q stack and Set Examples Eliminate Errors and Inconsistencies Between Similar and Separate Classes q Simplifies Maintenance Problems q Focuses on Abstraction and Design Promotes Correctness and Consistent Program Behavior q Once Designed/Developed, Reused with Consistent Results q If Problems, Corrections in Single Location OV-157
https: //adamdoupe. com/teaching/classes/cse 340 -principles-of -programming-languages-f 15/slides/05 -Type-Systems. pptx Type Systems CSE 340 – Principles of Programming Languages Fall 2015 Adam Doupé Arizona State University http: //adamdoupe. com
Type Compatibility • Which assignments are allowed by the type system? – a = b; ? – int a; float b; – float a; int b; Adam Doupé, Principles of Programming Languages 159
Type Inference • Types of expressions or other constructs as a function of subexpression types –a+b • a int; b float – Returns a float in C – Error in ML –a*b • a string; b int – Error in most languages – Returns a string in Python Adam Doupé, Principles of Programming Languages 160
Type Compatibility • Principally about type equivalence – How to determine if two types are equal? Type cm : integer; Type inch : integer; cm x; inch y; x = y? Adam Doupé, Principles of Programming Languages 161
Name Equivalence • Types must have the exact same name to be equivalent Type cm : integer; Type inch : integer; cm x; inch y; x = y? // ERROR Adam Doupé, Principles of Programming Languages 162
Name Equivalence a: array [0. . 4] of int; b: array [0. . 4] of int; • a = b? – Not allowed under name equivalence Adam Doupé, Principles of Programming Languages 163
Name Equivalence a, b: array [0. . 4] of int; • a = b? – Not allowed because array [0. . 4] of int is not named Adam Doupé, Principles of Programming Languages 164
Name Equivalence Type A: array [0. . 4] of int; a: A; b: A; • a = b? – Allowed, because both a and b have the same name Adam Doupé, Principles of Programming Languages 165
Internal Name Equivalence • If the program interpreter gives the same internal name to two different variables, then they share the same type a, b: array [0. . 4] of int; c: array [0. . 4] of int; • a = b? – Yes, because interpreter/compiler gives the same internal name to a and b • a = c? – No, because interpreter/compiler gives different internal name to c than to a and b Adam Doupé, Principles of Programming Languages 166
Structural Equivalence 1. Same built-in types 2. Pointers to structurally equivalent types Type cm : integer; Type inch : integer; cm x; inch y; x = y? // Allowed! Adam Doupé, Principles of Programming Languages 167
Structural Equivalence int* a; float* b; • a = b? – Not structurally equivalent, because int and float are not structurally equivalent Adam Doupé, Principles of Programming Languages 168
Structural Equivalence 3. Determining structural equivalence – Two structures – st 1 { x 1: W 1, x 2: W 2, …, xk: Wk } – st 2 { y 1: Q 1, y 2: Q 2, . . . , yk: Qk } – st 1 and st 2 are structurally equivalent iff • • W 1 structurally equivalent to Q 1 W 2 structurally equivalent to Q 2. . . Wk structurally equivalent to Qk Adam Doupé, Principles of Programming Languages 169
Structural Equivalence struct A { a: int, b: float } struct B { b: int, a: float } A foo; B bar; • foo = bar? Adam Doupé, Principles of Programming Languages 170
Structural Equivalence struct A { a: int, b: float } struct B { b: float, a: int } A foo; B bar; • a = b? Adam Doupé, Principles of Programming Languages 171
Structural Equivalence 4. Determining array structural equivalence – – Two Arrays T 1 = array range 1 of t 1 T 2 = array range 2 of t 2 T 1 and T 2 are structurally equivalent iff: • • range 1 and range 2 have (1) the same number of dimensions and (2) the same number of entries in each dimension t 1 and t 2 are structurally equivalent Adam Doupé, Principles of Programming Languages 172
Structural Equivalence 5. Determining function structural equivalence – – Two functions T 1 = function of (t 1, t 2, t 3, …, tk) returns t T 2 = function of (v 1, v 2, v 3, . . . , vk) returns v T 1 and T 2 are structurally equivalent iff: • • For all i from 1 to k, ti is structurally equivalent to vi t is structurally equivalent to v Adam Doupé, Principles of Programming Languages 173
Determining Structural Equivalence • The goal is to determine, for every pair of types in the program, if they are structurally equivalent • Seems fairly simple, just keep applying the previous 5 rules until the base case 1 or 2 is reached • How to handle the following case: T 1 = struct { a: int; p: pointer to T 2; } T 2 = struct { a: int; p: pointer to T 1; } • Applying the rules states that T 1 is structurally equivalent to T 2 iff pointer to T 1 is structurally equivalent to pointer to T 2, which is true if T 1 is structurally equivalent to T 2 Adam Doupé, Principles of Programming Languages 174