Chapter 4 of Programming Languages by Ravi Sethi.

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms
Advertisements

Names and Bindings.
Chapter 7:: Data Types Programming Language Pragmatics
Copyright © 2005 Elsevier Chapter 7:: Data Types Programming Language Pragmatics Michael L. Scott.
1 Introduction to Data Types (Section 7.1) CSCI 431 Programming Languages Fall 2003 A compilation of material developed by Felix Hernandez-Campos and Michael.
Elementary Data Types Prof. Alamdeep Singh. Scalar Data Types Scalar data types represent a single object, i.e. only one value can be derived. In general,
CSCI 330: Programming Language Concepts Instructor: Pranava K. Jha
Chapter 5: Elementary Data Types Properties of types and objects –Data objects, variables and constants –Data types –Declarations –Type checking –Assignment.
Chapter Four Data Types Pratt 2 Data Objects A run-time grouping of one or more pieces of data in a virtual machine a container for data it can be –system.
CS 331, Principles of Programming Languages Chapter 4 Types: Data Representation.
Type Checking.
Compiler Construction
CS 355 – Programming Languages
Chapter 6 Structured Data Types Arrays Records. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Definitions data type –collection of data objects.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 5 Types Types are the leaven of computer programming;
Names, Bindings, Type Checking, and Scopes
ISBN Chapter 6 Data Types: Structured types.
ISBN Chapter 5 Names, Bindings, Type Checking, and Scopes Names Variables The Concept of Binding Type Checking Strong Typing Type Compatibility.
G. Levine Chapter 6 Chapter 6 Encapsulation –Why do we want encapsulation? Programmer friendliness- programmer need not know about these details –Easier.
Copyright © 1995 by Addison-Wesley Publishing Co. 1 Names - Design issues: - Maximum length? - Are connector characters allowed? - Are names case sensitive?
1 Type Type system for a programming language = –set of types AND – rules that specify how a typed program is allowed to behave Why? –to generate better.
Chapter 6 Structured Data Types Arrays Records. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Definitions data type –collection of data objects.
Data Types. Primitives Integer Float Character Boolean Pointers Aggregates Strings Records Enumerated Arrays Objects.
1 Adapted from slides for COMP 144 Programming Language Concepts Spring 2002 by Felix Hernandez-Campos The University of North Carolina at Chapel Hill.
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
1 CS Programming Languages Class 07 September 14, 2000.
Names Variables Type Checking Strong Typing Type Compatibility 1.
5-1 Chapter 5: Names, Bindings, Type Checking, and Scopes Variables The Concept of Binding Type Checking Strong Typing Type Compatibility Scope and Lifetime.
CSE 425: Data Types II Survey of Common Types I Records –E.g., structs in C++ –If elements are named, a record is projected into its fields (e.g., via.
March 12, ICE 1341 – Programming Languages (Lecture #6) In-Young Ko Programming Languages (ICE 1341) Lecture #6 Programming Languages (ICE 1341)
1 COSC3306: Programming Paradigms Lecture 2: Data Types Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.
Introduction A variable can be characterized by a collection of properties, or attributes, the most important of which is type, a fundamental concept in.
1 Type Checking Type checking ensures that the operands and the operator are of compatible types Generalized to include subprograms and assignments Compatible.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
1 Records Record aggregate of data elements –Possibly heterogeneous –Elements/slots are identified by names –Elements in same fixed order in all records.
Ch. 5 Ch. 51 jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (more notes) Dr. Carter Tiernan.
Polymorphism Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 7.3.
Types(1). Lecture 52 Type(1)  A type is a collection of values and operations on those values. Integer type  values..., -2, -1, 0, 1, 2,...  operations.
1 CS Programming Languages Class 09 September 21, 2000.
Structure of Programming Languages Names, Bindings, Type Checking, and Scopes.
Ch. 5 Ch. 51 jcmt Summer 2003Programming Languages CSE3302 Programming Languages (more notes) Summer 2003 Dr. Carter Tiernan.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Variables reference, coding, visibility. Rules for making names  permitted character set  maximum length, significant length  case sensitivity  special.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
1 Structure of Compilers Lexical Analyzer (scanner) Modified Source Program Parser Tokens Semantic Analysis Syntactic Structure Optimizer Code Generator.
Data Types (3) 1 Programming Languages – Principles and Practice by Kenneth C Louden.
ISBN Chapter 6 Data Types. Copyright © 2006 Addison-Wesley. All rights reserved.2 Primitive Data Types Almost all programming languages.
Names, Scope, and Bindings Programming Languages and Paradigms.
Programming Language Theory 2011, 1 Chap. 7 :: Data Type Michael L. Scott.
CSI 3125, Data Types, page 1 Data types Outline Primitive data types Structured data types Strings Enumerated types Arrays Records Pointers Reading assignment.
Dr. M. Al-Mulhem Introduction 1 Chapter 6 Type Systems.
Data Types Chapter 6: Data Types Lectures # 11. Topics Introduction Primitive Data Types Character String Types Array Types Associative Arrays Record.
Data Types In Text: Chapter 6.
Names and Attributes Names are a key programming language feature
Chapter 6 – Data Types CSCE 343.
Type Checking Generalizes the concept of operands and operators to include subprograms and assignments Type checking is the activity of ensuring that the.
Type Checking, and Scopes
Compilers Principles, Techniques, & Tools Taught by Jing Zhang
Lecture 16: Introduction to Data Types
CS 326 Programming Languages, Concepts and Implementation
Records Design Issues: 1. What is the form of references?
Complex Data Types One very important measure of the “goodness” of a PL is the capability of its data types to model the problem space variables Design.
Names and Binding In Text: Chapter 5.
Chapter 6 Data Types.
Compiler Construction
Course Overview PART I: overview material PART II: inside a compiler
Compiler Construction
Lecture 7: Types (Revised based on the Tucker’s slides) 10/4/2019
Presentation transcript:

Chapter 4 of Programming Languages by Ravi Sethi

TYPES:DATA REPRESENTATION The Role of TypesThe Role of Types Basic TypesBasic Types Arrays: Sequences of ElementsArrays: Sequences of Elements Records: Named FieldsRecords: Named Fields Unions and Variant RecordsUnions and Variant Records SetsSets Pointers: Efficiency and Dynamic AllocationPointers: Efficiency and Dynamic Allocation Two String TablesTwo String Tables Types and Error CheckingTypes and Error Checking

THE ROLE OF TYPES Data objects and Data representationData objects and Data representation Objects in an application have corresponding representations in a program. Objects in an application have corresponding representations in a program. Example: correspondence between application and program Example: correspondence between application and program application program application program data January data January data May data May variable d n(integer #) variable d n(integer #) operation tomorrow (d) n+1 operation tomorrow (d) n+1 Values and Their TypesValues and Their Types 1. Basic type 1. Basic type 2. Constructed type 2. Constructed type

THE ROLE OF TYPES(cont’d) Type ExpressionType Expression a) Describes how a data representation is built up a) Describes how a data representation is built up B) Can be used to B) Can be used to 1. Represent data objects 1. Represent data objects 2. Lay out values in the underlying machine 2. Lay out values in the underlying machine 3. Check that operators are applied properly within expression 3. Check that operators are applied properly within expression Static Layout DecisionStatic Layout Decision (next slide) (next slide) A Preview of Type Names, Arrays, and RecordsA Preview of Type Names, Arrays, and Records 1. Type names: boolean, char, integer, real 1. Type names: boolean, char, integer, real 2. Arrays: a sequence of elements 2. Arrays: a sequence of elements 3. Records: a set of components, each with its own type 3. Records: a set of components, each with its own type

THE ROLE OF TYPES(cont’d)

BASIC TYPES Enumeration : a finite sequence of names written between parenthesesEnumeration : a finite sequence of names written between parentheses type day = (Mon, Tue, Wed, Thu, Fir, Sat, Sun); type day = (Mon, Tue, Wed, Thu, Fir, Sat, Sun); Integers and RealsIntegers and Reals Short-Circuit Evaluation of Boolean ExpressionsShort-Circuit Evaluation of Boolean Expressions Example : While (i >= 0 && x != A[ i ]) i = i-1 ; Example : While (i >= 0 && x != A[ i ]) i = i-1 ; Subranges : a special case of basic types that restrict the range of values of an existing type - weekends, weekdaysSubranges : a special case of basic types that restrict the range of values of an existing type - weekends, weekdays

BASIC TYPES (cont’d) Programming Style: Characters and Type ConversionProgramming Style: Characters and Type Conversion Example : Example : C : characters are implicitly coerced to integers C : characters are implicitly coerced to integers int c; int c; c = getchar(); -> coerced to an int c = getchar(); -> coerced to an int Pascal : Conversion will be done explicitly Pascal : Conversion will be done explicitly c = chr(ord(c)) c = chr(ord(c)) i = ord(chr(i)) i = ord(chr(i))

ARRAYS: SEQUENCES OF ELEMENTS Efficient access and storage allocationEfficient access and storage allocation Indexed by integers or enumerationsIndexed by integers or enumerations Array layoutArray layout 1. Elements appear in consecutive location in the underlying machine 1. Elements appear in consecutive location in the underlying machine 2. Elements can be computed in two parts 2. Elements can be computed in two parts a) Pre-computation a) Pre-computation b) Run time b) Run time 3. Arrays of Arrays : row-major layout, column-major layout 3. Arrays of Arrays : row-major layout, column-major layout

ARRAYS: SEQUENCES OF ELEMENTS (cont’d) Array BoundsArray Bounds a) Computed at compile time (Static evaluation) a) Computed at compile time (Static evaluation) b) Computed at run time (Dynamic evaluation) b) Computed at run time (Dynamic evaluation) Array Values and Initialization : a sequence of values for array elementsArray Values and Initialization : a sequence of values for array elements Example: int coin[] = { 1, 5, 10, 25, 50, 100 }; Example: int coin[] = { 1, 5, 10, 25, 50, 100 };

RECORDS: NAMED FIELDS A record type is a templateA record type is a template A Variable declaration allocates storageA Variable declaration allocates storage Operations on RecordsOperations on Records Example : z. re := x. re + y. re Example : z. re := x. re + y. re A comparison of Arrays and RecordsA comparison of Arrays and Records arraysrecords arraysrecords component types homogeneousheterogeneous component selectors expressions evaluated names known at at run time compile time at run time compile time

UNIONS AND VARIANT RECORDS Union : a special case of a variant record with an empty common partUnion : a special case of a variant record with an empty common part Variant record : a part common to all records of that type and a variant partVariant record : a part common to all records of that type and a variant part figure 4.7 (next slide)figure 4.7 (next slide)

UNIONS AND VARIANT RECORDS(cont’d)

Layout of Variant RecordsLayout of Variant Records 1. Fixed Part 1. Fixed Part 2. Tag Field 2. Tag Field 3. Variant Part 3. Variant Part Variant Records compromise type safetyVariant Records compromise type safety

SETS Set Values:in Pascal, All elements must be of the same simple typeSet Values:in Pascal, All elements must be of the same simple type Set Types: Type set of S represents subsets of SSet Types: Type set of S represents subsets of S Example: var A : set of [1..3] Example: var A : set of [1..3] A can denote one of the following sets: A can denote one of the following sets: [ ],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3] [ ],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3] A set of n elements: implemented as a bit vector of length nA set of n elements: implemented as a bit vector of length n The basic operation on set is a membership testThe basic operation on set is a membership test

POINTERS: EFFICIENCY AND DYNAMIC ALLOCATION More efficient to move or copy a pointer to the data structureMore efficient to move or copy a pointer to the data structure Dynamically Implemented to use in data structureDynamically Implemented to use in data structure First-class citizensFirst-class citizens Pointer type must be declared before usedPointer type must be declared before used Dereferencing operation : indirect accessDereferencing operation : indirect access Example Pascal: dynamic allocation on the heap, dereferencing, assignment, equality testing, deallocation Example Pascal: dynamic allocation on the heap, dereferencing, assignment, equality testing, deallocation Serve as links between cells (linked lists)Serve as links between cells (linked lists) Type and layout of storage are known statically before a program runsType and layout of storage are known statically before a program runs

POINTERS: EFFICIENCY AND DYNAMIC ALLOCATION(cont’d) The pointer operations affect access to storageThe pointer operations affect access to storage Dangling pointer is a pointer to storage that is being used for another purpose (deallocate the storage, but the reference to the pointer is still there)Dangling pointer is a pointer to storage that is being used for another purpose (deallocate the storage, but the reference to the pointer is still there) Pascal restricts pointer operations (only new and dispose); C stresses flexibilityPascal restricts pointer operations (only new and dispose); C stresses flexibility Rearranged inexpensivelyRearranged inexpensively

TWO STRING TABLES From a distance, types in Pascal and C are very similar, both have arrays, records and pointers. Differences in the treatment of pointers, lead to differences in style. The variable-length string application is famous and is used to show the differences (section 4.8)From a distance, types in Pascal and C are very similar, both have arrays, records and pointers. Differences in the treatment of pointers, lead to differences in style. The variable-length string application is famous and is used to show the differences (section 4.8) PascalPascal TeXTeX trofftroff WordWord all the words are in a pool (buffer), the words are index through an array called start which contains the beginning position of the word in the pool starting at 0 so start[0] = 0 and pool[start[0]] is the ’T’all the words are in a pool (buffer), the words are index through an array called start which contains the beginning position of the word in the pool starting at 0 so start[0] = 0 and pool[start[0]] is the ’T’ Indirect access through an array Indirect access through an array Integers as pointers - disadvantage compiler cannot check that it is a character Integers as pointers - disadvantage compiler cannot check that it is a character

TWO STRING TABLES From Yacc - Yet another Compiler CompilerFrom Yacc - Yet another Compiler Compiler start is the actual pointer address in pool not just an indexstart is the actual pointer address in pool not just an index C 1. Indirect access through pointers 1. Indirect access through pointers 2. Array name : pointer to a zeroth element - operations on pointers in C allow successive characters in a string to be accessed 2. Array name : pointer to a zeroth element - operations on pointers in C allow successive characters in a string to be accessed 3. Dereferencing and yielding operators 3. Dereferencing and yielding operators Example: p = &x; Example: p = &x; *p = *p + 1; is same as x = x + 1; *p = *p + 1; is same as x = x + 1;

TYPES AND ERROR CHECKING Types extend from values to expressions, the type of an expression x + y can be inferred from the types x and yTypes extend from values to expressions, the type of an expression x + y can be inferred from the types x and y Types of variable bindingsTypes of variable bindings 1. Static or early bindings 1. Static or early bindings 2. Dynamic or late bindings 2. Dynamic or late bindings Pascal has static bindings of types and dynamic bindings of values to variables. Lisp has dynamic binding of both values and types Pascal has static bindings of types and dynamic bindings of values to variables. Lisp has dynamic binding of both values and types Type systems : a set of rulesType systems : a set of rules Basic rule of type checkingBasic rule of type checking 1. Overloading : Multiple Meanings 1. Overloading : Multiple Meanings 2. Coercion : conversion from one type to another 2. Coercion : conversion from one type to another 3. Polymorphism : parameterized type 3. Polymorphism : parameterized type

TYPES AND ERROR CHECKING(cont’d) Type names and type equivalenceType names and type equivalence Example : Example : x, y : array [0..9] of integer x, y : array [0..9] of integer z : array [0..9] of integer z : array [0..9] of integer In Pascal, x and y have the same type, but z does not In Pascal, x and y have the same type, but z does not * Structural Equivalence * Structural Equivalence 1. A type name is structurally equivalent to itself 1. A type name is structurally equivalent to itself 2. Two types are formed by applying the same type constructor 2. Two types are formed by applying the same type constructor 3. After a type declaration, type n = T 3. After a type declaration, type n = T

TYPES AND ERROR CHECKING(cont’d) * Forms of Name Equivalence * Forms of Name Equivalence 1. Pure name equivalence 1. Pure name equivalence 2. Transitive name equivalence, type S = integer; T = S; U = integer; 2. Transitive name equivalence, type S = integer; T = S; U = integer; 3. Type expression equivalence 3. Type expression equivalence * Type Equivalence - sometimes left ambiguous in Pascal, sometimes given rules like Modula-2 * Type Equivalence - sometimes left ambiguous in Pascal, sometimes given rules like Modula-2 * Circular Types : linked data structures give rise to recursive or circular * Circular Types : linked data structures give rise to recursive or circular types struct x { types struct x { int p; int p; struct x *next; struct x *next; }; };

TYPES AND ERROR CHECKING(cont’d) Static and Dynamic CheckingStatic and Dynamic Checking 1. Type error occurs if an operation is improperly applied 1. Type error occurs if an operation is improperly applied 2. Programs are checked statically 2. Programs are checked statically 3. Dynamic checking is done during program execution 3. Dynamic checking is done during program execution 4. Strong type ensures freedom from type errors 4. Strong type ensures freedom from type errors