Programming Language Theory 1

Total Page:16

File Type:pdf, Size:1020Kb

Programming Language Theory 1 Programming Language Theory 1 Lecture #6 2 Data Types Programming Language 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 C 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 Operating System: 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 imp lemented 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 brac ktkets • 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. Examp le:
Recommended publications
  • Software II: Principles of Programming Languages
    Software II: Principles of Programming Languages Lecture 6 – Data Types Some Basic Definitions • A data type defines a collection of data objects and a set of predefined operations on those objects • A descriptor is the collection of the attributes of a variable • An object represents an instance of a user- defined (abstract data) type • One design issue for all data types: What operations are defined and how are they specified? Primitive Data Types • Almost all programming languages provide a set of primitive data types • Primitive data types: Those not defined in terms of other data types • Some primitive data types are merely reflections of the hardware • Others require only a little non-hardware support for their implementation The Integer Data Type • Almost always an exact reflection of the hardware so the mapping is trivial • There may be as many as eight different integer types in a language • Java’s signed integer sizes: byte , short , int , long The Floating Point Data Type • Model real numbers, but only as approximations • Languages for scientific use support at least two floating-point types (e.g., float and double ; sometimes more • Usually exactly like the hardware, but not always • IEEE Floating-Point Standard 754 Complex Data Type • Some languages support a complex type, e.g., C99, Fortran, and Python • Each value consists of two floats, the real part and the imaginary part • Literal form real component – (in Fortran: (7, 3) imaginary – (in Python): (7 + 3j) component The Decimal Data Type • For business applications (money)
    [Show full text]
  • 16 Concurrent Hash Tables: Fast and General(?)!
    Concurrent Hash Tables: Fast and General(?)! TOBIAS MAIER and PETER SANDERS, Karlsruhe Institute of Technology, Germany ROMAN DEMENTIEV, Intel Deutschland GmbH, Germany Concurrent hash tables are one of the most important concurrent data structures, which are used in numer- ous applications. For some applications, it is common that hash table accesses dominate the execution time. To efficiently solve these problems in parallel, we need implementations that achieve speedups inhighly concurrent scenarios. Unfortunately, currently available concurrent hashing libraries are far away from this requirement, in particular, when adaptively sized tables are necessary or contention on some elements occurs. Our starting point for better performing data structures is a fast and simple lock-free concurrent hash table based on linear probing that is, however, limited to word-sized key-value types and does not support 16 dynamic size adaptation. We explain how to lift these limitations in a provably scalable way and demonstrate that dynamic growing has a performance overhead comparable to the same generalization in sequential hash tables. We perform extensive experiments comparing the performance of our implementations with six of the most widely used concurrent hash tables. Ours are considerably faster than the best algorithms with similar restrictions and an order of magnitude faster than the best more general tables. In some extreme cases, the difference even approaches four orders of magnitude. All our implementations discussed in this publication
    [Show full text]
  • Off-Heap Memory Management for Scalable Query-Dominated Collections
    Self-managed collections: Off-heap memory management for scalable query-dominated collections Fabian Nagel Gavin Bierman University of Edinburgh, UK Oracle Labs, Cambridge, UK [email protected] [email protected] Aleksandar Dragojevic Stratis D. Viglas Microsoft Research, University of Edinburgh, UK Cambridge, UK [email protected] [email protected] ABSTRACT sources. dram Explosive growth in DRAM capacities and the emergence Over the last two decades, prices have been drop- of language-integrated query enable a new class of man- ping at an annual rate of 33%. As of September 2016, servers dram aged applications that perform complex query processing with a capacity of more than 1TB are available for un- on huge volumes of data stored as collections of objects in der US$50k. These servers allow the entire working set of the memory space of the application. While more flexible many applications to fit into main memory, which greatly in terms of schema design and application development, this facilitates query processing as data no longer has to be con- approach typically experiences sub-par query execution per- tinuously fetched from disk (e.g., via a disk-based external formance when compared to specialized systems like DBMS. data management system); instead, it can be loaded into To address this issue, we propose self-managed collections, main memory and processed there, thus improving query which utilize off-heap memory management and dynamic processing performance. query compilation to improve the performance of querying Granted, the use-case of a persistent (database) and a managed data through language-integrated query.
    [Show full text]
  • 7.7.2 Dangling References
    DataTypes7 7.7.2 Dangling References Memory access errors—dangling references, memory leaks, out-of-bounds access to arrays—are among the most serious program bugs, and among the most difficult to find. Testing and debugging techniques for memory errors vary in when they are performed, how much they cost, and how conservative they are. Several commercial and open-source tools employ binary instrumentation (Sec- tion 15.2.3) to track the allocation status of every block in memory and to check every load or store to make sure it refers to an allocated block. These tools have proven to be highly effective, but they can slow a program several-fold, and may generate false positives—indications of error in programs that, while arguably poorly written, are technically correct. Many compilers can also be instructed to generate dynamic semantic checks for certain kinds of memory errors. Such checks must generally be fast (much less than 2× slowdown), and must never gen- erate false positives. In this section we consider two candidate implementations of checks for dangling references. Tombstones Tombstones [Lom75, Lom85] allow a language implementation can catch all dan- EXAMPLE 7.134 gling references, to objects in both the stack and the heap. The idea is simple: Dangling reference rather than have a pointer refer to an object directly, we introduce an extra level detection with tombstones of indirection (Figure 7.17). When an object is allocated in the heap (or when a pointer is created to an object in the stack), the language run-time system allocates a tombstone.
    [Show full text]
  • Concurrent Hash Tables: Fast and General?(!)
    Concurrent Hash Tables: Fast and General(?)! Tobias Maier1, Peter Sanders1, and Roman Dementiev2 1 Karlsruhe Institute of Technology, Karlsruhe, Germany ft.maier,[email protected] 2 Intel Deutschland GmbH [email protected] Abstract 1 Introduction Concurrent hash tables are one of the most impor- A hash table is a dynamic data structure which tant concurrent data structures which is used in stores a set of elements that are accessible by their numerous applications. Since hash table accesses key. It supports insertion, deletion, find and update can dominate the execution time of whole applica- in constant expected time. In a concurrent hash ta- tions, we need implementations that achieve good ble, multiple threads have access to the same table. speedup even in these cases. Unfortunately, cur- This allows threads to share information in a flex- rently available concurrent hashing libraries turn ible and efficient way. Therefore, concurrent hash out to be far away from this requirement in partic- tables are one of the most important concurrent ular when adaptively sized tables are necessary or data structures. See Section 4 for a more detailed contention on some elements occurs. discussion of concurrent hash table functionality. To show the ubiquity of hash tables we give a Our starting point for better performing data short list of example applications: A very sim- structures is a fast and simple lock-free concurrent ple use case is storing sparse sets of precom- hash table based on linear probing that is however puted solutions (e.g. [27], [3]). A more compli- limited to word sized key-value types and does not cated one is aggregation as it is frequently used support dynamic size adaptation.
    [Show full text]
  • Session 6: Data Types and Representation
    Programming Languages Session 6 – Main Theme Data Types and Representation and Introduction to ML Dr. Jean-Claude Franchitti New York University Computer Science Department Courant Institute of Mathematical Sciences Adapted from course textbook resources Programming Language Pragmatics (3rd Edition) Michael L. Scott, Copyright © 2009 Elsevier 1 Agenda 11 SessionSession OverviewOverview 22 DataData TypesTypes andand RepresentationRepresentation 33 MLML 44 ConclusionConclusion 2 What is the course about? Course description and syllabus: » http://www.nyu.edu/classes/jcf/g22.2110-001 » http://www.cs.nyu.edu/courses/fall10/G22.2110-001/index.html Textbook: » Programming Language Pragmatics (3rd Edition) Michael L. Scott Morgan Kaufmann ISBN-10: 0-12374-514-4, ISBN-13: 978-0-12374-514-4, (04/06/09) Additional References: » Osinski, Lecture notes, Summer 2010 » Grimm, Lecture notes, Spring 2010 » Gottlieb, Lecture notes, Fall 2009 » Barrett, Lecture notes, Fall 2008 3 Session Agenda Session Overview Data Types and Representation ML Overview Conclusion 4 Icons / Metaphors Information Common Realization Knowledge/Competency Pattern Governance Alignment Solution Approach 55 Session 5 Review Historical Origins Lambda Calculus Functional Programming Concepts A Review/Overview of Scheme Evaluation Order Revisited High-Order Functions Functional Programming in Perspective Conclusions 6 Agenda 11 SessionSession OverviewOverview 22 DataData TypesTypes andand RepresentationRepresentation 33 MLML 44 ConclusionConclusion 7 Data Types and Representation
    [Show full text]
  • Memory and Object Management in Ramcloud
    MEMORY AND OBJECT MANAGEMENT IN RAMCLOUD A DISSERTATION SUBMITTED TO THE DEPARTMENT OF COMPUTER SCIENCE AND THE COMMITTEE ON GRADUATE STUDIES OF STANFORD UNIVERSITY IN PARTIAL FULFILLMENT OF THE REQUIREMENTS FOR THE DEGREE OF DOCTOR OF PHILOSOPHY Stephen Mathew Rumble March 2014 © 2014 by Stephen Mathew Rumble. All Rights Reserved. Re-distributed by Stanford University under license with the author. This work is licensed under a Creative Commons Attribution- Noncommercial 3.0 United States License. http://creativecommons.org/licenses/by-nc/3.0/us/ This dissertation is online at: http://purl.stanford.edu/bx554qk6640 ii I certify that I have read this dissertation and that, in my opinion, it is fully adequate in scope and quality as a dissertation for the degree of Doctor of Philosophy. John Ousterhout, Primary Adviser I certify that I have read this dissertation and that, in my opinion, it is fully adequate in scope and quality as a dissertation for the degree of Doctor of Philosophy. David Mazieres, Co-Adviser I certify that I have read this dissertation and that, in my opinion, it is fully adequate in scope and quality as a dissertation for the degree of Doctor of Philosophy. Mendel Rosenblum Approved for the Stanford University Committee on Graduate Studies. Patricia J. Gumport, Vice Provost for Graduate Education This signature page was generated electronically upon submission of this dissertation in electronic format. An original signed hard copy of the signature page is on file in University Archives. iii Abstract Traditional memory allocation mechanisms are not suitable for new DRAM-based storage systems because they use memory inefficiently, particularly under changing access patterns.
    [Show full text]
  • PRINCIPLES of BIG DATA Intentionally Left As Blank PRINCIPLES of BIG DATA Preparing, Sharing, and Analyzing Complex Information
    PRINCIPLES OF BIG DATA Intentionally left as blank PRINCIPLES OF BIG DATA Preparing, Sharing, and Analyzing Complex Information JULES J. BERMAN, Ph.D., M.D. AMSTERDAM • BOSTON • HEIDELBERG • LONDON NEW YORK • OXFORD • PARIS • SAN DIEGO SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO Morgan Kaufmann is an imprint of Elsevier Acquiring Editor: Andrea Dierna Editorial Project Manager: Heather Scherer Project Manager: Punithavathy Govindaradjane Designer: Russell Purdy Morgan Kaufmann is an imprint of Elsevier 225 Wyman Street, Waltham, MA 02451, USA Copyright # 2013 Elsevier Inc. All rights reserved No part of this publication may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or any information storage and retrieval system, without permission in writing from the publisher. Details on how to seek permission, further information about the Publisher’s permissions policies and our arrangements with organizations such as the Copyright Clearance Center and the Copyright Licensing Agency, can be found at our website: www.elsevier.com/permissions. This book and the individual contributions contained in it are protected under copyright by the Publisher (other than as may be noted herein). Notices Knowledge and best practice in this field are constantly changing. As new research and experience broaden our understanding, changes in research methods or professional practices, may become necessary. Practitioners and researchers must always rely on their own experience and knowledge in evaluating and using any information or methods described herein. In using such information or methods they should be mindful of their own safety and the safety of others, including parties for whom they have a professional responsibility.
    [Show full text]
  • CS 230 Programming Languages
    CS 230 Programming Languages 11 / 06 / 2020 Instructor: Michael Eckmann Today’s Topics • Questions? / Comments? • More about Pointers vs. Reference types • Solutions to dangling pointers and memory leaks • Start C++ Michael Eckmann - Skidmore College - CS 230 - Fall 2020 Pointers • Reference types in C/C++ and Java and C# – C/C++ reference type is a special kind of pointer type • Used when declaring parameters to a function so that it is passed by reference • Formal parameter is specified with an & • But inside the function, it is implicitly dereferenced. – Makes code more readable and safer • Can get the same effect with regular pointers but code may be less readable (b/c explicit dereferencing required) and less safe Pointers • Reference types in C/C++ and Java and C# – C/C++ reference type is a special kind of pointer type • Would there be any use for passing by reference using a constant reference parameter (that is, one that disallows its contents to be changed)? – Java • References replace C++'s pointers – Why? • Java references refer to class instances (objects). • No dangling references b/c implicit deallocation Pointers • Reference types in C/C++ and Java and C# – C# • Has both Java-like references and C++-like pointers. • Pointers are discouraged --- methods that use pointers need to be modified with the unsafe keyword. Pointers • Implementation of pointers – Pointers hold an address • Solutions to dangling pointer problem – Tombstones • A tombstone points to (holds the address of) where the data is (a heap-dynamic variable.) • Pointers can only point to a tombstone (which in turn points to the actual data.) • What does this solve? • When deallocate, the tombstone is set to nil.
    [Show full text]