Data elements and bindings Variables and their values Expression - - PowerPoint PPT Presentation

data elements and bindings
SMART_READER_LITE
LIVE PREVIEW

Data elements and bindings Variables and their values Expression - - PowerPoint PPT Presentation

Imperative programming Data elements and bindings Variables and their values Expression (value) evaluation Binding of variables and types static and dynamic binding Lifetime of variables Scopes of variables Lambdas in


slide-1
SLIDE 1

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

1

Data elements and bindings

  • Variables and their values
  • Expression (value) evaluation
  • Binding of variables and types

– static and dynamic binding

  • Lifetime of variables
  • Scopes of variables

– static and dynamic scoping

Imperative programming Lambdas in C++11

slide-2
SLIDE 2

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

2

von Neumann architecture

  • Imperative

programming

– variable – assignment

  • von Neumannin

architecture

– memory cell – transfer (CPU-memory)

Arithmetic and logic unit Memory (instructions and data) Instructions and data Results of operations CPU Control unit Input and

  • utput

devices

slide-3
SLIDE 3

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

3

Data items (variables)

  • Creating and handling data

– is based on changing the state (memory content) of the computer

  • Essential operation of the program

– memory location = space for data item – content of the location = value of the data item

  • Pointer/reference type

– value of a data item is a memory address or a reference to a memory location – in most languages identifies a variable

  • equal pointers = same variables
  • A named variable can be either a data item or a

reference to it

slide-4
SLIDE 4

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

4

Variables

  • Characteristics:

– name – address (L-value) – value (R-value) – type – lifetime – scope

  • Aliasing

X := X + 1; var X: Integer; subroutine SUM ( I, J, K ) integer I, J, K I = J + K return end call SUM ( 1, 2, 3 )

memory location for a variable value of a variable

Pascal: Fortran:

vs.

( f ( a ) + 3 ) -> b [ c ] = 2; C:

slide-5
SLIDE 5

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Value vs. reference semantics

  • In some languages (C, C++,…) variables

contain the data

  • In other languages (Java, Python, …)

variables (=names) are references to objects that contain the data

  • Affects how variables/objects work (e.g.

lifetime, memory allocation)

  • A major source of confusion when changing

to another language

slide-6
SLIDE 6

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Value semantics

  • Variables: named data items
  • (Nameless variables also possible)
  • Assigning to a variable changes the data
  • Pointers/references: variables that refer to

another variable

3 a p

slide-7
SLIDE 7

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Reference semantics

  • Objects: nameless data items
  • Variables/references/names (term depend on

language): named references to objects

  • (Nameless references also possible)
  • Assigning to a variable changes the reference

(refer now to another object)

  • Objects and variables separate, variables

cannot refer to other variables, only to objects

a 3

slide-8
SLIDE 8

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

8

Assignment

  • Changes the state of data

L := R

  • Type checking ensures that the memory location

referenced by L has room for the value of expression R

  • Indirect referencing

– e.g. through pointer dereference – usually what we want – makes compiler optimization harder

0x0804a008 2148 0x0804a865 0x0804a008 ptr ptr == 0x0804a008 *ptr == 2148

slide-9
SLIDE 9

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

9

Variations of assignments

  • Multiple assignment

– e.g. Python – function may return several values (e.g Clu)

  • Compound operations

– e.g. C (+=, -=)

  • Increment and decrement operations

a, b = b, a Triple = proc ( ) returns ( int, int, int ) return ( 1, 2, 3 ) end Triple; ... a, b, c: int := Triple ( ) a.b [ i + j ] += 2; a.b [ i + j ] = a.b [ i + j ] + 2; a [ i ++ ] *= 10;

slide-10
SLIDE 10

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

10

Expression language

  • Statement has a value
  • C: assignment has a value

– enables multiple assignments

  • Algol68:

a = b = 1 a = ( b = 1 ) begin a := if b < c then d else e; a := begin f ( b ); g ( c ) end; g ( d ); 2 + 3 end while ( ( ch = getchar ( ) ) != EOF ) ... if ( x = y ) if ( x == y )

slide-11
SLIDE 11

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

11

Expressions

  • Expressions consist of

– operands

  • e.g. variables, constants, function calls

– operators

  • e.g. operator symbols, functions

a - 5 + f ( 1, 2 ) * 3

slide-12
SLIDE 12

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

12

Operators (1)

  • Different amount of operands:

– unary (signs, negation, C’s ++ and &) – binary (arithmetic operators, comparison operators, assignment, ->) – ternary (in C)

  • Different layout:

– prefix (many unary operators, e.g. -1, !a, ++i)

  • operators in Scheme

– postfix (e.g. i++) – infix (many binary operators) a ? b : c

slide-13
SLIDE 13

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

13

Operators (2)

  • Precedence

– described as precedence levels

  • e.g. binary *-operator usually has a higher precedence (level)

than binary +-operator

  • Association

– applied to operators of the same precedence level – operators associated from left to right:

  • e.g. arithmetic operators, C’s <<, ->

– operators associated from right to left:

  • e.g. power raising, C’s +=, =
slide-14
SLIDE 14

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

14

Operator precedences

Fortran Pascal C Ada

** *, /, div, mod ++, -- **, abs *, / +, - (all) +, - (unary) *, /, mod, rem +, - (all) *, /, % +, - (unary) +, - (binary) +, - (binary) s != 1 << n + 1; A [ i ] = i = x;

C-code:

Obs! Parentheses are recommended a = b << c = d;

(Does not work)

slide-15
SLIDE 15

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

15

Expression evaluation (1)

  • Evaluation can be based on an intermediate

presentation

– syntax tree

  • passed in post-order (left subtree, right subtree, root)

– postfix notation

  • evaluation can be based on stack

– three-address-code

  • common sub-expressions can be used in optimization
  • memory space needed for temporary variables

( a + b ) * ( c – d ) * a b c d

  • +

a b + c d - * t1 = a + b t2 = c – d t3 = t1 * t2

slide-16
SLIDE 16

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

16

Expression evaluation (2)

  • Precedence levels and associations do not

determine the evaluation order of the whole syntax tree

  • Obs: side effects

+

  • *

1 2 3 + y x * 3 3 * ( y – 1 ) + 2 * ( x + 3 ) a = 10; b = a + fun ( a );

slide-17
SLIDE 17

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

17

Expression evaluation (3)

  • Evaluation of logic expressions can be based on short-

short-circuit evaluation

– Modula-2: – C: – Ada: short-circuit operators: andthen, orelse

  • Example of lazy evaluation which means that

– expression is evaluated only when its value is needed

  • e.g. passing an expression as a parameter does not require evaluation
  • f the expression

A or B A and B IF ( i > 0 ) AND ( i < 11 ) AND ( a [ i ] = b ) THEN ... if ( p && ( p->item == x ) ) ...

slide-18
SLIDE 18

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

18

Bindings

  • Binding

– relation or association

  • e.g. between an object and property/feature
  • e.g. between an operation and its symbol
  • Binding time

– time, when a binding occurs

  • Static and dynamic binding
slide-19
SLIDE 19

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

19

Example bindings

  • Set of possible types for count

– bound at language design time

  • Type of count

– bound at compile time

  • Set of possible values of count

– bound at compiler design time

  • Value of count

– bound at execution time with this statement

  • Set of possible meanings for the operator symbol *

– bound at language design time

  • Meaning of the operator symbol * in this statement

– bound at compile time

  • Internal representation of the literal 5

– bound at compiler design time

int count; ... count = count * 5;

C-code:

slide-20
SLIDE 20

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Binding of types

  • Static (compile-time) / dynamic (run-time)?
  • Objects only / objects + references?
  • Can the type of an object change?
  • Can an object have several types at the

same time: inheritance (polymorphism)

  • Explicit/implicit typing
  • Type deduction
slide-21
SLIDE 21

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

21

Binding of variables and types

  • Static binding

– before a variable can be referenced, it must be bound to a data type

  • Choices for static binding:

– explicit declaration – implicit declaration

  • Fortran:

– identifier beginning with I, J, K, L, M, or N => INTEGER – other letter as the first letter => REAL

  • Perl

– beginning with $ => scalar (numeric value or string) – beginning with @ => array – beginning with % => hash (associative array)

slide-22
SLIDE 22

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

22

Explicit declaration

  • Basic rule: declare indentifiers before using them
  • Exceptions for the rule:

– pointers, mutually recursive subprograms type APtr = ^A; A = record next: APtr; data: ... end; type A; type APtr is access A; type A is record next: APtr; data: ... end record; Pascal: Ada:

slide-23
SLIDE 23

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

23

Dynamic binding of types

  • Variable is bound to a type when it is

assigned a value at execution time

– e.g. JavaScript, Python

  • Advantages:

– flexibility, genericity

  • Disadvantages:

– missing support for error detection – (= errors reported to users, not to programmers) – implementation costs

list = [ 10.2, 3.5 ] ... list = 47

JavaScript-code:

slide-24
SLIDE 24

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

24

Type deduction (ML, Haskell, ..)

fun circumf ( r ) = 3.14 * r * r; fun square ( x ) = x * x; fun square ( x ) : int = x * x; ⇒ argument is float, ⇒ result is float ⇒ cannot be deduced a hint given by programmer suffix x = x ++ ”.jpg” square x = x * x auto iter = v.begin ( ) + 2; ⇒ argument is string, ⇒ result is string deduced only when used C++

slide-25
SLIDE 25

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

25

Lifetime

  • Storage bindings (variable bound to memory)

– reservation of memory space for a variable (allocation) – releasing the reserved memory space (deallocation)

  • Variable lifetime

– time during which the variable is bound to a specific memory location – binding between data item (variable declaration) and memory location – occurs at execution time (usually)

  • except for persistent variables stored in a database
slide-26
SLIDE 26

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

26

Variable classification according to lifetime

  • Static variables

– bound to memory location before program execution – binding is preserved through the whole execution

  • Stack-dynamic variables

– bound to memory location during elaboration of their declaration – type is bound statically

  • Explicit heap-dynamic variables

– bound to memory location according to programmer’s instructions – variables are referenced via pointers (no name) – type is bound statically

  • Implicit heap-dynamic variables

– bound to memory location when values are assigned global variables static (in C) local variables pointer variables variables in script languages

slide-27
SLIDE 27

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

27

Garbage collection

  • Memory management

– memory allocation – memory deallocation

  • can be done automatically, when an object can no longer be

reached from the program

  • Triggering garbage collection

– immediately when garbage may be created – size of reserved blocks has grown over some limit – a given time limit is reached – the system has nothing else to do

  • 1. Separate alive objects from

those not in use any more

  • 2. Collect objects not in use
slide-28
SLIDE 28

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

28

Garbage collection methods

  • Reference counts

– keep track of the number of pointers that refer to the same memory location

  • Mark and sweep

– before collection all memory allocations are marked as not seen – referenced allocation blocks are marked as seen – sweep phase sweeps away all allocations that are not seen

  • Stop and copy

– memory space is split into two parts, and only one of them is used for new object allocations – in garbage collection, reachable objects are copied from the allocation space (from-space) to the other, initially empty space (to-space) – finally the roles of these two spaces are switched

slide-29
SLIDE 29

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

29

Pointer problems

  • Lost heap-dynamic variable (garbage)

– memory is allocated for a dynamic variable via a pointer – memory is re-allocated via the same pointer

  • Dangling pointer or dangling reference

– memory is allocated for a dynamic variable via a pointer – the value of the pointer is assigned to another pointer – the space is deallocated via one of the above pointers – the other pointer references now to the deallocated space

New ( p ); ... New ( p ); New ( p1 ); p2 = p1; Dispose ( p1 );

Pascal- codes

slide-30
SLIDE 30

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

30

Example pointer problem

char *init_line ( ) { char *line = new char [ 60 ]; ... return line; } Who (which program structure) owns the pointer?

C-code:

slide-31
SLIDE 31

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

31

Solution for dangling pointers: tombstones

  • Each heap-dynamic variable include a special cell

(tombstone) that is itself a pointer to a heap- dynamic variable

  • Actual pointer variables point only to tombstones
  • When a heap-dynamic variable is deallocated, the

tombstone remains but is set to nil

RIP new ( ptr1 ); ptr2 := ptr1; free ( ptr1 );

delete p; p = nil; if ( p == nil ) ...

slide-32
SLIDE 32

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

32

Solution for dangling pointers: locks and keys

  • Pointer values are associated with an integer (key)
  • Heap-dynamic variables are associated with an

integer (lock)

  • In space allocation, the same value is given for

both key and lock

  • Upon referencing, the equality of the lock and key

is checked

  • Upon deallocation, the value is set invalid

32

135942 135942 135942 135942 135942 135942 135942 new ( ptr1 ); ptr2 := ptr1; free ( ptr1 );

slide-33
SLIDE 33

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

33

Scope

  • Solves which identifier (where declared) is meant

in a reference (usage)

  • Binding between the use of data element and its

definition (declaration)

  • Creates a visibility region

– range of statements in which the variable is visible

  • a variable is visible in statement if it can be referenced in that

statement

– scopes can be nested

  • Static and dynamic scope
slide-34
SLIDE 34

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

34

Moving between scopes

  • Each subprogram has an own scope
  • Moving to a new scope (e.g. calling a subprogram)

– elaboration of declarations – creating bindings to the local variables of the scope – hiding binding of non-local variables of the same name

  • Moving back to the previous scope (e.g. returning

from a subprogram)

– restoring bindings as they were earlier

slide-35
SLIDE 35

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

35

Scope example

  • In inner scope, bindings

to those outer variables that have same names as inner variables, are not preserved

program P; var x, y: Real; procedure P1; var y, z: Integer; begin ... y := 2; x := 2.2; ... end; begin ... x := 1.1; y := 3.3; ... end.

Pascal-code:

slide-36
SLIDE 36

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

36

Static scoping

  • Bindings (between variable declarations and variable

usages) are created at compile time

– can be detected in the program text

  • Choices for static binding:

– single global scope

  • Basic

– both global and local variables

  • Fortran

– nested subprograms

  • Algol60, Pascal, Ada

– nested blocks

  • C, Ada
  • Modules and classes determine scopes
slide-37
SLIDE 37

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

37

Dynamic scoping

  • Bindings depend on

control flow and the

  • rder of subprogram

calls

– e.g. APL, Snobol, early dialects of Lisp, Perl

  • Rule: latest binding

that is created during execution holds

a: integer procedure first a := 1 procedure second a: integer first ( ) a := 2 if read_integer ( ) > 0 second ( ) else first ( ) write_integer ( a ) global declaration local declaration Pseudo code: main program

slide-38
SLIDE 38

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

38

Lifetime and scope

  • Variable lifetime and (static)

scope can be closely related

– e.g. Pascal, nested subprograms

  • Lifetime and scope may not be

related

– e.g. static variables in C – e.g. subprogram calls from another subprogram void printHeader ( ) { ... } void compute ( ) { int sum; ... printHeader ( ); }

C-code:

slide-39
SLIDE 39

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

39

Lambdas and closures

  • Lambda = lambda expression

– exists in source code (compile-time feature) – definition

  • Closure = lambda’s run-time counterpart

– definition + environment = instantiation – environment binds each free variable in lambda expression to a value

– free variables become closed -> closure class instance of a class = object

cf.

slide-40
SLIDE 40

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Lambda example in C++11

#include <iostream> using namespace std; int main ( ) { auto func = [ ] ( int x, int y ) { return x + y; }; cout << func ( 2, 3 ) << endl; } => 5

slide-41
SLIDE 41

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Lambda example in C++11

#include <iostream> using namespace std; int main ( ) { int n = [ ] ( int x, int y ) { return x + y; } ( 5, 4 ); cout << n << endl; } => 9

slide-42
SLIDE 42

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Captures in C++11

  • Capture clause = lambda introducer
  • Specify which outside (free) variables are

available for the lambda function and how to capture them

− by value or by reference

  • In other words: how to bind free variables

(variables referenced in the body of a lambda)

slide-43
SLIDE 43

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Capture choices in C++11

[ ] captures nothing [ = ] captures all outside variables by value [ & ] captures all outside variables by reference [ a, &b ] captures a by value and b by reference [ this ] captures this pointer by value

slide-44
SLIDE 44

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Lambda example in C++11

#include <iostream> using namespace std; int main ( ) { int x = 3; int y = 5; auto func = [ x, &y ] { return x + y; }; x = 22; y = 44; cout << func ( ) << endl; } => 47

slide-45
SLIDE 45

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Lambda and STL (for_each)

vector<int> v; v.push_back ( 1 ); v.push_back ( 2 ); // … for ( auto itr = v.begin ( ), end = v.end ( ); itr != end; itr++ ) { cout << *itr; } vector<int> v; v.push_back ( 1 ); v.push_back ( 2 ); // … for_each ( v.begin ( ), v.end ( ), [ ] ( int val ) { cout << val; } );