Variables Six properties: Binding times of properties:

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms
Advertisements

Names and Bindings.
Chapter 5 Names, Bindings, and Scopes
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
Chapter 5: Elementary Data Types Properties of types and objects –Data objects, variables and constants –Data types –Declarations –Type checking –Assignment.
Variables Names Bindings Type Scope. L-Value versus R-Value Not complicated Associated with assignment statements Left hand side represents an address.
Chapter 5 Basic Semantics
CS 330 Programming Languages 10 / 16 / 2008 Instructor: Michael Eckmann.
Names, Bindings, Type Checking, and Scopes
Lifetime “The lifetime of a variable is the time during which the variable is bound to a specific memory location.” [p. 219] “…the lifetime of a variable.
CS 330 Programming Languages 10 / 18 / 2007 Instructor: Michael Eckmann.
ISBN Chapter 5 Names, Bindings, Type Checking, and Scopes Names Variables The Concept of Binding Type Checking Strong Typing Type Compatibility.
The Concept of Variables
Copyright © 1995 by Addison-Wesley Publishing Co. 1 Names - Design issues: - Maximum length? - Are connector characters allowed? - Are names case sensitive?
CS 330 Programming Languages 10 / 24 / 2006 Instructor: Michael Eckmann.
Names and Bindings Introduction Names Variables The concept of binding Chapter 5-a.
Names, Bindings, and Scopes
Names, Bindings, and Scopes
Software II: Principles of Programming Languages Lecture 5 – Names, Bindings, and Scopes.
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
Chapter TwelveModern Programming Languages1 Memory Locations For Variables.
CS 330 Programming Languages 10 / 21 / 2008 Instructor: Michael Eckmann.
Names and Binding In procedural programming, you write instructions the manipulate the “state” of the process where the “state” is the collection of variables.
ISBN Chapter 5 Names, Bindings, Type Checking, and Scopes.
COMP4730/2003/lec5/H.Melikian Names, Bindings,Type Checking and Scopes (Chapter 5) - Design issues: - Maximum length? - Are connector characters allowed?
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
5-1 Chapter 5: Names, Bindings, Type Checking, and Scopes Variables The Concept of Binding Type Checking Strong Typing Type Compatibility Scope and Lifetime.
March 12, ICE 1341 – Programming Languages (Lecture #6) In-Young Ko Programming Languages (ICE 1341) Lecture #6 Programming Languages (ICE 1341)
Compiler Construction
1 Names, Scopes and Bindings Aaron Bloomfield CS 415 Fall
Chapter 5 Names, Bindings, and Scopes. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Chapter 5 Topics Introduction Names Variables The Concept.
ISBN Chapter 5 Names, Bindings, and Scopes.
Storage Bindings Allocation is the process by which the memory cell or collection of memory cells is assigned to a variable. These cells are taken from.
Introduction A variable can be characterized by a collection of properties, or attributes, the most important of which is type, a fundamental concept in.
Basic Semantics Associating meaning with language entities.
ISBN Chapter 5 Names, Bindings, and Scopes.
Programming Languages and Paradigms Imperative Programming.
CS 330 Programming Languages 10 / 30 / 2007 Instructor: Michael Eckmann.
Semantics CSE 340 – Principles of Programming Languages Fall 2015 Adam Doupé Arizona State University
Names, Bindings, and Scope Session 3 Course : T Programming Language Concept Year : February 2011.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Concepts of programming languages Chapter 5 Names, Bindings, and Scopes Lec. 12 Lecturer: Dr. Emad Nabil 1-1.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Variables reference, coding, visibility. Rules for making names  permitted character set  maximum length, significant length  case sensitivity  special.
ISBN Chapter 5 Names, Bindings, Type Checking, and Scopes.
Names and Binding In Text: Chapter 4.
ISBN Variables, Names, Scope and Lifetime ICOM 4036 Lecture 9.
1 Structure of Compilers Lexical Analyzer (scanner) Modified Source Program Parser Tokens Semantic Analysis Syntactic Structure Optimizer Code Generator.
CS 330 Programming Languages 10 / 23 / 2007 Instructor: Michael Eckmann.
ISBN Chapter 5 Names, Bindings, Type Checking, and Scopes.
Names, Scope, and Bindings Programming Languages and Paradigms.
Names, Bindings, Type Checking and Scopes. Chapter 5 Topics Introduction Names Variables The Concept of Binding Type Checking Strong Typing Type Equivalence.
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering CSCE 330 Programming Language Structures Operational Semantics (Slides mainly.
ISBN Chapter 12 Support for Object-Oriented Programming.
CHAPTER 4 VARIABLES & BINDING SUNG-DONG KIM DEPT. OF COMPUTER ENGINEERING, HANSUNG UNIVERSITY.
Chapter 5 Names, Bindings, Type Checking CSCE 343.
Advanced Programming in C
Object Lifetime and Pointers
Data Types In Text: Chapter 6.
Names and Attributes Names are a key programming language feature
Type Checking, and Scopes
Chapter 5 Names, Bindings, Type Checking, and Scopes.
Names, Bindings, and Scopes
Chapter 5 Names, Bindings, Type Checking, and Scopes.
Names and Binding In Text: Chapter 5.
Names, Bindings, and Scopes
Types and Related Issues
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Variables Six properties: Binding times of properties: name address type value lifetime scope Binding times of properties: language specification time language implementation time compile time run time Broad classification: static dynamic

1. Name Syntax of language specifies valid names. Languages used to limit length of names BASIC (1978): [A-Z]([0-9]) Fortran77: 6 characters Fortran95: 31 characters Java, C#: no limit Restrictions: keywords have special meaning (e.g. ‘for’) reserved words cannot be used as names generally keywords are reserved

2. Address The memory address at which the value associated with the name is stored. This is called the l-value (because it is the value used on the left hand side of an assignment operator). In Scheme terms, an unevaluated symbol. A given name can be associated with multiple addresses during program execution (e.g. parameters of a recursive function, an instance variable defined in a multiply-instantiated class). Aliasing occurs when many variables share an address.

3. Type The type of a variable determines the set of values which can be associated with the name. We will return to type binding and type checking.

Aside: binding times of types The binding time of a set of values to a type differs across languages. In Java the size and representation for types is written into the language specification. every Java implementation is guaranteed to have the same range of values for the primitive types. In C the binding of a set of value to types is left to implementation time. different implementations can (and do) make different decisions implication is that the very same program can behave differently on different platforms.

Binding types to names (1) Explicit vs. implicit an explicit declaration specifies the type of a variable an implicit declaration is a language convention giving name-type mappings Fortran: “If the identifier begins with one of the letters I, J, K, L, M or N, or their lowercase versions, it is implicitly declared to be Integer type, otherwise it is implicitly declared to be Real type.” [p. 213] Perl: different namespaces for different types $ implies scalar @ implies array % implies hash

Binding types to names (2) Static vs. dynamic with static binding the type of a variable is known at compile time (e.g. C, C++, Java) with dynamic binding the type of a variable is not known until run time (e.g. Scheme, JavaScript), and can change during the execution of a program [pg. 214]: list = [10.2, 3.5]; list = 47;

Binding types to names (3) Type inferencing (ML) ML derives the types of all expressions from the types of their constituent parts. ML (with very few exceptions) does not require any type declarations, and yet all expressions are fully typed at compile time. ML uses type variables to express generic types (e.g. ’a and ”a).

4. Value The r-value of the variable (because it is the value used on the right hand side of an assignment operator). In Scheme terms, the value retrieved from symbol lookup in an environment. This is the contents of a block of memory cells, whose starting address is the l-value of the variable, whose size and interpretation are determined by the type of the variable. Sometimes we refer to this block of memory, typically many bytes large, simply as the “memory cell” of a variable.

Aside: memory footprint & representation The type of a variable determines two very important things: the amount of memory allocated to the variable the representation scheme used to write/read bit patterns into/from memory. Consider the type short in C. Using the default ‘cc’ compiler on pollux, we find that a short occupies 8 bits; integers are stored using the 2’s complement representation scheme.

Anatomy of a short The range of values we can store in a short is -128 to +127: BIT PATTERN DECIMAL VALUE 01111111 +127 01111110 +126 . . . . . . . . 00000010 +2 00000001 +1 00000000 0 11111111 -1 11111110 -2 10000001 -127 10000000 -128

Anatomy of an int The range of values we can store in an int is -32768 to +32767: BIT PATTERN DECIMAL VALUE 0111111111111111 +32767 0111111111111110 +32766 . . . . . . . . 0000000000000010 +2 0000000000000001 +1 0000000000000000 0 1111111111111111 -1 1111111111111110 -2 1000000000000001 -32767 1000000000000000 -32768

What happens here? int i = 128; short s = i;

5. Lifetime “The lifetime of a variable is the time during which the variable is bound to a specific memory location.” [p. 219] “…the lifetime of a variable begins when it is bound to a specific cell and ends when it is unbound from that cell.” [p. 219] Four categories static stack-dynamic explicit heap-dynamic implicit heap-dynamic

Memory organization STATIC code & static data STACK local data: AVAILABLE MEMORY STACK local data: invocation records HEAP dynamic data

static variables Bound to a memory location prior to execution. No run-time allocation needs to occur: efficient. Persistent: variable persists throughout execution of a program.

Example (C) #include “stdio.h”; int counter() { static int k = 0; return ++k; } int main() { printf(“Counter is %d \n”,counter()); return 0; /* OUTPUT IS: Counter is 1 Counter is 2 */

Notes about example static variable k is allocated space in the static segment allocation happens once k’s lifetime is the that of the entire program k’s value persists from call to call

stack dynamic variables “storage bindings are created when their declaration statements are elaborated, but whose types are statically bound” [p. 220] Allocated on the run-time stack

Example (C) #include “stdio.h”; int counter() { int k = 0; return ++k; } int main() { printf(“Counter is %d \n”,counter()); return 0; /* OUTPUT IS: Counter is 1 */

Notes about example stack-dynamic variable k is allocated space in the stack segment allocation happens each time function is called k’s lifetime is the that of the function invocation k’s value does not persist from call to call: it is reinitialized on each function execution

explicit heap-dynamic variables anonymous (nameless) variables created at runtime, allocated on the heap, and accessible only via indirection (a pointer) Example [p. 221] int *intnode; // Create a pointer ... intnode = new int; // Create the heap-dynamic variable delete intnode; // Deallocate the heap-dynamic variable // to which intnode points

Example (Java) public class Count private int k; public Count() { } public int counter() { return ++k; public static void main(String [] args) { Count c = new Count(); System.out.println(“Counter is ”+c.counter()); /* OUTPUT IS: Counter is 1 Counter is 2 */

Notes about example instance variable k is allocated space in the heap segment allocation happens each time object is created k’s lifetime is the that of its object k’s value persists from call to call of the method many different independent k’s can co-exist

implicit heap-dynamic variables automatic heap-allocation JavaScript, [pg. 214]: list = [10.2, 3.5]; list = 47; Scheme all allocation is done on heap cons allocates a pair environments are allocated on heap (so no runtime stack is needed for function calls).

Example (Scheme) (define count1 (lambda () (let ((k 0)) (set! k (+ k 1)) k ))) (define count2 (display (count1)) (newline) (display (count2)) (newline) /* OUTPUT IS: 1 2 */

Environment diagrams (drawn on board)

Notes about example in count1 k is initialized each time function is called in count2 k is initialized when the function is defined

Exercise How do you define a Scheme function which can dynamically generate counter functions, each with its own independent counter?

counterMaker (define counterMaker (lambda () (let ((k 0)) (set! k (+ k 1)) k )))) (define c1 (counterMaker)) (define c2 (counterMaker)) (c1) (c1) (c1) (c2) (c2) (c1) (c2)

6. Scope “The scope of a variable is the range of statements in which the variable is visible. A variable is visible in a statement if it can be referenced in that statement.” Two basic approaches: static scoping dynamic scoping

Static scope Static scoping (also called lexical scoping): the scope of a variable is determined by the static (lexical) structure of the program. scope determined by lexical nesting some languages allow nested blocks we’ve seen examples in C and Java some languages allow nested functions C/C++/Java do not allow this Scheme/ML do

Dynamic scope dynamic scope scope determined by (dynamic) call history we will see an example soon

Why do we care? Obviously important for our understanding of programs. More importantly, we use the scoping of variables to support encapsulation. Strong encapsulation lets us build robust components: grants access to those components which need it denies access to all other components

Collection classes Each collection defines its own Iterator. Each collection needs to keep its implementation details private. Each iterator is defined as a separate class (so it can be instantiated independently of the class). Each iterator encapsulates iteration logic for a specific collection. It must know the implementation details in order to serve as the bridge between clients of the collection and the internal workings of that collection. How do we grant access to Iterator classes while denying access to others?

Inner classes Java’s Collection classes concrete collection class must hide its implementation must provide Iterator Iterator must know implementation details Inner class structure embeds Iterator definition within scope of collection class Iterator can access internals of collection without collection having to break encapsulation

Nested functions Create nested scopes to hide bindings Allows us to hide helper functions (similar to what inner classes let us do): (define fact (letrec ((helper (lambda (n acc) (if (= n 0) acc (helper (- n 1) (* n acc)))))) (lambda (n) (helper n 1))))

Examples comparing static and dynamic scope Example in C-like language Example in Scheme-like language

Dynamic vs. static scope: C-like language int a = 3; void foo(){ printf(“a has value %d \n”,a); } void bar(){ int a = 5; foo();} foo(); // what does this print? bar(); // what does this print?

With static scope C is statically scoped, so the output will be: int a = 3; void foo(){ printf(“a has value %d \n”,a); } void bar(){ int a = 5; foo();} void abc(){ int a = 7; foo();} foo(); // what does this print? bar(); // what does this print? abd(); // what does this print? C is statically scoped, so the output will be: a has value 3

With dynamic scope If C were dynamically scoped, the output would be: int a = 3; void foo(){ printf(“a has value %d \n”,a); } void bar(){ int a = 5; foo();} void abc(){ int a = 7; foo();} foo(); // what does this print? bar(); // what does this print? abd(); // what does this print? If C were dynamically scoped, the output would be: a has value 3 a has value 5 a has value 7

Languages with dynamic scope Common Lisp and Perl give the programmer the option of using either dynamic or static scope.

Dynamic vs. static scope: Scheme-like language (define a 3) (define f (lambda () a)) (define g (lambda (a) (f))) (f) (g 7)

Environment: (define a 3) a 3

Environment: (define a 3) (define f (lambda () a )) () a a 3 f

Environment: (define a 3) (define f (lambda () a )) (define g

Environment during evaluation of (f): (define a 3) (define f (lambda () a )) (define g (lambda (a) (f) () a (a) a 3 (f) f g (f) => 3 a => 3 static link dynamic link

Environment during evaluation of (g 7): (define a 3) (define f (lambda () a )) (define g (lambda (a) (f) (g 7) () a (a) a 3 (f) f g (g) a 7 (f) static link dynamic link => 3 a => 7

Questions?