0% found this document useful (0 votes)
88 views236 pages

Design

The document discusses principles of programming language design. It begins by stating the goals of designing a programming language and implementing its compiler. It then outlines the phases of the programming language development life cycle, including requirements analysis, design, implementation, and maintenance. Key aspects of the design phase are discussed such as grammar, syntax, semantics, and backend. The document also defines common jargon used in programming language design such as language, statement, alphabet, grammar, derivation, and language recognition/acceptor.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views236 pages

Design

The document discusses principles of programming language design. It begins by stating the goals of designing a programming language and implementing its compiler. It then outlines the phases of the programming language development life cycle, including requirements analysis, design, implementation, and maintenance. Key aspects of the design phase are discussed such as grammar, syntax, semantics, and backend. The document also defines common jargon used in programming language design such as language, statement, alphabet, grammar, derivation, and language recognition/acceptor.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 236

Principles of Programming Languages

CS F 301/ IS F301

D.C.KIRAN
BITS Pilani [email protected]
Pilani Campus
Slides are Mostly From

Text Book 1:
Programming Languages: Concepts & Constructs, 2/e

By
Ravi Sethi and K. V. Viswanatha

Reference Book 1:
Concepts of Programming Languages, 8/e

by Robert W. Sebesta

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Programming Language Design


Goal
* To design the Programming Language.

* To Implement the compiler (start now and continue learning till end of next semester)

* Not to worry much about Cousins of Compiler

• Preprocessors
• Assemblers
• Linkers
• Loaders

4
BITS Pilani, Pilani Campus
Developing Programming Language
• Similar to developing any software.
• Should have knowledge Data used and Environment where program runs.
• Follows all phases of Software Development Life Cycle (SDLC)

SDLC (PL-DLC)
Phase Output
• Requirements analysis • Programming Language
Requirements Specification
(PLRS)
• Design Document,
• Design
Design rules
 Grammar / Syntax
 Semantic
 Back end
• Implementation • Writing compiler.

• Maintenance • Modification/ Version


Management 5
BITS Pilani, Pilani Campus
Why Design is so Important?

6
BITS Pilani, Pilani Campus
Jargons

• Language
• Statement
• Alphabets
• Grammar
• Derivation
• Language Recognition / Acceptor

BITS Pilani, Pilani Campus


Language / Statements /Alphabets
Hindi: { आम, बेटा, कताब, ब
चा, घर }

Kannada: { ಅಮ, ಮಗು, ಾವ


, ೆಂಗಳರು}

Tamil: { அம்மா, ஆைச , திரு , ேதாைச }

Telugu: { , к , 


,  }

English: {Apple, Ball, Cat, Doll, Egg, Fish, Girl, Him, In, Jump, Kick……….}

C: { int main()
{
printf(“hello world”);
return (0);
}
}

BITS Pilani, Pilani Campus


Programming Language Example
string fun1(int x, string y,){
1) <Program> →<funcons>comma<functionbody>comma int a;
2) <funcons>→<funcon><funcons>/ ε string b;
3) <funcon> →<funsignature><functionbody> b = b + y;
4) <Funsignature>→ <type> id ( <params)> *y;
}
5) <type>→ int / float/string
6) <params>→ <type> id comma <params> / ε float fun2(int I, float j,){
7) <functionbody>→{ <declaraons> <statements> *<E>; } int k;
8) <declaraons>→ <type>id ; <declarations >/ ε k = I *j+k;
9) <statements> → id = <E>;/ id = id <more>;<statements>/ε *k;
10) <E>→ <E>+<E >/ }
<E*E>/id/<intigerliteral>/<floatliteral>/<stringliteral>
11) <more> →(<args>) ,
{
12) <args> → id comma <args> / ε
float z; string s= “bits”;
int p;
Z=10.5; p=5;
z = fun1(p,s,);
p = fun2(p,z,);
*z;
}
,

BITS Pilani, Pilani Campus


Programming Language Example
string fun1(int x, string y,){
1) <Program> →<funcons>comma<functionbody>comma int a;
2) <funcons>→<funcon><funcons>/ ε string b;
3) <funcon> →<funsignature><functionbody> b = b + y;
4) <Funsignature>→ <type> id ( <params)> *y;
}
5) <type>→ int / float/string
6) <params>→ <type> id comma <params> / ε float fun2(int I, float j,){
7) <functionbody>→{ <declaraons> <statements> *<E>; } int k;
8) <declaraons>→ <type>id ; <declarations >/ ε k = I *j+k;
9) <statements> → id =<E>;/ id = id <more>;<statements>/ε *k;
10) <E>→ <E>+<E >/ }
<E*E>/id/<intigerliteral>/<floatliteral>/<stringliteral>
11) <more> →(<args>) ,
{
12) <args> → id comma <args> / ε
float z;
string s= “bits”;
int p;
Z=10.5; p=5;
z = fun1(p,s,);
p = fun2(p,z,);
*z;
}
,
BITS Pilani, Pilani Campus
Programming Language Example
string fun1(int x, string y,){
1) <Program> →<funcons>comma<functionbody>comma int a;
2) <funcons>→<funcon><funcons>/ ε string b;
3) <funcon> →<funsignature><functionbody> b = b + y;
4) <Funsignature>→ <type> id ( <params)> *y;
}
5) <type>→ int / float/string
6) <params>→ <type> id comma <params> / ε float fun2(int I, float j,){
7) <functionbody>→{ <declaraons> <statements> *<E>; } int k;
8) <declaraons>→ <type>id ; <declarations >/ ε k = I *j+k;
9) <statements> → id = <E>;/ id = id <more>;<statements>/ε *k;
10) <E>→ <E>+<E >/ }
<E*E>/id/<intigerliteral>/<floatliteral>/<stringliteral>
11) <more> →(<args>) ,
{
12) <args> → id comma <args> / ε
float z; string s= “bits”;
int p;
Z=10.5; p=5;
z = fun1(p,s,);
p = fun2(p,z,);
*z;
}
,

BITS Pilani, Pilani Campus


BITS Pilani, Pilani Campus
Language Recognition / Acceptor

start < =
0 1 2 return(relop, LE)
>
3 return(relop, NE)
other
Pushback(LA)
= 4
*
return(relop, LT)

5 return(relop, EQ)
>

=
6 7 return(relop, GE)
other
8
*
return(relop, GT)
Pushback(LA)

BITS Pilani, Pilani Campus


Revisiting Jargons

• Language
• Statement
• Alphabets
• Grammar
• Derivation
• Language Recognition / Acceptor

BITS Pilani, Pilani Campus


Definitions
Alphabet: Is a finite, non empty set of symbols. Usually denoted by ∑ symbol.
Example: Binary ∑ ={ 0,1}.
all lower case letters ∑ = {a, b, …………z}
DNA molecule letters ∑ = {a, c, g, t}

Sentence : Strings of symbols. Usually denoted by ‘w ‘symbol.


Example: { ε, 0, 1, 00, 11, 010,101,1111100000, 0011,…..}
Note: ε denote empty string
Language: A language is a collection of sentences of finite length all constructed
from alphabets and follow some grammar rules. Denoted by ∑*.
Example: { 10001, 000111, 1010001,11100000}
{ 11, 011011, 110011, 11}
Note: * (Kleene Closure) denote zero or more

Grammar : Finite set of rules defining a language. Denoted by symbol G.


“A grammar can be regarded as a device that enumerates the sentences of a
language” - nothing more, nothing less

BITS Pilani, Pilani Campus


Language Generators
• Grammar is 4 tuple { N. T. P S}
– A mechanism (or set of rules) by which a language is generated
– Defined by :
• A set of non-terminal symbols, N
– Do not actually appear in strings
• A set of terminal symbols, T or ∑
– Appear in strings
• A set of productions, P
– Rules used in string generation
• A starting symbol, S
Note:
1) Non-terminals are generally denoted by capital letters { A, B, …….Z}
2) Terminals are generally denoted by { a, b,….z, 0-9, operators, symbols….etc.}
3) Productions must be of the form
<N>  α / β / δ Where α , β , δ are strings containing terminals
and non-terminals including ε.

BITS Pilani, Pilani Campus


Grammar Example
Example 1: Grammar to generate sets of balanced
parentheses
N = {A}
T = {(,)}
S=A
P=
A AA | (A) | ()

Example 2: Expression Grammar


N = {E, T, ID, F}
T = {+ , * , (, ), a, b, c,…..z}
S=E
P=
E E+T / T
T T * F / F
F ID / ( E)
ID a / b / c / ……/ z

BITS Pilani, Pilani Campus


Derivation

BITS Pilani, Pilani Campus


Derivation

– Example: Leftmost derivation of nested


parens: (()(()))
A → (A)
→ (AA)
→ (()A)
→ (()(A))
→ (()(()))
– We can view this derivation as a tree, called a
parse tree for the string

BITS Pilani, Pilani Campus


Parse Tree

• Parse tree for (()(())) A

( A )

A A

( ) ( A )

( )

BITS Pilani, Pilani Campus


Grammar Example 3

BITS Pilani, Pilani Campus


Grammar Example
– Example 4 : The grammar G(L) to generate a language L, strings of
0’s and 1’s having a substring 000
SA000A
A 0A / 1A / A1 / A0 / ε
– Example 5: Regular grammar to generate a binary string containing an
odd number of 1s
– A → 0A | 1B | 1
– B → 0B | 1A | 0
Example 6: Grammar to generate set of all strings with at least one
a when ∑ ={a,b}
SbS / aA
A aA / bA / ε
Example 7: Grammar to generate set of all strings with exactly one
a when ∑ ={a,b}
SbS /aB
B bB / ε
BITS Pilani, Pilani Campus
Example Grammar 8

BITS Pilani, Pilani Campus


Ambiguous Grammars

Two distinct parse trees for the same sentence, A = B + C * A

BITS Pilani, Pilani Campus


A unique parse tree for A = B + C * A

BITS Pilani, Pilani Campus


Ambiguous

BITS Pilani, Pilani Campus


Ambiguous

– We can easily make this grammar


unambiguous:
• Remove production: A → 0A1
• Note that nonterminal B can generate an arbitrary
number of 0s and nonterminal C can generate an
arbitrary number of 1s
• Now only one parse tree

BITS Pilani, Pilani Campus


Dangling if_else Statement

Stmt→if <Logic_Expr> then <Stmt> else <Stmt> | if <Logic_Expr> then <Stmt>

Consider the string:

If <logic-expr>then if <logic_expr> then <stmt> else <stmt>

Yields two distinct parse trees and is therefore ambiguous

BITS Pilani, Pilani Campus


Dangling if_else Statement

BITS Pilani, Pilani Campus


Dangling if_else Statement

int a=0;
if (0==0) What is the value of a after this fragment
if (0==1) a=1; executes?
else a=2;

 Some languages define if-then-else in a way that forces the programmer to be


more clear
 Algol does not allow the then part to be another if statement – though it can be a
block containing an if statement
 Ada requires each if statement to be terminated with an end if
 Python requires nested if statement to be indented

int a=0; int a=0;


if (0==0) { if (0==0)
if (0==1) { a=1;} if (0==1) a=1;
{ else a=2; } else a=2;
}

Use of a block reinforces the structure Correct indentation

BITS Pilani, Pilani Campus


Dangling if_else Statement

Stmt→if <Logic_Expr> then <Stmt> else <Stmt> | if <Logic_Expr> then <Stmt>

Becomes:
<Stmt> → EwithElse | EnoElse
EwithElse → if <Logic_Expr> then EwithElse else EwithElse | other
EnoElse → if <Logic_Expr> then <Stmt>
| if <Logic_Expr> then EwithElse else EnoElse

BITS Pilani, Pilani Campus


Left Recursion

• A grammar is left recursive if for a non-


terminal A, there is a derivation A⇒+ Aα

• There are three types of left recursion:


– direct (A → A x)
– indirect (A → B C, B → A )
– hidden (A → B A, B → ε)

BITS Pilani, Pilani Campus


Left Recursion

• To eliminate direct left recursion replace

A → Aα1 | Aα2 | ... | Aαm | β1 | β2 | ... | βn

with

A → β1B | β2B | ... | βnB


B → α1B | α2B | ... | αmB | ε

BITS Pilani, Pilani Campus


Left Recursion

BITS Pilani, Pilani Campus


Left recursion

Example 3:
Expression Grammar:

S→E
E → E+T
E→T
T → E-T
T→F
F → E*F
F → id

BITS Pilani, Pilani Campus


Eliminating indirect left recursion
S→E S→E S→E S→E
E → TE' E → TE' E → TE'
E → E+T /T E'→+TE'|ε E'→+TE'|ε E'→+TE'|ε
T → E-T T → TE'-T T → FT'
T → E-T / F T→F T→F T' → E'-TT'|ε
F → E*F F → E*F F → E*F
F → E*F /id F → id F → id F → id

S→E S→E S→E


E → TE' E → TE' E → TE'
E'→+TE'|ε E'→+TE'|ε E'→+TE'|ε
T → FT' T → FT' T → FT'
T' → E'-TT'|ε T' → E'-TT'|ε T' → E'-TT'|ε
F → TE'*F F → FT'E'*F F → idF'
F → id F → id F' → T'E'*FF'|ε

BITS Pilani, Pilani Campus


Look ahead during Parsing or Syntax Analysis

To derive the string : aacdmnb

SaAb / aCb
A aBC / aCa S
B cd
C  mn / pq
a A b

a
B C

c m
d n
BITS Pilani, Pilani Campus
Left-Factor

Stmt→if <Logic_Expr> then <Stmt> else <Stmt> | if <Logic_Expr> then <Stmt>___

Stmt→if <Logic_Expr> then <Stmt> S’


S’else <Stmt> | ε

BITS Pilani, Pilani Campus


aaaaaaaaa
aaaaaa

BITS Pilani, Pilani Campus


BITS Pilani, Pilani Campus
Left-Factoring

BITS Pilani, Pilani Campus


Left-Factoring

BITS Pilani, Pilani Campus


Check List for Design

Constructs Issues
Identifiers (Naming, Binding, Scope, Lifetime)
Data Types ( Primitive and User Defined)
Expressions & (Precedence , Associativity and Evaluation)
Assignment Statements
Iterative Statements Condition vs Range
Selection Statements Two Way vs Multiple Selection

BITS Pilani, Pilani Campus


Expressions

BITS Pilani, Pilani Campus


Issues: Precedence and Associativity

Grammars define associativity and precedence among the operators in an


expression.

Precedence: which operator is evaluated first; e.g., in the expression “a + b / c”

Associtivity: evaluation order for equal precedence (adjacent) operators; e.g., in


the expression “a - b + c”

BITS Pilani, Pilani Campus


Precedence Associativity Operators
3 right ^
2 left * / %
1 left + -
The structure of the parse tree shows operator precedence & associativity:
Operators lower in the tree are evaluated first.
An operation can’t be performed until its operands are evaluated

BITS Pilani, Pilani Campus


Issue #1: Precedence
Expression Grammar
<exp>  <exp> + <exp>
| <exp> * <exp>
| (<exp>)
| a | b | c

<exp>
<exp>

<exp> * <exp> <exp> + <exp>

<exp> + <exp> c a <exp> * <exp>

b c
a b

Our grammar generates this tree for a+b*c. In left tree, the addition is performed
before the multiplication, which is not the usual convention for operator precedence.
BITS Pilani, Pilani Campus
Precedence In The Grammar
Expression Grammar
<exp>  <exp> + <exp>
| <exp> * <exp>
| (<exp>)
| a | b | c

To fix the precedence problem, we modify the grammar so that it is forced to put *
below + in the parse tree.

Modified Expression Grammar Correct Parse tree


<exp>
<exp> <exp> + <exp> | <mulexp>
<mulexp>  <mulexp> * <mulexp>
| (<exp>) <exp> + <exp>
| a | b | c
a <mulexp> <mulexp>
*
b c

BITS Pilani, Pilani Campus


Higher Level Precedence

To add a higher level of precedence, add another non-terminal

Expression Grammar

<exp>  <exp> + <exp> | <mulexp>


<mulexp>  <mulexp> * <rootexp> | <rootexp>
<rootexp>  (<exp>)| a | b | c

BITS Pilani, Pilani Campus


Issue #2: Associativity
<exp>
<exp>
<exp> <exp>
+ <exp> + <exp>
<mulexp> <mulexp>
<exp> + <exp>
<exp> + <exp>
<rootexp> <rootexp>
<mulexp> <mulexp>
<mulexp> <mulexp>
c a
<rootexp> <rootexp>
<rootexp> <rootexp>
a
b c
b
Left-associative parse tree.
Right-associative parse tree.

 Our grammar generates both these trees for a+b+c.


 The Second one is not the usual convention for operator associativity.
 The grammar for a language must generate only one parse tree for each
expression.
BITS Pilani, Pilani Campus
Modify the grammar to fix the associativity problem

• <exp> <exp> + <Term> the recursive non-terminal is on left so left-associative

• <exp>  <Term> + <exp> the recursive non-terminal is on right so right-associative

Modified Grammar
<exp>  <exp> + <mulexp> | <mulexp> <exp>
<mulexp>  <mulexp> * <rootexp> | <rootexp>
<rootexp>  (<exp>) | a | b | c <exp>
+ <mulexp>

<mulexp>
<exp> + <mulexp>
<rootexp>
<mulexp> <rootexp>
c
<rootexp> b

a
Left-associative parse tree.
BITS Pilani, Pilani Campus
Exercise

Expression Grammar
<exp>  <exp> + <mulexp> | <mulexp>
<mulexp>  <mulexp> * <rootexp> | <rootexp>
<rootexp>  (<exp>) | a | b | c

1.) Add a left-associative & operator, at lower precedence than any of the others
2.) Then add a right-associative ^ operator, at higher precedence than any of the
others

52
BITS Pilani, Pilani Campus
Solution

Modified Expression Grammar

<exp>  <exp> & <expplus> | <expplus>


<expplus> <expplus> + <mulexp> | <mulexp>
<mulexp>  <mulexp> * <expoexp> | <expoexp>
<expoexp>  <rootexp> ^ <expoexp> | <rootexp>
<rootexp>  (<exp>) | a | b | c

53
BITS Pilani, Pilani Campus
Boolean Expressions

<Bool>--> <Bool> and <Reln> / <Bool> or <Reln> / <Reln>

<Reln> --> Integer < Integer / Integer = =Integer / <TF>

<TF>--> true / false

54
BITS Pilani, Pilani Campus
Expression Evaluation

55
BITS Pilani, Pilani Campus
Short Circuit Evaluation
As soon as we can conclude outcome of the evaluation, skip the
remainder of it.

An expression in which the result is determined without evaluating all


operands and/or operators

Example 1: (13*a) * (b/13–1)


If a is zero, there is no need to evaluate (b/13-1)

Example2 : (a >= 0) && (b < 10)

If a is less than 0, making a >= 0 false, there is no need to


evaluate (b <10). This shortcut can be easily discovered during
execution.
In Pascal list.size()!=0 will get
Example 3: in Java evaluated in all the case. To
avoid we need to write it as:
if ( list != null && list.size() != 0))
System.out.println(list.size()); if ( list != null )
Will never throw null pointer exception If(list.size() != 0))
56
System.out.println(list.size());
BITS Pilani, Pilani Campus
Short Circuit Evaluation
Example 4: Problem with non-short-circuit evaluation
index = 0;
while (index < listlen) && (LIST[index] != key)
index = index + 1;

When index==listlen, LIST[index] causes an indexing


problem (if LIST has listlen-1 elements)

Potential problem with languages that provide short-circuit evaluation


and side-effects in expressions.

(a > b) && ( ( b++) / 3)

Solution: Provide additional operators that will cause full-evaluation


of an expression to occur in all cases.

• C-based languages use & and | for full-evaluation.

• Ada provides the two-word operators and then and or else to


specify that short-circuit evaluation is to be used.

BITS Pilani, Pilani Campus


Order of Evaluation

Church-Rosser theorem:
1. If E => F1 and E => F2, then there always exists a G such that F1 => G
and F2 => G.
2. If E has a normal form G, then there is a normal order evaluation E -> G.

Normal order Applicative order


/Lazy /Eager

In addition, normal order evaluation guarantees termination if the given expression


has a normal form.

BITS Pilani, Pilani Campus


Order of Evaluation

BITS Pilani, Pilani Campus


Order of Evaluation

<Condition>? <trueExpression> : <falseExpression>?


• Compiler can evaluate this expression in either lazy order (condition is
evaluated before expression) or eager order (condition and expression are
evaluated together).
• Most programming languages follow lazy order evaluation.

• Problem with eager order evaluation:


(n>=a)? n+1: n/a;

If a == 0 we have problem in eager evaluation!.


n/0 is run time error.
Compiler can’t detect.

BITS Pilani, Pilani Campus


Assignment Statements

BITS Pilani, Pilani Campus


The general syntax
<target_var> <assign_operator> <expression>
The assignment operator
= FORTRAN, BASIC, PL/I, C, C++, Java
:= ALGOLs, Pascal, Ada
LET,LET*,and LETREC in Scheme programming Language

Obviously, using = as the assignment operator and overloaded as the relational operator for
equality can lead to many errors and therefore a bad design decision.

• Example: if (x = y) will not be detected as an error in this case.

In the C-based languages the = operator can be embedded in expressions.


a = b = c; is possible along with if ( a > (b = c) ) …

Design choices have varied widely.


Fortran and Ada require that an assignment can only appear as a stand-alone
statement and the destination must be a single variable.

BITS Pilani, Pilani Campus


Conditional Assignment (flag)? total : subtotal = 0
Shorthand a += b
Unary Assignment i. sum = ++count
ii. sum = count++
iii. count++
iv. -count++
As expression 1 while ((ch = getchar())!= EOF){…}
first the assignment statement
As expression 2 a = b + (c = d / b++) -1
T1=b T1=b
T2= b+1 T2= b+1
T3 = d/ T1 T3 = d/ T2
T4 = T1+ T3 T4 = T1+ T3
T5= T4 -1 T5= T4 -1
a= T5; a= T5;
b= T2 b= T2;
List Assignment ($first, $second, $third) = (20, 40, 60);
($first, $second, $third) = (20, 40, 60, 70);
($first, $second, $third, $fourth) = (20, 40, 60);
Mixed Mode Assignment / Type int a, b;
conversion float c;
c = a / b;

BITS Pilani, Pilani Campus


Programming Language Example
string fun1(int x, string y,){
1) <Program> →<funcons>comma<functionbody>comma int a;
2) <funcons>→<funcon><funcons>/ ε string b;
3) <funcon> →<funsignature><functionbody> b = b + y;
4) <Funsignature>→ <type> id ( <params)> *y;
}
5) <type>→ int / float/string
6) <params>→ <type> id comma <params> / ε float fun2(int I, float j,){
7) <functionbody>→{ <declaraons> <statements> *<E>; } int k;
8) <declaraons>→ <type>id ; <declarations >/ ε k = I *j+k;
9) <statements> → id = <E>; <statements> *k;
/ id = id <more>;<statements>/ε }
10) <E>→ <E>+<E >
<E*E>/id/<intigerliteral>/<floatliteral>/<stringliteral> ,
{
11) <more> →(<args>)
float z; string s= “bits”;
12) <args> → id comma <args> / ε int p;
Z=10.5; p=5;
z = fun1(p,s,);
p = fun2(p,z,);
*z;
}
,

BITS Pilani, Pilani Campus


Modified Assignment Grammar : Rule number 9

<statements> → <Exp_stmt> ; <statements>/ <Assignment_stmt>; <statements> /


<Iterative_stmt> <statements>/ <Selection_stmt> <statements> /
<jump_stmt> <statements>

<Exp_stmt>  <Exp> /* include unary operations like ++count, --count, -count etc*/

<assignment_stmt>  id <assignment_opr><Exp>
/ id = id <more>;<statements>
/ cond-assign>/ ε
<assignment_opr>  = / *= / += / -= / /=

<cond-assign>  <Bool>? <Exp> : <Exp> = <number> ;

BITS Pilani, Pilani Campus


Type Conversions : Issues

 If x is float, is x=3 acceptable?


• Disallow
• Allow and implicitly convert 3 to float.
• "Allow" but require programmer to explicitly convert 3 to float

 How do we convert?
– Reinterpret bit sequence
– Build new object
 What should be allowed?
• float to int ?
• int to float ?

 Consider 3 + "4" in a language that can convert strings to integers.

BITS Pilani, Pilani Campus


Type Conversions

Implicit Conversion vs Explicit Conversion.

Narrowing vs Widening Conversion.

67
BITS Pilani, Pilani Campus
Type Conversions : Mixed mode Assignment

• Explicit type conversion by programmer:


• casting in C-based languages, e.g.,
– C: (int) angle
– Ada: Float (Sum)
• May cause errors in expressions
– Limitations of computer arithmetic, e.g. overflow

Implicit type conversion by compiler: coercion

• Disadvantage: decrease in the type error detection ability of the


compiler
• In most languages, all numeric types are coerced in expressions,
using widening conversions
• In Ada, there are virtually no coercions in expressions to minimize
errors .

68
BITS Pilani, Pilani Campus
Type Conversions : Mixed mode Assignment

int m, n;
float x, y;
scanf(“%d %d”,&m,&n);
scanf(“%f %f”,&x,&y);

printf("%d %f %f %d", m + n, x + y, m+y, n+x);

BITS Pilani, Pilani Campus


Type Conversions
• A narrowing conversion is one that converts an object to a
type that cannot include all of the values of the original type,
e.g., float to int
– Not always safe
• A widening conversion is one in which an object is converted
to a type that can include at least approximations to all of the
values of the original type, e.g., int to float
– Usually safe but may lose accuracy
Widening Narrowing (usually with a cast)

double double
float float
long long
int int
short byte char char short byte
70
BITS Pilani, Pilani Campus
Check List for Design

Constructs Issues
Identifiers (Naming, Binding, Scope, Lifetime)
Data Types ( Primitive and User Defined)
Expressions &
Assignment Statements
(Precedence , Associativity and Evaluation)
Type conversion √
Iterative Statements Condition vs Range
Selection Statements Two Way vs Multiple Selection

BITS Pilani, Pilani Campus


Iterative Statements

72
BITS Pilani, Pilani Campus
Condition Based
Rules for C Programming language iterative statements

Python can have else with while


Realized using
JMP
JA
JNBE
JNZ
JNE / JE in assembly Language

BITS Pilani, Pilani Campus


BITS Pilani, Pilani Campus
Range Based

75
BITS Pilani, Pilani Campus
For loop in Database Applications

76
BITS Pilani, Pilani Campus
Check List for Design

Constructs Issues
Identifiers (Naming, Binding, Scope, Lifetime)
Data Types ( Primitive and User Defined)
Expressions &
Assignment Statements
(Precedence , Associativity and Evaluation)

Iterative Statements Condition vs Range

Selection Statements Two Way vs Multiple Selection

BITS Pilani, Pilani Campus


Selection Statements

78
BITS Pilani, Pilani Campus
Selection Statements: Evolution

FORTRAN I control statements were based directly on IBM 704 hardware.


At the time, little was known about the inherent difficulties of programming so these were
considered to be completely adequate.
By today’s standards, they would be considered to be wholly inadequate.

There was much research and many arguments in the late 1960s and early
1970s about this issue.
One important result:
It was proven that all algorithms represented by flowcharts can be coded with only two-
way selection and pretest logical loops.
So the unconditional branch statement and its inherent problems was superfluous.
Other constructs have been added for readability/writability.
• For statement; post test loop…
• Need to balance…
– Increase in writability vs. decrease simplicity, size and readability.

79
BITS Pilani, Pilani Campus
Selection Statements

A selection statement provides the means of


choosing between two or more paths of execution
Two general categories:
–Two-way selectors
–Multiple-way selectors

80
BITS Pilani, Pilani Campus
Two-Way Selection Statements

• General form:
if control_expression
then clause
else clause
• Design Issues:
– What is the form and type of the control expression?
– How are the then and else clauses specified?
– How should the meaning of nested selectors be specified?

81
BITS Pilani, Pilani Campus
Two-Way Selection Statements

Form and type of the control expression

Must have some type of ‘syntactic marker’ to signal the beginning of


the ‘then clause’.
• Many languages use parentheses around the control
expression.
• Some use the keyword then after the control expression, in
which case, the parentheses may be omitted.
The type of the control expression may be
• arithmetic and/or boolean, or restricted to boolean
– C89 only supports arithmetic expressions.
– C99, C++ and Python allow arithmetic or boolean expressions.
– Ada, Java, Ruby and C# restrict the type to boolean.

82
BITS Pilani, Pilani Campus
Two-Way Selection Statements

Form of the then and else clauses


In most languages, these clauses can appear as either a single statement or a compound statement
(i.e. one or more statements “blocked” together)
• Examples: C based langauges, JavaScript, and PHP.
Early Fortran allowed only single statement, a GOTO was required to move to another statement.
In Perl, all clauses must be compound statements.
In Fortran 95, Ada, Ruby, and Python, the clauses are statement sequences.
• Interesting Example in Python, where indention is used to specify compound statements.

If x > y :
x = y;
print “case 1”

83
BITS Pilani, Pilani Campus
Nesting Selectors

Java example
if (sum == 0)
if (count == 0)
result = 0;
else result = 1;
Which if gets the else?
Java's static semantics rule: else matches with
the nearest if

84
BITS Pilani, Pilani Campus
Nesting Selectors (continued)

To force an alternative semantics, compound statements


may be used:
if (sum == 0) {
if (count == 0)
result = 0;
}
else result = 1;
Perl requires all then and else clauses to be compound, thus requiring
braces. The above code would be:
if (sum == 0) {
if (count == 0) {
result = 0;
}
} else {
result = 1;
}
85
BITS Pilani, Pilani Campus
Nesting Selectors (continued)

Ways to form compound statements:


Braces as in Java, C, c++, C# (Note that Perl requires compound statements…)
if (sum == 0) {
if (count == 0)
result = 0;
}
else result = 1;

Indentation as in Python..
• Python Example:
if sum == 0 :
if count == 0 :
result = 0
else:
result = 1
end

Use of a special word to mark then end of the selection construct, as in Fortran 95, Ada and Ruby.
• Ruby Example:
if sum == 0 then
if count == 0 then
result = 0
end
else
result = 1
end 86
BITS Pilani, Pilani Campus
Multiple-Way Selection Statements

• Allow the selection of one of any number of statements


or statement groups
• Design Issues:
– What is the form and type of the control expression?
– How are the selectable segments specified?
– Is execution flow through the structure restricted to include just
a single selectable segment? Usage of Break in C
– What is done about unrepresented expression values?
Usage of “Default” in “switch” statement and “else” after “else-if “
clause in C Language.

87
BITS Pilani, Pilani Campus
Multiple-Way Selection: Examples

Early multiple selectors:


FORTRAN arithmetic IF (a three-way selector)
IF (arithmetic expression) N1, N2, N3
Segments require GOTOs
Not encapsulated (selectable segments could be
anywhere)

88
BITS Pilani, Pilani Campus
Multiple-Way Selection: Examples

• Design choices for C’s switch statement


– Control expression can be only an integer type
– Selectable segments can be statement sequences, blocks, or
compound statements
– Any number of segments can be executed in one execution of the
construct (there is no implicit branch at the end of selectable
segments) Must use breaks if this is needed.
– default clause is for unrepresented values (if there is no default,
the whole statement does nothing)
– Syntax:
switch (control expression) {
case const_expr_1: stmt_1;

case const_expr_n: stmt_n;
[default: stmt_n+1]
}
89
BITS Pilani, Pilani Campus
Multiple-Way Selection: Examples

The Ada case statement


case expression is
when choice list => stmt_sequence;

when choice list => stmt_sequence;
[when others => stmt_sequence;]
end case;
More reliable than C’s switch (once a stmt_sequence
execution is completed, control is passed to the first
statement after the case statement. Implicit break…

90
BITS Pilani, Pilani Campus
Multiple-Way Selection: Examples

Ruby has two forms of multiple-selection constructs called case expressions.


•Form 1
case
when boolean expression then expression
when boolean expression then expression
[else expression]
end
Algorithm for leap year:
Example: if ( (year modulo 4 is 0) and
case
when year % 400 == 0 then true
(year modulo 100 is not 0)
when year % 100 == 0 then false or
else year % 4 == 0 (year modulo 400 is 0) )
end
•Form 2
case expression then leap
when value then statement sequence
when value then statement sequence else no_leap
[else statement sequence]
end
•Example
case year
when (1700..1799) then “Eighteenth”
when (1800..1899) then “Nineteenth”
when (1900..1999) then “Twentieth”
else “Other”
end

91
BITS Pilani, Pilani Campus
Multiple-Way Selection Using if

Multiple Selectors can appear as direct extensions to two-way selectors, using else-if clauses.
Ada example:
if ...
then ...
elsif ...
then ...
elsif ...
then ...
else ...
end if

Python example:
if count < 10 :
bag1 = True
elif count < 100 :
bag2 = True
elif count < 1000 :
bag3 = True

Ruby example:

case
when count < 10 then bag1 = True
when count < 100 then bag2 = True
when count < 1000 then bag3 = True

92
BITS Pilani, Pilani Campus
Grammar for Selection In C Language

BITS Pilani, Pilani Campus


Tutorial 2

BITS Pilani, Pilani Campus


1) <Program> →<functions>comma<functionbody>comma
2) <functions>→<function><functions>/ ε
3) <function> →<funsignature><functionbody>
4) <Funsignature>→ <type> id ( <params>)
5) <type>→ int / float
6) <params>→ <type> id comma <params> / ε
7) <functionbody>→{ <declarations> <statements> *<E>; }
8) <declarations>→ <type>id ; <declarations >/ ε
9) <statements> → id = <E>;/ id = id <more>;<statements>/ε
10) <E>→ <E>+<E >/ <E*E>/id/<intigerliteral>/<floatliteral>/<stringliteral>
11) <more> →(<args>)
12) <args> → id comma <args> / ε
Test Case
,
float fun(int I, float j,int a[],) {
{ float k ,z;
float k; int p,b[1...10];
int m,n; enum size {L=2,Small=0,Medium,XL=3,XXL};
m=2; n=3; enum size Shirtsize;
k =(float) I *j+k+m+n; z=10.5; p=5;
*k; k= fun2(p,z,b);
} *z;
}
,

BITS Pilani, Pilani Campus


1) <Program> →<functions>comma<functionbody>comma
2) <functions>→<function><functions>/ ε
3) <function> →<funsignature><functionbody>
4) <Funsignature>→ <type> id ( <params>)
5) <type>→ int / float/<enumdec>
6) <params>→ <type> id comma <params> / ε
7) <functionbody>→{ <declarations> <statements> *<E>; }
8) <declarations>→ <type> <idlist> / <declarations > /<enumtype>/ ε
9) <statements> → id := <E>;/ id := id <more>;<statements>/ε
10) <E>→ <typecast> <E>+<E > /<typecast> <E*E> / id / <intigerliteral> / <floatliteral> / <stringliteral>
11) <more> →(<args>)
12) <args> → id comma <args> / ε
13) <decend>  comma / ;
14) <idlist>→id <decend><idlist>/<arraytype><idlist>/ ε
15) <arraytype>→ id[<intigerliteral>...<intigerliteral>]
16) <enumtype>→ enum id { <enumlist>}
17) <enumlist>→ <enumerator>,<enumlist>/<enumerator>
18) <enumerator>→ id / id=<intigerliteral>
19) <enumdec>→ enum id id;
20) <typecast>→ (<type>) / ε
BITS Pilani, Pilani Campus
Modify the grammar to add Iterative and Selection statements

<statements> →<statement> <statements> / ε


<statement>  <Exp_stmt> ; <statements>/ <Assignment_stmt>; <statements> /
<Iterative_stmt> <statements>/ <Selection_stmt> <statements>

Example : Iterative statements in C Language

BITS Pilani, Pilani Campus


Write Grammar to have

• Goto label
• Continue
• Break
• Return
Inside the for statement.

BITS Pilani, Pilani Campus


Modify the grammar to add Iterative and Selection statements

<statements> →<statement> <statements> / ε

<statement> → <Exp_stmt> ; <statements>/ <Assignment_stmt>; <statements> /


<Iterative_stmt> <statements>/ <Selection_stmt> <statements> /
<jump_stmt>; <statements>

Jump Statement

<Jump_stmt> → goto id / continue / break / *<exp>

BITS Pilani, Pilani Campus


Some More requirement

BITS Pilani, Pilani Campus


<statements> →<statement> <statements> / ε

<statement> → <Exp_stmt> ; <statements>/ <Assignment_stmt>; <statements> /


<Iterative_stmt> <statements>/ <Selection_stmt> <statements> /
<jump_stmt>; <statements>

<Iterative_stmt> for id in <stringliteral> <statements>


/ for id in <array_type> <statements>
/ for id in range(<integerliteral>,<integerliteral>) <statements>
/ for id in reverse <stringliteral> <statements>
/ for id in reverse <array_type> <statements>
/ for id in reverse range (<integerliteral>,<integerliteral>) / <statements>

Left factored Grammar


<Iterative_stmt> for id in <reversed> <iterative_option> <statements>

<iterative_option> <stringeral> / <array_type> / range(<integerliteral>,<integerliteral>)

<reversed>  reverse / ε
<Compound_stmt>  { <statements> } / <statements>
BITS Pilani, Pilani Campus
Modify grammar to add selection Statements

• Two way selective statements


if-else
• Nesting if-else statement.
• Multiple selective statements
If-elseif…………………….else
Switch(exp){ case 1:…………………………case n: default: }
Or
Case(exp) : When(choice_list)…..When(choice_list)…..else.

Tell them break is required in switch statement as in C


Language but later need not have break statement.

BITS Pilani, Pilani Campus


Choice for two way selection Statements

If ( Cond_exp) If ( Cond_exp)
If ( Cond_exp) If ( Cond_exp)
{ {
<statement> <statement>
<statements> <statements>
else else
} }
{ <statement>
else else
<statements>
{ <statement>
}
<statements>
}

If ( Cond_exp)
If ( Cond_exp):
then
<statements>
<statements>
endif
else
else
then
<statements>
<statements>
endelse
BITS Pilani, Pilani Campus
<Selection_stmt> if (cond_exp) { <statements> } else { <statements>}
/ if(cond_exp) { <statements> }
/ if (cond_exp) <statement> else { <statements>}
/ if(cond_exp) <statement>
/ if (cond_exp) { <statements> } else <statement>
/ if (cond_exp) <statement> else <statement>

BITS Pilani, Pilani Campus


Choice for Multiple way selection Statements

If ( Cond_exp) If ( Cond_exp)
{ {
<statements> <statements>
} }
else if (Cond_exp)
{ else if (Cond_exp)
<statements> <statement>
}
else if (Cond_exp) else if (Cond_exp)
{ {
<statements> <statements>
} }
else else
{ {
<statements> <statements>
} }

BITS Pilani, Pilani Campus


<Selection_stmt> if (cond_exp) { <statements> } <else_if> else { <statements>}
/ if(cond_exp) { <statements> }
/ if (cond_exp) <statement> <else_if> else { <statements>}
/ if(cond_exp) <statement>
/ if (cond_exp) { <statements> } <else_if> else <statement>
/ if (cond_exp) <statement> <else_if> else <statement>

<else _if>  else if (Cond_exp) { <statements> } <else_if>/ ε


/ else if (cond_exp) <statement> <else_if>

BITS Pilani, Pilani Campus


End of Tutorial 2

BITS Pilani, Pilani Campus


Check List for Design

Constructs Issues
Identifiers (Naming, Binding, Scope, Lifetime)
Data Types ( Primitive and User Defined)
Expressions &
Assignment Statements
(Precedence , Associativity and Evaluation)

Iterative Statements Condition vs Range

Control Statements Control Statements.

BITS Pilani, Pilani Campus


Identifiers

BITS Pilani, Pilani Campus


Topics

• Introduction
• Variables (Name, Address, type, value)
• The Concept of Binding
• Scope (Static vs Dynamic)
• Type Checking
• Type Equivalence
• Referencing Environments
• Named Constants

110
BITS Pilani, Pilani Campus
Introduction

Imperative languages are abstractions of von Neumann architecture


Memory
Processor
A variable is an abstraction of a memory cell
Variables can be characterized as a six tuple of attributes:
Name
Address
Value
Type
Lifetime
Scope
To design a type, must consider scope, lifetime, type checking,
initialization, and type compatibility

111
BITS Pilani, Pilani Campus
Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

– Case sensitivity

 ROSE, rose, Rose are different in C-based languages

• Disadvantage: readability (names that look alike are


different)
– Names in the C-based languages are case sensitive
– Names in C++, Java, and C# have predefined
names with mixed case

 parseInt : to convert form char to int, Parseint: are not


recognized in java

112
BITS Pilani, Pilani Campus
Length

If too short, they cannot be connective


Language examples:
FORTRAN I: maximum 6
COBOL: maximum 30
FORTRAN 90 and C89: maximum 31
C99: maximum 63
C#, Ada, and Java: no limit, and all are significant
C++: no limit, but implementers often impose one

BITS Pilani, Pilani Campus


Special words

– Special words -- reserved words or keywords?


An aid to readability; used to delimit or separate statement
clauses
A keyword is a word that is special only in certain
contexts, e.g., in Fortran
» Real VarName (Real is a data type followed with a
name, therefore Real is a keyword)
» Real = 3.4 (Real is a variable)
A reserved word is a special word that cannot be used as a
user-defined name
Potential problem with reserved words: If there are too
many, many collisions occur (e.g., COBOL has 300
reserved words!)

BITS Pilani, Pilani Campus


Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

• Address - the memory address with which it is associated


A variable may have different addresses at different times during
execution
A variable may have different addresses at different places in a
program
If two variable names can be used to access the same memory
location, they are called aliases
Aliases are created via pointers, reference variables, Using
Typedef in C and C++
• Aliases can be harmful to readability (program readers
must remember all of them)

115
BITS Pilani, Pilani Campus
Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

Value - the contents of the location with which the variable is


associated
Abstract memory cell - the physical cell or collection of cells
associated with a variable

- The l-value of a variable is its address


- The r-value of a variable is its value
To access r-value, the l value must be determined first.
Scoping rules can greatly complicate matters.

116
BITS Pilani, Pilani Campus
Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

Type –
Determines the range of values of variables
and
the set of operations that are defined for values of that type;

In the case of floating point, type also determines the precision

Type Binding
How is a type specified?
When does the binding take place?

117
BITS Pilani, Pilani Campus
First -- The Concept of Binding…

A binding is an association, such as between an attribute and


an entity, or between an operation and a symbol
Binding time is the time at which a binding takes place.
Static Binding
• A binding is static if it first occurs before run time and
remains unchanged throughout program execution.
Dynamic Binding
• A binding is dynamic if it first occurs during execution
or can change during execution of the program

A Complete Understanding of the binding times of the


attributes of program entities is a prerequisite for
understanding the semantics of the programming
language.

118
BITS Pilani, Pilani Campus
Possible Binding Times

• Language design time


Binding of an operator symbol to its operation
• Language implementation time
Binding of the floating point data type to a specific
representation
• Compile time
Binding of a variable to a type as in C or Java
• Load time
Binding of a variable to a memory cell as with C or C++
static variables
• Runtime
Binding of a non static local variable to a memory cell

119
BITS Pilani, Pilani Campus
Binding Times Static vs Run time

Static
int m, n;
float x, y;
scanf(“%d %d”,&m,&n);
scanf(“%f %f”,&x,&y);

printf("%d %f %f %d", m + n, x + y, m+y, n+x);

Dynamic Static
void function(m,n,x,y) void function(int m, int n, float x, float y)
{ {
OP1= m+n; OP1= m+n;
OP2 = x*y; OP2 = x*y;
OP3 = x*m; OP3= x*m;
} }

BITS Pilani, Pilani Campus


The following code declares three distinct functions in C++.

int max (int x, int y);


int max (int x, int y, int z);
float max (float x, float y);

BITS Pilani, Pilani Campus


Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

Static Type Binding -- Explicit/Implicit Declaration

An explicit declaration is a program statement used for


declaring the types of variables
int count;

An implicit declaration is a default mechanism for specifying


types of variables (the first appearance of the variable in the
program)

Pre 1960s - FORTRAN, PL/I, BASIC


Post 1960s –JavaScript, Ruby, and ML
Perl uses special characters to denote type ($ scalar and @ for
array )
Advantage: writability
Disadvantage: reliability
– Forgotten declarations in Python and Fortran.
122
BITS Pilani, Pilani Campus
Implicit:
scanf(“%d %d”,&m,&n);
scanf(“%f %f”,&x,&y);

printf("%d %f %f %d", m + n, x + y, m+y, n+x);

Explicit
int m, n;
float x, y;
scanf(“%d %d”,&m,&n);
scanf(“%f %f”,&x,&y);

printf("%d %f %f %d", m + n, x + y, m+y, n+x);

BITS Pilani, Pilani Campus


Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

Dynamic Type Binding


When the assignment statement is executed, the name on the
lhs is bound to the type of the value of the rhs
• JavaScript
list = [2, 4.33, 6, 8];
list = 17.3;
Advantage: flexibility (generic program units)
Disadvantages:
• High cost (dynamic type checking and interpretation)
• Type error detection by the compiler is difficult

124
BITS Pilani, Pilani Campus
Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

Who is in the memory?

BITS Pilani, Pilani Campus


Lifetime and Scope

Lifetime
• Period of time when location is allocated to program
Scope
• Region of program text where declaration is visible
– Inner declaration of x hides outer: “hole in scope”

BITS Pilani, Pilani Campus


Run-time Environments

• The compiler creates and manages a run-time environment


in which it assumes the target program will be executed
• Includes
– Layout and allocation of storage locations for named
program objects
– Mechanism for the target program to access variables
– Linkages between procedures
– Mechanisms for passing parameters
– Interfaces to the operating system for I/O and other
programs

127

BITS Pilani, Pilani Campus


Memory Manager

• The memory manager has one large chunk of memory from the
operating system that it can manage for the application
program
• Allocation – when a program requests memory for a variable or
an object (anything requiring space), the memory manager
gives it the address of a chunk of contiguous heap memory
– if there is no space big enough, can request the operating
system for virtual space
– if out of space, inform the program
• De-allocation – returns de-allocated space to the pool of free
space
– doesn’t reduce the size of space and return to the operating
system
128

BITS Pilani, Pilani Campus


Storage Organization

• Assumes a logical address space


– Operating system will later map it to physical
addresses, decide how to use cache memory, etc.
• Memory typically divided into areas for
– Program code
– Other static data storage, including global constants
and compiler generated data
– Stack to support call/return policy for procedures
– Heap to store data that can outlive a call to a
procedure

Code Static Heap Free Memory Stack


129

BITS Pilani, Pilani Campus


Heap Management

• Store used for data that lives indefinitely, or until the


program explicitly deletes it
• Memory manager allocates and de-allocates memory in the
heap
– calls to free and delete can be generated by the
compiler, or in some languages, explicitly by the
programmer
• Garbage Collection is an important subsystem of the
memory manager that finds spaces within the heap that
are no longer used and can be returned to free storage
– the language Java uses the garbage collector as the de-
allocation operation

130

BITS Pilani, Pilani Campus


Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

The lifetime of a variable is the time during which it is bound to


a particular memory cell
• Static
• Stack-dynamic
• Explicit heap-dynamic
• Implicit heap-dynamic

131
BITS Pilani, Pilani Campus
Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

• Static
Bound to memory cells before program execution begins and
remains bound to the same memory cell throughout execution.
• C and C++ static variables

–Advantages:
• efficiency – static constants in Java
• efficiency - (direct addressing) and no run-time
allocate/deallocate
• history-sensitive support

–Disadvantage: lack of flexibility (no recursion)

132
BITS Pilani, Pilani Campus
Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

Stack-dynamic
Storage bindings are created for variables when their
declaration statements are elaborated.
• A declaration is elaborated when the executable code
associated with it is executed.
• Local variables of a method in Java
Advantages
allows recursion
conserves storage

Disadvantages
Overhead of allocation and de-allocation
Subprograms cannot be history sensitive
Inefficient references (indirect addressing)

133
BITS Pilani, Pilani Campus
Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

Explicit heap-dynamic
allocated and de-allocated by explicit directives, specified by the
programmer, which take effect during execution
Referenced only through pointers or references
• dynamic objects in C++ (via new and delete)
int *intnode;

intnode = new int;

Delete intnode;

• Objects in Java
–Advantage: provides for dynamic storage management
–Disadvantages: inefficient and can be unreliable due to the
complexities of storage management
134
BITS Pilani, Pilani Campus
Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

Implicit heap-dynamic
Bound to heap storage only when assigned a value
• allocation and de-allocation caused by assignment
statements
– all variables in APL; all strings and arrays in Perl,
JavaScript, and PHP
» Highs = [74, 80, 85, 90]

• Advantage: flexibility (generic code)


• Disadvantages:
– Inefficient, because all attributes are dynamic
– Loss of error detection

135
BITS Pilani, Pilani Campus
Classify the variables in the program according to their Lifetime

static int x; Variable Category


int m; 1. x Static
int fun(double a) 2 m Static
{ 3. a Stack
static int z = 0; 4. z Static
int y[100] ; 5. y Stack
int *ptr = new (int); 6. ptr Stack
static char *p= {"B","I","T","S"}; 7 the anonymous Heap
... object to which
} ptr points.
8 p Static
9 the string BITS Heap
which p is
pointing to.

BITS Pilani, Pilani Campus


Run-time stack

• Each time a procedure is called (or a block entered), space


for local variables is pushed onto the stack.
• When the procedure is terminated, the space is popped off
the stack.
• If procedure p calls procedure q, then even in cases of
exceptions and errors, q will always terminate before p.
• Activations of procedures during the running of a program
can be represented by an activation tree
• Each procedure activation has an activation record (aka
frame) on the run-time stack.
– The run-time stack consists of the activation records at
any point in time during the running of the program for
all procedures which have been called but not yet
returned.

137
BITS Pilani, Pilani Campus
Activation Tree
main()
{ …;
g(x);
main Global area
return(0); }
activation
record for
void g(int m) main
{ … g(2) activation
f(y); … record for
g(2)
g(y);
activation
activation
… f(1) g(1) record
recordforfor
} g(1)
f(1)
activation
void f(int n) record for
g(1) g(1)
{ g(n);

}
138
BITS Pilani, Pilani Campus
Finding the factorial of 3

fact(1)
1
fact(2) fact(2) fact(2)
2
fact(3) fact(3) fact(3) fact(3) fact(3)
6
main() main() main() main() main() main()

Time 2: Time 3: Time 4: Time 5: Time 6: Time 7:


Push: fact(3) Push: fact(2) Push: fact(1) Pop: fact(1) Pop: fact(2) Pop: fact(3)

returns 1. returns 2. returns 6.

Inside findFactorial(3): Inside findFactorial(2): Inside findFactorial(1):

if (number <= 1) return 1; if (number <= 1) return 1; if (number <= 1) return 1;

else return (3 * factorial else return (2 * factorial else return (1 * factorial (0));
(2)); (1));

BITS Pilani, Pilani Campus


Storage Allocation

High address
Parameter &
Heap Return value
Control link & Activation
Saved status Record

Stack ptr Frame pointer


Local temps (fp)

Stack Parameter &


Return value
Control link &
Static data
Saved status

Code Local temps

Low address

BITS Pilani, Pilani Campus


Activation Record
Format or Layout of the non code part of sub-program

Temporaries temporaries

Return a value to the calling


Returned value
procedure

Local data Local data

To supply parameters to the called


parameter procedure
Optional access link / To refer to nonlocal data held in the
static link other activation records

Optional control link /


dynamic link Points to the activation record of
the caller
Return Address Info about the state of the machine
just before the proc is called
BITS Pilani, Pilani Campus
An Example: C Function

void sub(float total, int part)


{ [4]

int list[4]; [3]

float sum; [2]

… [1]

}
[0]

142
BITS Pilani, Pilani Campus
void main() ARI: Activation Record Instance
{
int a,b,c;
c=sum(a,b);
print(c);
}

int sum(int m, int n)


{
int res;
res = m+f(n);
return(res);
}

int f(int p)
{ NIL 1008 sp
int i; return value 1007

for(i=0;i<5;i++) c 1006

{ b 1005
a 1004
ARI of function main
p= p+i;
} NIL 1003

return(p): NIL 1002

} NIL 1001
fp return global env 1000
Call Sequence in Stack-based Environments

• Calling sequence
– Store return address
– Push fp as control link
– Copy sp to fp
– Push arguments
– Reserve space for local
variables
• Return sequence
– Copy fp to sp
– Load control link into fp
– Jump to return address
– Change sp

144
void main()
{
int a,b,c;
c=sum(a,b);
print(c);
}
NIL 1016 sp
int sum(int m, int n)
return value 1015
{
res 1014
int res;
n 1013
res = m+f(n);
m 1012
return(res);
NIL 1011
} ARI of function sum
1000 1010

int f(int p) fp return main 1009

NIL 1008
{
return value 1007
int i;
c 1006
for(i=0;i<5;i++)
b 1005
{
a 1004 ARI of function main
p= p+i;
NIL 1003
}
NIL 1002
return(p):
NIL 1001
}
return global env 1000
void main() temp 1023
sp
{ return value 1022
int a,b,c; i 1021
c=sum(a,b); p 1020
print(c); NIL 1019 ARI of function f
} 1009 1018

fp return sum 1017

int sum(int m, int n) NIL 1016


{ return value 1015
int res; res 1014
res = m+f(n); n 1013

return(res); m 1012

} NIL 1011 ARI of function sum


1000 1010
return main 1009
int f(int p)
NIL 1008
{
return value 1007
int i;
c 1006
for(i=0;i<5;i++)
b 1005
{
a 1004 ARI of function main
p= p+i; NIL 1003
} NIL 1002
return(p): NIL 1001
} return global env 1000
Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

The scope of a variable is the range of statements over which it is visible

The non local variables (free variables) of a program unit are those that
are visible but not declared there

The scope rules of a language determine how references to names are


associated with variables.
• Disallowing them altogether (except keywords and special forms)
• Lexical Scoping: Compile Time
-- Only two scoping Levels- Global and Local.
-- Nested scoping
• Dynamic Scoping: At run time.

147
BITS Pilani, Pilani Campus
Static Scope

• Also called Lexical Scope


• Lexical scope rules specify the association of variables
with declarations based on just the examination of the
source code
• The binding of variables to declarations is done at compile
time
• It is based on their spatial relationship
• Pascal and C use Static Scoping rules

BITS Pilani, Pilani Campus


void main() {
int x,y,z;
program MAIN_2;
var X : integer; while(…)
procedure BIGSUB;
var A, B, C : integer; {
procedure SUB1;
var A, D : integer;
int a,b,c;
begin { SUB1 } ……………
A := B + C; <-----------------------1
end; { SUB1 } while(…)
procedure SUB2(X : integer);
var B, E : integer; {
procedure SUB3;
var C, E : integer;
int d,e;
begin { SUB3 } ……
SUB1;
E := B + A: <--------------------2 }
end; { SUB3 }
begin { SUB2 } }
SUB3; while(………)
A := D + E; <-----------------------3
end; { SUB2 } {
begin { BIGSUB }
SUB2(7); int f,g;
end; { BIGSUB }
begin }
BIGSUB; }
end; { MAIN_2 }
BITS Pilani, Pilani Campus
Dynamic Scope
• The binding of variables to declarations is done at run time
• It is based on the calling sequence of subprograms.
• Pure Lisp and original Common Lisp, as well as Snobol and APL
use Dynamic Scoping Rules

void sub3() { In sub3:


int x, z; Call Sequence
reference to x is local
x = u + v; main calls sub1
} sub1 calls sub1
reference to u searches all
void sub2() { sub1 calls sub2
activation records on stack
int w, x; ... sub2 calls sub3
until main
} Run time Stack reference to v is in most recent
void sub1() { Sub3 :x,z activation record of sub1
int v, w; ...
Sub2 :w,x
}
int main() {
Sub1: v,w
int v, u; ... Sub1: v,w
} Main: v,u 150
BITS Pilani, Pilani Campus
Implementing Dynamic Scoping

Deep Access: non-local references are found by searching the


activation record instances on the dynamic chain.
Example in previous slide

•Shallow Access: put locals in a central place


One stack for each variable name
Central table with an entry for each variable name

151
BITS Pilani, Pilani Campus
For Dynamic Scoping check the visibility of Non-local variable

void main()
fun2
{
int a,b,c,d,e,f; fun1
fun1() main a b c d e f
}

int fun1( )
{
int res, a,b,g,h,i,j;
Fun2()
}

int fun2( )
{
int a,b,g,l,m,n;
Draw run time stack
}

BITS Pilani, Pilani Campus


For Dynamic Scoping check the visibility of Non-local variable

void main()
fun2
{
int a,b,c,d,e,f; fun1 a b g h i j c d e f
fun1() main a b c d e f
}

int fun1( )
{
int res, a,b,g,h,i,j;
Fun2()
}

int fun2( )
{
int a,b,g,l,m,n;

BITS Pilani, Pilani Campus


For Dynamic Scoping check the visibility of Non-local variable

void main()
fun2 a b g l m n c d e f h i j
{
int a,b,c,d,e,f; fun1 a b g h i j c d e f
fun1() main a b c d e f
}

int fun1( )
{
int res, a,b,g,h,i,j;
Fun2()
}

int fun2( )
{
int a,b,g,l,m,n;

BITS Pilani, Pilani Campus


Exercise:

void main()
fun2
{
int a,b,c,d,e,f; fun1
fun1() main
fun2()
}

int fun1( )
{
int res, a,b,g,h,i,j;
}

int fun2( )
{
int a,b,g,l,m,n;
Draw run time stack
Fill the visible variables
}
Calculate the address of non local variable

BITS Pilani, Pilani Campus


Exercise:

void main()
fun2 a b g l m n c d e f
{
int a,b,c,d,e,f; fun1 a b g h i j c d e f
fun1() main a b c d e f
fun2()
}

int fun1( )
{
int res, a,b,g,h,i,j;
}

int fun2( )
{
int a,b,g,l,m,n;
Draw run time stack
Fill the visible variables
}
Calculate the address of non local variable

BITS Pilani, Pilani Campus


Example 1 :Static vs Dynamic

int i = 10;

void fun1() {
printf(“Inside fun1…%d\n”, i);
}
Static Scope
void fun2() { Inside fun1… 10
int i = 20;
Inside fun1… 10
fun1();
} Inside fun1… 10

int main() {
fun1(); Dynamic Scope
fun2(); Inside fun1… 10
fun1();
} Inside fun1… 20
Inside fun1… 10

BITS Pilani, Pilani Campus


Example 2: Static vs. Dynamic Scope

var a : integer;

procedure first
a := 1;

procedure second
var a : integer;
first();

begin
a := 2;
second();
write_integer(a);
end;
158
BITS Pilani, Pilani Campus
Example 2: Static Scope

var a : integer;

procedure first
a := 1; var a : integer;
main()
a := 2;
procedure second second()
var a : integer; var a : integer;
first(); first()
a := 1;
write_integer(a);
begin
a := 2;
second(); The program prints 1
write_integer(a);
end;
159
BITS Pilani, Pilani Campus
Example 2: Dynamic Scope

var a : integer;

procedure first
a := 1; var a : integer;
main()
a := 2;
procedure second second()
var a : integer; var a : integer;
first(); first()
a := 1;
write_integer(a);
begin
a := 2;
second(); The program prints 2
write_integer(a);
end;
160
BITS Pilani, Pilani Campus
Example 3: Static vs. Dynamic Scope

int n = 1;
print_plus_n(int x)
{
Print( x + n);
}
increment_n()
{
n = n + 2;
print_plus_n(n);
}
Static Scoping
main() {
8 6 50
int n;
n = 200;
Dynamic Scoping
print_plus_n(7);
207 104 52
n = 50;
increment_n();
Print( n);
}

BITS Pilani, Pilani Campus


Example 4: Static vs. Dynamic Scope

void P() { write x; }

void Q() {
x = x + 1;
if (x < 23) Q();
else P();
}

void R() {
int x = 20; Dynamic Scoping
Q(); 23
P(): 23
} 10

void main() {
int x = 10;
R();
P();
}

BITS Pilani, Pilani Campus


Dynamic scope - Shallow Access

Alternative implementation, not a different semantics


Variables are not stored in activation records of subprograms
Have separate stack for each variable. When subprogram begins,
values are pushed onto stack. When it exits, values are popped
off all stacks.
Allows fast references, but costly exits and entrances to
subprograms

163
BITS Pilani, Pilani Campus
Using Shallow Access to Implement Dynamic Scoping

void subC() {
int x, z;
x = u + v;
}
void subB() {
int w, x; ...
}
A B
Stacks
void subA() { A C A
int v, w; ...
Main Main B C A
}
int main() { Variables u v x z w
int v, u; ...
}
main calls subA Names in the stack cells indicate the
subA calls subA program units of the variable declaration
subA calls subB
subB calls subC

164
BITS Pilani, Pilani Campus
Blocks

Blocks are user-specified local scopes for variables


An example in C
{
int temp;
temp = list [upper];
list [upper] = list [lower];
list [lower] = temp
}
The lifetime of temp in the above example begins when control
enters the block
An advantage of using a local variable like temp is that it
cannot interfere with any other variable with the same name

165
BITS Pilani, Pilani Campus
Implementing Blocks

• Two Methods:
1. Treat blocks as parameter-less subprograms that are
always called from the same location
– Every block has its own activation record; an
instance is created every time the block is executed
2. Since the maximum storage required for a block can be
statically determined, this amount of space can be
allocated after the local variables in the activation
record. Blocks that are not active at the same time can
reuse space.

166
BITS Pilani, Pilani Campus
Static Link
void main() {
int x,y,z,m; f, g while 3
while(…) ---1
{ d, e, m while 2
int a,b,c,m;
…………… a ,b, c, m while 1
while(…)-2
{ x, y, z, m main
int d,e,m;
d = b + x + m;

}
Statically visible variables
}
While 3 F G X Y Z M
while(………)-3
{ While 2 D E M A B C X Y Z
int f,g; While 1 A B C M X Y Z
f=b + x + m; Main X Y Z M
}
}
BITS Pilani, Pilani Campus
Static Chain- for Nested Scoping

A static chain is a chain of static links that connects certain


activation record instances
The static link in an activation record instance for subprogram
A points to one of the activation record instances of A's static
parent (for access to variables)

The static chain from an activation record instance connects it


to all of its static ancestors

168
BITS Pilani, Pilani Campus
void main() {
int x,y,z;
while(…)
e
{
int a,b,c; d
…………… Block c
while(…) Variables b and g
{ a and f
int d,e; z
…… Local
y
} Variables
x
}
while(………)
{
int f,g;
}
}
BITS Pilani, Pilani Campus
Nested Subprograms

• Some non-C-based static-scoped languages (e.g., Fortran 95, Ada,


Python, JavaScript) use stack-dynamic local variables and allow
subprograms to be nested.

procedure A is
procedure B is
procedure C is
...
end; -- of C
procedure D is
...
end; -- of D
end; -- of B
end; -- of A
170
BITS Pilani, Pilani Campus
Example Pascal Program
program MAIN_2; Static Structure of the program
var X : integer;
procedure BIGSUB;
var A, B, C : integer;
procedure SUB1;
var A, D : integer;
begin { SUB1 }
A := B + C; ----1
end; { SUB1 }
procedure SUB2(X : integer);
var B, E : integer;
procedure SUB3;
var C, E : integer;
begin { SUB3 }
SUB1; VS
E := B + A: ----- 2
end; { SUB3 }
begin { SUB2 } Call sequence for MAIN_2
SUB3;
A := D + E; --------3
end; { SUB2 } MAIN_2 calls BIGSUB
begin { BIGSUB }
SUB2(7);
BIGSUB calls SUB2
end; { BIGSUB } SUB2 calls SUB3
begin
BIGSUB; SUB3 calls SUB1
end; { MAIN_2 }

171
BITS Pilani, Pilani Campus
Example Pascal Program
program MAIN_2;
var X : integer;
procedure BIGSUB;
var A, B, C : integer;
procedure SUB1; Statically visible variables
var A, D : integer;
begin { SUB1 } SUB 3 C E B A X
A := B + C; ----1
end; { SUB1 } SUB2 B E A C X
procedure SUB2(X : integer);
var B, E : integer; SUB1 A D B C X
procedure SUB3;
var C, E : integer; BIGSUB A B C X
begin { SUB3 }
SUB1; Main_2 X
E := B + A: ----- 2
end; { SUB3 }
begin { SUB2 }
SUB3;
A := D + E; --------3 Call sequence for MAIN_2
end; { SUB2 }
begin { BIGSUB }
SUB2(7); MAIN_2 calls BIGSUB
end; { BIGSUB }
begin BIGSUB calls SUB2
BIGSUB; SUB2 calls SUB3
end; { MAIN_2 }
SUB3 calls SUB1
172
BITS Pilani, Pilani Campus
Example Pascal Program
program MAIN_2;
var X : integer;
procedure BIGSUB; Dynamically visible variables
var A, B, C : integer;
procedure SUB1; SUB 1 A D C E X B
var A, D : integer;
begin { SUB1 }
SUB3 C E B A X
A := B + C; ----1 SUB2 B E A C X
end; { SUB1 }
procedure SUB2(X : integer);
var B, E : integer;
procedure SUB3; BIGSUB A B C X
var C, E : integer;
begin { SUB3 } Main_2 X
SUB1;
E := B + A: ----- 2
end; { SUB3 }
begin { SUB2 } Call sequence for MAIN_2
SUB3;
A := D + E; --------3
end; { SUB2 } MAIN_2 calls BIGSUB
begin { BIGSUB }
SUB2(7);
BIGSUB calls SUB2
end; { BIGSUB } SUB2 calls SUB3
begin
BIGSUB; SUB3 calls SUB1
end; { MAIN_2 }

173
BITS Pilani, Pilani Campus
D

Example Pascal Program A


SUB1
Static Link
program MAIN_2; Dynamic link
var X : integer;
procedure BIGSUB; Return SUB 3
var A, B, C : integer; Local offect
procedure SUB1; E
var A, D : integer; C
begin { SUB1 } SUB3
A := B + C; ----1 Static Link Static Links
end; { SUB1 } Dynamic link At Position 1
procedure SUB2(X : integer);
var B, E : integer;
Return SUB 2 A (0 , 3)
procedure SUB3; B (1 , 4)
var C, E : integer; E
begin { SUB3 }
C (1 , 5)
B
SUB 2
SUB1;
X
E := B + A: ----- 2
Static Link
end; { SUB3 } Chain_offect
begin { SUB2 } Dynamic link
SUB3;
return BIGSUB
A := D + E; --------3
end; { SUB2 }
C
begin { BIGSUB }
SUB2(7); B
BIGSUB
end; { BIGSUB } A
begin
BIGSUB; Static Link
end; { MAIN_2 } Dynamic link
return to main
X
return global env
BITS Pilani, Pilani Campus
Nested Scoping

The actual reference can be represented by an ordered pair


of integers(Chain_offect, Local offect).
To compute Chain_offset it is required to understand the
Static Depth of a variable.
Static Depth: An integer associated with a static scope
that indicates how deeply it is nested in the outermost
scope.

procedure A is
procedure B is Let static depth of main procedure is
0.
procedure C is
A’s static depth is 0
...
B’s static depth is 1
end; -- of C
C’s static depth is 2
procedure D is
D’s static depth is 2
...
end; -- of D
end; -- of B
end; -- of A
175
BITS Pilani, Pilani Campus
Chain_offect/ nesting_depth

• Needed to reach the correct activation record instance


for a non local references to a variable x
• Difference between the static depth of the procedure
containing the reference to x and the static depth of
the procedure containing the declaration for x.

procedure A is
procedure B is • If procedure C reference a
procedure C is variable declared in A, The
chain_offcect of the
... reference would be 2.
end; -- of C
• If Procedure C references a
procedure D is variable declared in B, The
... chain_offect of that
reference would be 1.
end; -- of D
• Reference to local is 0
end; -- of B
end; -- of A

BITS Pilani, Pilani Campus


Example Pascal Program
program MAIN_2;
var X : integer; Call sequence for MAIN_2
procedure BIGSUB;
var A, B, C : integer;
procedure SUB1;
MAIN_2 calls BIGSUB
var A, D : integer; BIGSUB calls SUB2
begin { SUB1 } SUB2 calls SUB3
A := B + C; SUB3 calls SUB1
end; { SUB1 }
procedure SUB2(X : integer);
var B, E : integer;
procedure SUB3;
var C, E : integer;
begin { SUB3 }
SUB1;
E := B + A:
end; { SUB3 } Statically visible variable and their Chain offset
begin { SUB2 }
SUB3; SUB 3 C ( 0) E (0) B (1) A (2) X (1)
A := D + E;
end; { SUB2 } SUB2 B (0) E (0) A (1) C (1) X (0)
begin { BIGSUB }
SUB2(7); SUB1 A (0) D (0) B (1) C (1) X (2)
end; { BIGSUB }
begin BIGSUB A ( 0) B (0) C (0) X (1)
BIGSUB;
end; { MAIN_2 } Main_2 X (0)

177
BITS Pilani, Pilani Campus
D

Example Pascal Program A


SUB1
Static Link
program MAIN_2;
var X : integer;
Dynamic link Static Links
procedure BIGSUB; Return SUB 3 At Position 1
var A, B, C : integer; A (0,3)
procedure SUB1; E B (1,4)
var A, D : integer; C C (1,5)
begin { SUB1 } SUB3
At Position 2
Static Link
A := B + C; ----1 E (0,4)
end; { SUB1 } Dynamic link B (1,4)
procedure SUB2(X : integer); Return SUB 2 A (2,3)
var B, E : integer;
procedure SUB3; At Position 3
var C, E : integer; E A (1,3)
begin { SUB3 } B
D static error
SUB 2 (not visible)
SUB1;
X
E := B + A: ----- 2 E (0,5)
end; { SUB3 } Static Link
begin { SUB2 } Dynamic link
SUB3;
return BIGSUB
A := D + E; --------3
end; { SUB2 }
C
begin { BIGSUB }
SUB2(7); B
BIGSUB
end; { BIGSUB } A
begin
BIGSUB; Static Link
end; { MAIN_2 } Dynamic link
return to main
X
return global env
BITS Pilani, Pilani Campus
Scope
Statically visible variables

BLOCK 4 Y =13 X=3


BLOCK 3 Y =11 X=2
BLOCK 2 Y=11 X=3
BLOCK1 X=3 Y=7 Z

Dynamically visible variables

BLOCK 4 Y =13 X=3


BLOCK 3 Y =13 X=2
BLOCK 2 Y=13 X=2
BLOCK1 X=3 Y=7 Z

Solution
a. 33
b. 26

BITS Pilani, Pilani Campus


Static Scoping

Y= 11 ARI of function F
X=3

Y= 11 ARI of function G
X=2

Y= 13 Block 3
Y= 11
Block 2
X =3
Y= 7
Z= ? Block 1

BITS Pilani, Pilani Campus


Dynamic Scoping

Y= 13 ARI of function F
X=2

Y= 13 ARI of function G
X=2

Y= 13 Block 3
Y= 11
Block 2
X =3
Y= 7
Z= ? Block 1

BITS Pilani, Pilani Campus


Static Link
void main() {
int x,y,z,m; f, g while 3
while(…) ---1
{ d, e, m while 2
int a,b,c,m;
…………… a ,b, c, m while 1
while(…)-2
{ x, y, z, m main
int d,e,m;
d = b + x + m;

}
Statically visible variables
}
While 3 F G X Y Z M
while(………)-3
{ While 2 D E M A B C X Y Z
int f,g; While 1 A B C M X Y Z
f=b + x + m; Main X Y Z M
}
}
BITS Pilani, Pilani Campus
Static Link
void main() {
int x,y,z,m; f, g, m while 3
while(…) ---1
{ d, e, m while 2
int a,b,c,m;
…………… a ,b, c, m while 1
while(…)-2
{ x, y, z, m main
int d,e,m;
d = b + x + m;

}
Static Chain
}
While 3 F(0,1) B X(1,1) M(1,4)
while(………)-3
Static
{
error
int f,g;
While 2 D(0,1) B(1,2) X (2,1) M (0,3)
f=b + x + m;
}
}
BITS Pilani, Pilani Campus
Tutorial 3

Static Scope vs Dynamic Scope

BITS Pilani, Pilani Campus


What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?

int n = 1;
print_plus_n(int x)
{
Print( x + n);
}
increment_n()
{
n = n + 2;
print_plus_n(n);
}
main() {
int n; NIL
n = 200; return value
print_plus_n(7); n=200
n = 50; NIL
increment_n(); NIL
Print( n); return global env Global n=1
} Main
BITS Pilani, Pilani Campus
What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?

int n = 1;
print_plus_n(int x)
{
Print( x + n);
} NIL
increment_n() return value
{ x =7
n = n + 2; NIL
print_plus_n(n); NIL
} return Main
main() { Print_plus
int n; NIL
n = 200; return value
print_plus_n(7); n= 200
n = 50; NIL
increment_n(); NIL
Print( n); return global env Global n=1
} Main
BITS Pilani, Pilani Campus
What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?

int n = 1;
print_plus_n(int x)
{
Print( x + n);
}
increment_n()
{
n = n + 2;
print_plus_n(n);
}
main() {
int n; NIL

n = 200; return value

print_plus_n(7); n =50

n = 50; NIL

increment_n(); NIL

Print( n); return global env


Main Global n=1
}
BITS Pilani, Pilani Campus
What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?

int n = 1;
print_plus_n(int x)
{
Print( x + n);
} NIL

increment_n() return value

{ n

n = n + 2; NIL

print_plus_n(n); NIL

} return Main

main() { Increment_n

int n; NIL
n = 200; return value
print_plus_n(7); n = 52
n = 50; NIL
increment_n(); NIL
Print( n); return global env Global n=1
} Main
BITS Pilani, Pilani Campus
What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?
NIL
return value
x = 52

int n = 1; NIL

print_plus_n(int x) NIL

{ return
increment_n
Print( x + n);
Print_plus
} NIL

increment_n() return value

{ n

n = n + 2; NIL

print_plus_n(n); NIL

} return Main

main() { Increment_n

int n; NIL
n = 200; return value
print_plus_n(7); n= 52
n = 50; NIL
increment_n(); NIL
Print( n); return global env Global n=1
} Main
BITS Pilani, Pilani Campus
What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?

int n = 1;
print_plus_n(int x)
{
Print( x + n);
} NIL

increment_n() return value

{ n

n = n + 2; NIL

print_plus_n(n); NIL

} return Main

main() { Increment_n

int n; NIL
n = 200; return value
print_plus_n(7); n= 52
n = 50; NIL
increment_n(); NIL
Print( n); return global env Global n=1
} Main
BITS Pilani, Pilani Campus
What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?

int n = 1;
print_plus_n(int x)
{
Print( x + n);
}
increment_n()
{
n = n + 2;
print_plus_n(n);
}
main() {
int n; NIL
n = 200; return value
print_plus_n(7); n= 52
n = 50; NIL
increment_n(); NIL
Print( n); return global env Global n=1
} Main
BITS Pilani, Pilani Campus
What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?

int n = 1;
print_plus_n(int x)
{
Print( x + n);
}
increment_n()
{
n = n + 2; Static Scoping
print_plus_n(n); 8 6 50
}
main() { Dynamic Scoping
int n; 207 104 52
n = 200;
print_plus_n(7);
n = 50;
increment_n();
Print( n);
}
BITS Pilani, Pilani Campus
What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?

int n = 1;
print_plus_n(int x)
{
Print( x + n);
}
increment_n()
{
n = n + 2;
Main
print_plus_n(n);
n=
}
200
main() {
int n; Print_plus Global
n = 200; x=7 n =1
x n
print_plus_n(7);
n = 50;
increment_n();
Print( n);
}
BITS Pilani, Pilani Campus
What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?

int n = 1;
print_plus_n(int x)
{
Print( x + n);
}
increment_n()
{
n = n + 2;
Main
print_plus_n(n);
n =50
}
main() { Global n=1
int n;
n = 200; x n
print_plus_n(7);
n = 50;
increment_n();
Print( n);
}
BITS Pilani, Pilani Campus
What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?

int n = 1;
print_plus_n(int x)
{
Print( x + n);
}
increment_n()
{
n = n + 2;
Main
print_plus_n(n);
n =52
}
main() { Print_plus Global n=1
int n; x =52
n = 200; x
print_plus_n(7); n
n = 50;
increment_n();
Print( n);
}
BITS Pilani, Pilani Campus
What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?

int n = 1;
print_plus_n(int x)
{
Print( x + n);
}
increment_n()
{
n = n + 2;
Main
print_plus_n(n);
n =52
}
main() { Global n=1
int n;
n = 200; x
print_plus_n(7); n
n = 50;
increment_n();
Print( n);
}
BITS Pilani, Pilani Campus
What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?

void P() { write x; }

void Q() {
x = x + 1;
if (x < 23) Q();
else P();
}

void R() {
int x = 20; Dynamic Scoping
Q(); 23
P(): 23
} 10

void main() {
int x = 10;
R();
P();
}

BITS Pilani, Pilani Campus


What is the output when Static Scoping is followed?
What is the output when Dynamic Scoping is followed?
Give the run time stack when fun3() is executing (Shallow
Access)

void fun3( ) void fun2( ) void fun1( ) Global declare int


{ { { min=0,a=9,c=8;
min=(min<c)?min:c; declare int b=15; declare int b; driver( )
} declare int c=3; a=6; {
min= (a<b)?a :b; b=1; declare int
fun3( ); c=5; a=15,b=13,c=22;
} fun2( ); fun1( );
} Write( min );
}

BITS Pilani, Pilani Campus


Global declare int min=0,a=9,c=8;
driver( )
{
If the same program is
nested as shown, declare int a=15,b=13,c=22;
What is the Static link void fun1( )
of the variables in {
Position 1,2,3? declare int b;
a=6; b=1; c=5; -----------------------> Position 1
void fun2( )
{
declare int b=15,c=3;
min= (a<b)? a : b;----------------------> Position 2
void fun3( )
{
min=(min<c)? min : c;--------> Position 3
}//endfun3
fun3( );
}//end fun2
fun2( );
}//end fun1 Position 1: Position 2: Position 3:
fun1( ); a = (1,3) a = (2,3) c = (1,4)
Write( min ); b = (0,3) b = (0,3) min = (4,…)
c = (1,5) min = (3,…)
} BITS Pilani, Pilani Campus
Check List for Design

Constructs Issues
Identifiers (Naming, Binding, Scope, Lifetime)

Data Types ( Primitive and User Defined)
Expressions &
Assignment Statements
(Precedence , Associativity and Evaluation)

Iterative Statements Condition vs Range

Control Statements Control Statements.

BITS Pilani, Pilani Campus


Parse Tree

E1  E + T
E
ET
TT*F
TF E + T
F  id
F(E) T T * F

F F id

id id

BITS Pilani, Pilani Campus


What Next?

•Attributes of Variable
(Names, Address, Value, Type, Scope, Lifetime)
•Types
•Type Binding
• Type Conversion and Coercion
•Type Checking
•Strong Typing vs Weak Typing
•Type Equivalence

BITS Pilani, Pilani Campus


Variables Attributes –
(Name, Address, Value, Type, Lifetime, Scope)

• Type – “A Collection of computational entities that share


some common property”
 Set of values
 with a common collection of operations.
 which share a common representation.
int, float, Decimal, string, complex, Boolean…etc

203
BITS Pilani, Pilani Campus
Why Typing?

 Determines the range of values of variables.


 Defines the set of operations for the values.
 in the case of floating point, type also determines the
precision
 error detection: early detection of common
programming errors
 Offer Readability
 e.g. Celsius instead of integer

 Offer Protection.
 E.g. Float value stored in integer location can lead to loss of
data –
 can be prevented by compiler / run-time system that checks for
type matching.

BITS Pilani, Pilani Campus


Static Type Binding

BITS Pilani, Pilani Campus


Static Type Binding

E1  E + T
E
ET
TT*F
TF E + T
F  id
F(E) T T * F

F F id

id id

BITS Pilani, Pilani Campus


Static Type Binding

E1  E + T
E {24.2, real}
ET
T1  T * F
TF {2,int} E + T {12.2, real}
F  id
F(E) {2,int} T {3,int} T * F {4.2,
real}

{2,int} F {3,int} F id {place}

{place} id id {place}

BITS Pilani, Pilani Campus


How? :- Type Expression

• The type of a language construct is denoted by a type expression.


• A type expression can be:
– A basic type
• a primitive data type such as integer, real, char, boolean, …
• type-error to signal a type error
• void : no type
– A type constructor applies to other type expressions.
• Arrays:
• Records
• Functions:
• Pointers:

BITS Pilani, Pilani Campus


Type Constructor

Arrays: If T is a type expression, then array(I,T) is a type


expression where I denotes index range. Ex: array(0..99,int)

Functions:
•Treat functions in a programming language as mapping from a
domain type D to a range type R.
•The type of a function can be denoted by the type expression
D→R where D are R type expressions.
•Ex: int→int represents the type of a function which takes an
int value as parameter, and its return type is also int.

BITS Pilani, Pilani Campus


if (s and t are same basic types) then return true
else if (s=array(s1,s2) and t=array(t1,t2)) then return (equiv(s1,t1) and
equiv(s2,t2))
else if (s = s1  s2 and t = t1  t2) then return (equiv(s1,t1) and equiv(s2,t2))
else return false

BITS Pilani, Pilani Campus


Polymorphic Typing

• A language is polymorphic is language constructs can have more than


one type
procedure swap(anytype x, y)
where anytype is considered to be a type variable
• Polymorphic functions have type patterns instead of actual type
expressions
• The type checker must check that the types of the actual parameters fit
the pattern
– Technically, the type checker must find a substitution of actual types
for type variables that satisfies the type equivalence between the
formal type pattern and the actual type expression
• Most notably in the language ML
• Java and C# allow polymorphic type constructors, called generics

BITS Pilani, Pilani Campus


Polymorphism

A polymorphic function accepts arguments of different types:

Example parametric polymorphism in ML Example function polymorphism in ML


fun I(x) =x; fun Length(nil) =0
val I=fn :α->α | Length(a::y)=1+length(y);
val Length=fn :α list->int

Fired ( Employee) //Polymorphism due to sub-typing or Inclusive typing


Person Employee / Manager
If Employee Is of Type T
Manager is Sub-type of Type T
BITS Pilani, Pilani Campus
Where:- Type System

A collection of rules for assigning type expressions to the


various parts of a program.
 Type Checker: An implementation of a type system.

 Syntax Directed.

 Sound Type System: eliminates the need for checking


type errors during run time.
• A programming language is strongly-typed, if every
program its compiler accepts will execute without type
errors.
– In practice, some of type checking operations are done
at run-time (so, most of the programming languages
are not strongly-typed).
– Ex: int x[100]; … x[i] most of the compilers cannot
guarantee that i will be between 0 and 99

BITS Pilani, Pilani Campus


Strong vs Weak Typing

• In Strong typing any operation on wrong type will raise error.


This make language Type safe.
Example: int i=4; char c=“5”
operation i+5 will be an error.
• In Weak typing above operation can be legal.
Example: Visual basic will convert “5” to number 5 and add with
4. Java script will convert 4 to string and add the string.

BITS Pilani, Pilani Campus


Type Checking

• Type equivalence
– When are the types of two values the same?
• Type compatibility
– When can a value of type A be used in a context that
expects type B?
• Type inference
– What is the type of an expression, given the types of the
operands?

BITS Pilani, Pilani Campus


• Type
• Type Binding
• Type Expressions
• Type System
• Type Checking
• Type Compatibility
• Type Inference
• Type Equivalence
• Strong Vs Weak Typing
• Static Vs Dynamic Typing

BITS Pilani, Pilani Campus


Type Compatibility

• Overloading
– Arithmetic operators
2 + 3 means integer addition
2.0 + 3.0 means floating pt addition
– Language may have an arithmetic operator table,
telling which type of operator will be used based on
the expressions

Type of: a b a+b


int int int
int int float
int int double
float float float
float float double
double double double
BITS Pilani, Pilani Campus
Coercion and Conversion

• Type coercion
– If x is float, is x=3 acceptable?
• Disallow
• Allow and implicitly convert 3 to float.
• "Allow" but require programmer to explicitly convert 3 to float
• How do we convert?
– Reinterpret bit sequence
– Build new object
– What should be allowed?
• float to int ?
• int to float ?

BITS Pilani, Pilani Campus


Widening and Narrowing

• The rules for Java type conversion distinguishes between


– Widening conversions which preserve information
– Narrowing conversion which can lose information
• Conversions between primitive types in Java:

Widening(implicit) Narrowing (usually with a cast)


double double
float float
long long
int int
short byte char char short byte

219
BITS Pilani, Pilani Campus
Conversion and Coercion
• The typeEqual comparison is commonly extend to allow
arithmetic expressions of mixed type and for other cases of
types which are compatible, but not equal
– If mixed types are allowed in an arithmetic expression, then
a conversion should be inserted (into the AST or the code)
2 * 3.14 becomes code like
t1 = float ( 2)
t2 = t1 * 3.14

220
BITS Pilani, Pilani Campus
Type Equivalence

• Structural Equivalence
• Name Equivalence

BITS Pilani, Pilani Campus


Structure Type Equivalence
• Structure type Equivalence
Two type expressions are structural equivalent if they are
• same basic type or
• formed by applying the same constructor
 Does not depend on format.
 Does not depend on order.
More flexible, but harder to implement

typedef struct {
typedef struct {
int b;
int a;
int a;
int b;
typedef struct { int a, b; } foo1; } foo2; } foo3;

222
BITS Pilani, Pilani Campus
Equivalence Algorithm (equiv):

if (s and t are same basic types) then return true


else if (s=array(s1,s2) and t=array(t1,t2)) then return (equiv(s1,t1) and
equiv(s2,t2))
else if (s = s1  s2 and t = t1  t2) then return (equiv(s1,t1) and equiv(s2,t2))
else return false

BITS Pilani, Pilani Campus


Structural equivalence

• Are these two types structurally equivalent?

typedef struct { typedef struct {


char *name; char *name;
char *address; char *address;
int age; int age;
} student; } school;

• They are, and it is unlikely that the programmer intended to


make these two types equivalent

BITS Pilani, Pilani Campus


w.r.t Alias
Example:
typedef pointer to cell alink;
subtype alink blink;
pointer to cell p, q ;
alink r;
blink s;
Structure type equivalence equates all 5 variables
alink u;

BITS Pilani, Pilani Campus


Name Type Equivalence

• Name type Equivalence means the two variables are name


type equivalent if they are in either the same declaration or
in declarations that use the same type name.
typedef int ID; typedef int Marks;
Marks m1,m2,m3; ID i1,i2,i3; ID i4,i5;
Here : m1≠i1 if language support Name equivalence.
i1= i4; under Name equivalence.
• school and student are not equal.

typedef struct { typedef struct {


char *name; char *name;
char *address; char *address;
int age; int age;
} student; } school; 226
BITS Pilani, Pilani Campus
Strict vs Loose

w.r.t Alias

Strict name equivalence:


Aliases are not equivalent.
Loose name equivalence:
If they refer to the same declaration after factoring out
any type aliases.

typedef int ID; typedef int Marks;

Marks m1,m2,m3; ID i1,i2,i3; int x;

m1≠i1≠x under strict Name equivalence.


i1=x under loose Name equivalence
m1= x under loose Name equivalence.

BITS Pilani, Pilani Campus


Type Equivalence Example
typedef int array[10];
typedef array sarray;
array a;
array b;
sarray c;
int d[10];

• All variables (a,b,c,d) are equivalent in C Language


as d[2] can be interchangeable with a[2], b[3] or c[5].

• a and b is not equivalent to c under strict name equivalence.

• a, b, and c are mutually equivalent under loose name equivalence.

• a and b are not equal in pascal and ADA language.

BITS Pilani, Pilani Campus


Type Equivalence Example

int a[10],b[10];
int d[10];
a and b are equivalent in pascal and C.
d is not equivalent to a and b in pascal but it is equal in C.

BITS Pilani, Pilani Campus


Type Equivalence

• C support structural equivalence for all type except for record


type (struct). It follows name equivalence.

BITS Pilani, Pilani Campus


Type Equivalence

• C support structural equivalence for all type except for record


type (struct). It follows name equivalence.

typedef struct{ typedef struct{ structure1 var1, var2;

int a; int x; structure2 var3;

float b; float y;
} structure1; } structure2;

Value of var1 and var3 can’t be interchanged in either C nor Pascal

BITS Pilani, Pilani Campus


Loose name equivalence and structural equivalence may introduce
undesirable equivalence
typedef float celsius;
typedef float fahrenheit;

celsius c;
fahrenheit f;
………………
……………..
c=f; /*probably an error*/
……………..
……………..

BITS Pilani, Pilani Campus


Data Types

BITS Pilani, Pilani Campus


BITS Pilani, Pilani Campus
Check List for Design

Constructs Issues
Identifiers (Naming, Binding, Scope, Lifetime)

Data Types ( Primitive and User Defined)

Expressions &
Assignment Statements
(Precedence , Associativity and Evaluation)

Iterative Statements Condition vs Range

Control Statements Control Statements.

BITS Pilani, Pilani Campus


Thank You ...

BITS Pilani, Pilani Campus

You might also like