6. Names, Scopes, and Bindings

Total Page:16

File Type:pdf, Size:1020Kb

6. Names, Scopes, and Bindings Copyright (C) R.A. van Engelen, FSU Department of Computer Science, 2000-2004 Names and Abstractions: What's in a Name? Names enable programmers to refer to variables, constants, 6. Names, Scopes, and Bindings operations, and types using identifier names rather than low-level hardware components Overview Names also form control and data abstractions for complicated Names program fragments (control) and data structures Binding time Control abstraction: Object lifetime Subroutines (procedures and functions) allow programmers Object storage management to focus on manageble subset of program text Static allocation Subroutine interface hides implementation details, e.g. sort(MyArray) Stack allocation Data abstraction: Heap allocation Object-oriented classes hide data representation details Scope rules behind a set of operations Static and dynamic scoping Abstraction in the context of high-level programming languages Reference environments refers to the degree or level of language features Overloading Level of machine-independence "Power" of constructs Note: Study Chapter 3 of the textbook. Binding Time Language feature Binding time Syntax, e.g. if (a>0) b:=a; in C or Language design A binding is an association between a name and the thing that is if a>0 then b:=a end if in Ada named Keywords, e.g. class in C++ and Java Language design Binding time is the time at which an implementation decision is Reserved words, e.g. main in C and made to create a binding Language design writeln in Pascal 1. Language design time: the design of specific program constructs (syntax), primitive types, and meaning Meaning of operators, e.g. + (add) Language design (semantics) Primitive types, e.g. float Language design 2. Language implementation time: fixation of implementation and struct in C constants such as numeric precision, run-time memory sizes, Internal representation of literals, Language implementation max identifier name length, number and types of built-in e.g. 3.1 and "foo bar" exceptions, etc. The specific type of a variable in a Compile time 3. Program writing time: the programmer's choice of C or Pascal declaration algorithms and data structures Language design, 4. Compile time: the time of translation of high-level constructs Storage allocation method for a variable language implementation, to machine code and choice of memory layout for objects and/or compile time 5. Link time: the time at which multiple object codes (machine Linking calls to static library routines, code files) and libraries are combined into one executable Linker 6. Load time: the time at which the operating system loads the e.g. printf in C executable in memory Merging multiple object codes Linker 7. Run time: the time during which a program executes (runs) into one executable Loading executable in memory Loader (OS) and adjusting absolute addresses Binding Time Examples Nonstatic allocation of space for Run time variable The Effect of Binding Time Object Lifetime Early binding times (before run time) are associated with greater Key events in object lifetime efficiency Object creation Compilers try to fix decisions that can be taken at compile Creation of bindings time to avoid to generate code that makes a decision at run References to variables, subroutines, types are made using time bindings Syntax and static semantics checking is performed only once Deactivation and reactivation of temporarely unusable at compile time and does not impose any run-time overheads bindings Late binding times (at run time) are associated with greater Destruction of bindings flexibility Destruction of objects Interpreters allow programs to be extended at run time Binding lifetime: time between creation and destruction of Languages such as Smalltalk-80 with polymorphic types binding to object allow variable names to refer to objects of multiple types at E.g. a Java reference variable is assigned the address of an run time object Method binding in object-oriented languages must be late to E.g. a function's formal argument is bound to an actual support dynamic binding argument (object) Object lifetime: time between creation and destruction of an object Object Lifetime Example Object Storage Management Example C++ fragment: An object has to be stored in memory during its lifetime { SomeClass& myobject = *new SomeClass; Static objects have an absolute storage address that is retained ... throughout the execution of the program { OtherClass& myobject = *new OtherClass; Global variables ... myobject // is bound to other object ... Subroutine code } Class method code ... myobject // is visible again Stack objects are allocated in last-in first-out order, usually in ... delete myobject; conjunction with subroutine calls and returns } Actual arguments of a subroutine Local variables of a subroutine Heap objects may be allocated and deallocated at arbitrary times, but require an expensive storage management algorithm E.g. Java class instances are always stored on the heap recursive subroutines Typical Program and Data Layout in Memory Every (recursive) subroutine call must have separate Program code is at the bottom of the memory region (code instantiations of local variables section) Fortran 77 has no recursion Static data objects are stored in static region (data section) Both global and local variables can be statically allocated as Stack grows downward (data section) decided by compiler Heap grows upward (data section) Avoids overhead of creation and destruction of local objects for every subroutine call Stack Typical static subroutine data memory layout: ¯ Temporaries - (for intermediate values) Heap Local Static variables data Miscellaneous Program bookkeeping code (saved processor registers) Return address The code section is protected from run-time modification Arguments (in and out) Static Allocation Program code is statically allocated in most implementations of imperative languages Statically allocated variables are history sensitive Global variables static local variables in C function retain value even after function returns Advantage of statically allocated object is the fast access due to absolute addressing of the object Static allocation does not work for local variables in potentialy Stack-Based Allocation Subroutine A Temporaries Each instance of a subroutine at run time has a frame on the Local vars run-time stack (also called activation record) Bookkeeping Compiler generates subroutine calling sequence to setup ¬ fp (frame pointer) Return address Example C program frame, call the routine, and to destroy the frame afterwards Subroutine prologue and epilogue code operate and maintain Arguments main() the frame { ... Subroutine B A(); Frame layouts vary between languages and implementations Temporaries ... Typical frame layout: } Local vars Temporaries Bookkeeping A() Local vars { ... Return address B(); Bookkeeping ... Arguments Return address } Arguments Subroutine A B() Temporaries { ... A frame pointer (fp) points to the frame of the currently active A(); subroutine at run time (always topmost frame on stack) Local vars ... Subroutine arguments, local variables, and return values are Bookkeeping } accessed by constant address offsets from fp Return address main calls A, The stack pointer (sp) points to free space on the stack Arguments A calls B, B calls A Main program Stack-Based Allocation Example Temporaries Local vars - (growth) ¬ sp (stack pointer) Bookkeeping Return address Arguments Example Frame Heap-Based Allocation The word sizes of the types of local variables and arguments Implicit heap allocation: determines the fp offset in a frame Java class instances are always placed on the heap Scripting languages and functional languages make Temporaries extensive use of the heap for storing objects Local vars Some procedural languages allow array declarations with var offset size run-time dependent array size foo -18 2 words Example Pascal procedure Resizable character strings Explicit heap allocation: bar -16 4 words procedure P(a:integer, var b:real) (* a is passed by value Statements and/or functions for allocation and deallocation p -12 2 words b is passed by reference, Heap allocation is performed by searching heap for available which is a pointer to b's value Bookkeeping *) free space (offset = -10, 8 words) var foo:integer;(* integer: 2 words *) Object free (4 Object Object free (12 Object free (10 Return address bar:real; (* float: 4 words *) A words) B C words) D words) (offset = -2, 2 words) p:^integer; (* pointer: 2 words *) begin ¬ fp points here ... Request allocation for object E of 10 words: Arguments end arg offset size Object E (10 words) a 0 2 words Deletion of objects leaves free blocks in the heap that can be b 2 2 words reused Internal heap fragmentation: If allocated object is smaller than The compiler determines the slots for the local variables and the free block the extra space is wasted arguments in a frame External heap fragmentation: Smaller free blocks cannot always The fp of the previous active frame is saved in the current frame be reused resulting in wasted space and restored after the call Heap Allocation Algorithms Garbage Collection Maintain a linked list of free heap blocks Explicit manual deallocation errors are among the most First-fit: select the first block that is large enough on the list of expensive and hard to detect problems in real-world applications free heap blocks If an object is deallocated too soon, a reference to the object Best-fit: search entire list for the smallest free block that is large becomes a dangling
Recommended publications
  • Programming Languages
    Programming Languages Recitation Summer 2014 Recitation Leader • Joanna Gilberti • Email: [email protected] • Office: WWH, Room 328 • Web site: http://cims.nyu.edu/~jlg204/courses/PL/index.html Homework Submission Guidelines • Submit all homework to me via email (at [email protected] only) on the due date. • Email subject: “PL– homework #” (EXAMPLE: “PL – Homework 1”) • Use file naming convention on all attachments: “firstname_lastname_hw_#” (example: "joanna_gilberti_hw_1") • In the case multiple files are being submitted, package all files into a ZIP file, and name the ZIP file using the naming convention above. What’s Covered in Recitation • Homework Solutions • Questions on the homeworks • For additional questions on assignments, it is best to contact me via email. • I will hold office hours (time will be posted on the recitation Web site) • Run sample programs that demonstrate concepts covered in class Iterative Languages Scoping • Sample Languages • C: static-scoping • Perl: static and dynamic-scoping (use to be only dynamic scoping) • Both gcc (to run C programs), and perl (to run Perl programs) are installed on the cims servers • Must compile the C program with gcc, and then run the generated executable • Must include the path to the perl executable in the perl script Basic Scope Concepts in C • block scope (nested scope) • run scope_levels.c (sl) • ** block scope: set of statements enclosed in braces {}, and variables declared within a block has block scope and is active and accessible from its declaration to the end of the block
    [Show full text]
  • Chapter 5 Names, Bindings, and Scopes
    Chapter 5 Names, Bindings, and Scopes 5.1 Introduction 198 5.2 Names 199 5.3 Variables 200 5.4 The Concept of Binding 203 5.5 Scope 211 5.6 Scope and Lifetime 222 5.7 Referencing Environments 223 5.8 Named Constants 224 Summary • Review Questions • Problem Set • Programming Exercises 227 CMPS401 Class Notes (Chap05) Page 1 / 20 Dr. Kuo-pao Yang Chapter 5 Names, Bindings, and Scopes 5.1 Introduction 198 Imperative languages are abstractions of von Neumann architecture – Memory: stores both instructions and data – Processor: provides operations for modifying the contents of memory Variables are characterized by a collection of properties or attributes – The most important of which is type, a fundamental concept in programming languages – To design a type, must consider scope, lifetime, type checking, initialization, and type compatibility 5.2 Names 199 5.2.1 Design issues The following are the primary design issues for names: – Maximum length? – Are names case sensitive? – Are special words reserved words or keywords? 5.2.2 Name Forms A name is a string of characters used to identify some entity in a program. Length – If too short, they cannot be connotative – Language examples: . FORTRAN I: maximum 6 . COBOL: maximum 30 . C99: no limit but only the first 63 are significant; also, external names are limited to a maximum of 31 . C# and Java: no limit, and all characters are significant . C++: no limit, but implementers often impose a length limitation because they do not want the symbol table in which identifiers are stored during compilation to be too large and also to simplify the maintenance of that table.
    [Show full text]
  • Writing Fast Fortran Routines for Python
    Writing fast Fortran routines for Python Table of contents Table of contents ............................................................................................................................ 1 Overview ......................................................................................................................................... 2 Installation ...................................................................................................................................... 2 Basic Fortran programming ............................................................................................................ 3 A Fortran case study ....................................................................................................................... 8 Maximizing computational efficiency in Fortran code ................................................................. 12 Multiple functions in each Fortran file ......................................................................................... 14 Compiling and debugging ............................................................................................................ 15 Preparing code for f2py ................................................................................................................ 16 Running f2py ................................................................................................................................. 17 Help with f2py ..............................................................................................................................
    [Show full text]
  • Introduction to Programming in Lisp
    Introduction to Programming in Lisp Supplementary handout for 4th Year AI lectures · D W Murray · Hilary 1991 1 Background There are two widely used languages for AI, viz. Lisp and Prolog. The latter is the language for Logic Programming, but much of the remainder of the work is programmed in Lisp. Lisp is the general language for AI because it allows us to manipulate symbols and ideas in a commonsense manner. Lisp is an acronym for List Processing, a reference to the basic syntax of the language and aim of the language. The earliest list processing language was in fact IPL developed in the mid 1950’s by Simon, Newell and Shaw. Lisp itself was conceived by John McCarthy and students in the late 1950’s for use in the newly-named field of artificial intelligence. It caught on quickly in MIT’s AI Project, was implemented on the IBM 704 and by 1962 to spread through other AI groups. AI is still the largest application area for the language, but the removal of many of the flaws of early versions of the language have resulted in its gaining somewhat wider acceptance. One snag with Lisp is that although it started out as a very pure language based on mathematic logic, practical pressures mean that it has grown. There were many dialects which threaten the unity of the language, but recently there was a concerted effort to develop a more standard Lisp, viz. Common Lisp. Other Lisps you may hear of are FranzLisp, MacLisp, InterLisp, Cambridge Lisp, Le Lisp, ... Some good things about Lisp are: • Lisp is an early example of an interpreted language (though it can be compiled).
    [Show full text]
  • 7. Functions in PHP – II
    7. Functions in PHP – II Scope of variables in Function Scope of variable is the part of PHP script where the variable can be accessed or used. PHP supports three different scopes for a variable. These scopes are 1. Local 2. Global 3. Static A variable declared within the function has local scope. That means this variable is only used within the function body. This variable is not used outside the function. To demonstrate the concept, let us take an example. // local variable scope function localscope() { $var = 5; //local scope echo '<br> The value of $var inside the function is: '. $var; } localscope(); // call the function // using $var outside the function will generate an error echo '<br> The value of $var inside the function is: '. $var; The output will be: The value of $var inside the function is: 5 ( ! ) Notice: Undefined variable: var in H:\wamp\www\PathshalaWAD\function\function localscope demo.php on line 12 Call Stack # Time Memory Function Location 1 0.0003 240416 {main}( ) ..\function localscope demo.php:0 The value of $var inside the function is: Page 1 of 7 If a variable is defined outside of the function, then the variable scope is global. By default, a global scope variable is only available to code that runs at global level. That means, it is not available inside a function. Following example demonstrate it. <?php //variable scope is global $globalscope = 20; // local variable scope function localscope() { echo '<br> The value of global scope variable is :'.$globalscope; } localscope(); // call the function // using $var outside the function will generate an error echo '<br> The value of $globalscope outside the function is: '.
    [Show full text]
  • Object Lifetimes In
    Object Lifetimes in Tcl - Uses, Misuses, Limitations By Phil Brooks - Mentor – A Siemens Corporation Presented at the 25 nd annual Tcl/Tk conference, Houston Texas, November 2018 Mentor – A Siemens Corporation 8005 Boeckman Road Wilsonville, Oregon 97070 [email protected] Abstract: The management of the lifetime of an object in Tcl presents a number of unique challenges. In the C++ world, the technique of Resource Allocation is Initialization (RAII) is commonly used to control the lifetime of certain objects. With this technique, an object on the call stack is used to insure proper cleanup of a resource. When the object goes out of scope, the resource is released. It presents a low overhead mechanism for a garbage collection like facility without the complication of more complete garbage collection systems. Tcl doesn't have a similar direct capability, and the need for it has resulted in two techniques that are commonly used to substitute for the capability. The techniques are: 1) Use of the trace command to catch unset of a variable. 2) Mis-use of the lifetime of a Tcl_Obj created with Tcl_NewObj. Each of these techniques has drawbacks. The primary issue with the trace technique is that it requires the user of an object to arrange for explicit destruction of the object. This makes the interface more error prone. The mis-use of lifetime of a Tcl_Obj is subject to premature cleanup of the resource if the object is shimmered to a string for any reason. This paper surveys these lifetime management patterns and demonstrates the use of a new user level technique for lifetime management.
    [Show full text]
  • Declare Function Inside a Function Python
    Declare Function Inside A Function Python Transisthmian and praetorian Wye never ensphere helter-skelter when Shawn lord his nightshade. Larboard Hal rumors her dizziesacapnia very so encouragingly actinally. that Colbert aurifies very inferentially. Kenyan Tad reframes her botts so irefully that Etienne Closures prove to it efficient way something we took few functions in our code. Hope you have any mutable object. Calling Functions from Other Files Problem Solving with Python. What embassy your website look like? Then you can declare any result of a million developers have been loaded? The coach who asked this gas has marked it as solved. We focus group functions together can a Python module see modules and it this way lead our. What are Lambda Functions and How to Use Them? It working so art the result variable is only accessible inside the function in. Variables inside python node, learn more detail, regardless of instances of a program demonstrates it. The python function inside another, which start here, and beginners start out. Get code examples like python define a function within a function instantly right anytime your google search results with the Grepper Chrome. The function by replacing it contains one function start here are discussed: how do not provide extremely cost efficient as their name? How to the page helpful for case it requires you can declare python data science. Each item from the python function has arbitrary length arguments must first, but are only the output is simply the function to. We declare their perfomance varies with the gathered arguments using a wrapped the arguments does the computed fahrenheit to declare function inside a function python? List of python can declare a function inside a million other functions we declare function inside a function python.
    [Show full text]
  • CS 403/503: Programming Languages
    BNF for <expression> <expression> → identifier | number | CS 403 -<expression> | (<expression>) | <expression><operator><expression> Organization of Programming Languages <operator> → + | - | * | / Class 3 - August 30, 2001 Topics For Today Parse Tree Review of BNF (Chapter 2.1) Derivations and parse trees (Chapter 2.1) Binding time (Chapter 3.1) Object lifetime and storage slope * x + intercept management (Chapter 3.2) BNF Concept Review Another Parse Tree Terminal symbols: Actual items that are part of the language (0,1,+,-,*,/,etc.) Non-Terminal symbols: <expr>, <op>, etc. Rule/production: A single line of BNF Alternatives: Expressed with | Also: slope * x + intercept *: 0 or more occurrences +:1 or more occurrences 1 Binding Lifetimes • Binding lifetime: The period of time Def: A binding is an association, such between the creation and destruction of a as between an attribute and an entity, name-to-object binding • Object lifetime: The period of time or between an operation and a between the creation and destruction of symbol. an object • These don’t necessarily coincide Def: Binding time is the time at which a • EX. Reference parameters binding takes place. Possible binding times Object Lifetimes… 1. Language design time--e.g., bind operator …correspond to one of three principal symbols to operations 2. Language implementation time--e.g., bind fl. pt. storage allocation mechanisms: type to a representation Static objects: Object lifetime = program 3. Compile time--e.g., bind a variable to a type in C execution. Object bound to one storage or Java location from load time on. 4. Load time--e.g., bind a FORTRAN 77 variable to a memory cell (or a C static variable) Stack objects: Object lifetime = subroutine 5.
    [Show full text]
  • Scope in Fortran 90
    Scope in Fortran 90 The scope of objects (variables, named constants, subprograms) within a program is the portion of the program in which the object is visible (can be use and, if it is a variable, modified). It is important to understand the scope of objects not only so that we know where to define an object we wish to use, but also what portion of a program unit is effected when, for example, a variable is changed, and, what errors might occur when using identifiers declared in other program sections. Objects declared in a program unit (a main program section, module, or external subprogram) are visible throughout that program unit, including any internal subprograms it hosts. Such objects are said to be global. Objects are not visible between program units. This is illustrated in Figure 1. Figure 1: The figure shows three program units. Main program unit Main is a host to the internal function F1. The module program unit Mod is a host to internal function F2. The external subroutine Sub hosts internal function F3. Objects declared inside a program unit are global; they are visible anywhere in the program unit including in any internal subprograms that it hosts. Objects in one program unit are not visible in another program unit, for example variable X and function F3 are not visible to the module program unit Mod. Objects in the module Mod can be imported to the main program section via the USE statement, see later in this section. Data declared in an internal subprogram is only visible to that subprogram; i.e.
    [Show full text]
  • Chapter 5. Using Tcl/Tk
    The Almagest 5-1 Chapter 5. Using Tcl/Tk Authors: Edward A. Lee Other Contributors: Brian L. Evans Wei-Jen Huang Alan Kamas Kennard White 5.1 Introduction Tcl is an interpreted “tool command language” designed by John Ousterhout while at UC Berkeley. Tk is an associated X window toolkit. Both have been integrated into Ptolemy. Parts of the graphical user interface and all of the textual interpreter ptcl are designed using them. Several of the stars in the standard star library also use Tcl/Tk. This chapter explains how to use the most basic of these stars, TclScript, as well how to design such stars from scratch. It is possible to define very sophisticated, totally customized user interfaces using this mechanism. In this chapter, we assume the reader is familiar with the Tcl language. Documentation is provided along with the Ptolemy distribution in the $PTOLEMY/tcltk/itcl/man direc- tory in Unix man page format. HTML format documentation is available from the other.src tar file in $PTOLEMY/src/tcltk. Up-to-date documentation and software releases are available by on the SunScript web page at http://www.sunscript.com. There is also a newsgroup called comp.lang.tcl. This news group accumulates a list of frequently asked questions about Tcl which is available http://www.teraform.com/%7Elvirden/tcl-faq/. The principal use of Tcl/Tk in Ptolemy is to customize the user interface. Stars can be created that interact with the user in specialized ways, by creating customized displays or by soliciting graphical inputs. 5.2 Writing Tcl/Tk scripts for the TclScript star Several of the domains in Ptolemy have a star called TclScript.
    [Show full text]
  • C++/CLI Language Specification
    Ecma/TC39-TG5/2004/25 C++/CLI Language Specification Working Draft 1.5, Jun, 2004 Public Review Document Text highlighted like this indicates a placeholder for some future action. It might be a note from the editor to himself, or an indication of the actual or expected direction of some as-yet open issue. Note: In the spirit of the "Working Draft, Standard for Programming Language C++", this is an early draft. It’s known to be incomplet and incorrekt, and it has lots of bad formatting. Publication Time: 6/17/2004 11:44 PM Table of Contents Table of Contents Introduction....................................................................................................................................................xi 1. Scope............................................................................................................................................................. 1 2. Conformance ............................................................................................................................................... 2 3. Normative references .................................................................................................................................. 3 4. Definitions .................................................................................................................................................... 4 5. Notational conventions................................................................................................................................ 7 6. Acronyms and abbreviations
    [Show full text]
  • Subroutines – Get Efficient
    Subroutines – get efficient So far: The code we have looked at so far has been sequential: Subroutines – getting efficient with Perl do this; do that; now do something; finish; Problem Bela Tiwari You need something to be done over and over, perhaps slightly [email protected] differently depending on the context Solution Environmental Genomics Thematic Programme Put the code in a subroutine and call the subroutine whenever needed. Data Centre http://envgen.nox.ac.uk Syntax: There are a number of correct ways you can define and use Subroutines – get efficient subroutines. One is: A subroutine is a named block of code that can be executed as many times #!/usr/bin/perl as you wish. some code here; some more here; An artificial example: lalala(); #declare and call the subroutine Instead of: a bit more code here; print “Hello everyone!”; exit(); #explicitly exit the program ############ You could use: sub lalala { #define the subroutine sub hello_sub { print "Hello everyone!\n“; } #subroutine definition code to define what lalala does; #code defining the functionality of lalala more defining lalala; &hello_sub; #call the subroutine return(); #end of subroutine – return to the program } Syntax: Outline review of previous slide: Subroutines – get efficient Syntax: #!/usr/bin/perl Permutations on the theme: lalala(); #call the subroutine Defining the whole subroutine within the script when it is first needed: sub hello_sub {print “Hello everyone\n”;} ########### sub lalala { #define the subroutine The use of an ampersand to call the subroutine: &hello_sub; return(); #end of subroutine – return to the program } Note: There are subtle differences in the syntax allowed and required by Perl depending on how you declare/define/call your subroutines.
    [Show full text]