imperative programming

43
Imperative Programming

Upload: raheem

Post on 25-Feb-2016

236 views

Category:

Documents


14 download

DESCRIPTION

Imperative Programming. Imperative Programming. Most widely used paradigm Oldest paradigm Largest number of languages E.g. C, FORTRAN, Java/C++ (without the objects) Features closely related to machine architecture Based on the von Neumann stored program model - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Imperative Programming

Imperative Programming

Page 2: Imperative Programming

Imperative Programming

• Most widely used paradigm• Oldest paradigm• Largest number of languages

– E.g. C, FORTRAN, Java/C++ (without the objects)• Features closely related to machine architecture

– Based on the von Neumann stored program model• We will skip a number of topics in this chapter as

you should already be familiar with them from previous courses

Page 3: Imperative Programming

Imperative Programming• Language Structure

– Declarations• Associate variables with memory locations

– Expressions• Evaluated in the current environment

– Commands• Execution and flow of control• Similar to the machine instructions

– Assignment» Dynamically updates data store

– Conditionals» Statements executed or skipped

– Branching » Alters the flow of control» Supports looping

• Basis for defining an effective programming language

Page 4: Imperative Programming

Turing Completeness• A programming language is said to be Turing Complete if it contains

– Integer variables, values and operations– Assignments, branching, sequencing, and conditionals

• Other features make languages easier to program for complex applications– Loops– Procedures– Object Orientation

• But they have the same power as any other programming language– i.e. what is possible to compute in one is possible in the other– Jay is Turing Complete

Page 5: Imperative Programming

Other Features

• Typical Turing complete language today supports:– Data types for reals, chars, strings, booleans– For, while, switch– Arrays– Records– I/O commands– Pointers– Procedures and functions

Page 6: Imperative Programming

Imperative Programming Design Principles

• Structured Programming – The structure of the program text should be the guide to

understanding what it does.• Can be more efficient• Improved readability• Easier to tune and modify

– Efficiency• A language must allow an underlying assignment-oriented

machine to be used directly and efficiently.• Driving factor in the implementation of many imperative

languages

Page 7: Imperative Programming

Types in Typical Imperative Languages

• Emphasis on data structures with assignable components– Based on values that can be manipulated

directly by underlying machine• Size and layout fixed at compile time• Storage allocated and deallocated explicitly• Strongly typed• Storage efficiency is the key

Page 8: Imperative Programming

Naming and Variables

• Skipping in Text– Reserved words– Variables unique– Concept of scope, scoping rules

Page 9: Imperative Programming

Types, Values and Expressions in Jay

• Let’s look at defining types, values, and expressions in Jay

• Jay supports only two types– Boolean and Integer

• Boolean– Values: {true,false}– Operations: &&, ||, !

• Integer– Values: {…,-2,-1,0,1,2,…..}– Operations

» Arithmetic : +,-,*,/» Relational: ==, !=, <=, <, >=, >

Page 10: Imperative Programming

Expressions in Jay• Expression has the forms

– Value– Variable– Result of a binary operation– Result of a unary operation

• Type of an expression is defined by the types of its constituents– Constituent Expression Type

Value Type of the valueVariable Type of the variableArithmetic Binary operator intRelational Binary operator booleanUnary operator boolean

Page 11: Imperative Programming

Formally Defining Types

• Back to the typemap format from chapter 3:

language) the in supportedtypes all of (set Tttype declared its denotes t

Variable a denotes vtvtvtvtm

i

i

i

nn

},,,,,,{ 2211

Page 12: Imperative Programming

Types of Expressions

• Formally defining expression types in Jay:

),( tmTypeMapeExpressiontypeOf Value if e is atypee .Variableif e is a tm(e) tme

ry is a Bina if eint cOp}{Arithmatie.op s a Binary if e iBoolean }{BooleanOpe.op

a Binary if e isBoolean lOp}{Relationae.op ary e is a Un ifBoolean {UnaryOp}e.op

Page 13: Imperative Programming

Jay Expression Example

• Declaration: int x,y;• Expressions:

– x+2*y – x<2*y – x<2*y && x>0

• Typemap tm={<x,int>,<y,int>}

OpArithmatic int 2*y,tm)typeOf(x lOp Relationa boolean 2*y,tm)typeOf(x

BooleanOp && boolean 0,tm)2*y&&xtypeOf(x

Page 14: Imperative Programming

Validity of Expressions

• typeOf function determines the type of expressions

• typeOf function does NOT determine the validity of the expression

• Need to check separately

Page 15: Imperative Programming

Validity of Expressions

• An expression is valid if it is:– int or boolean Value– Variable in the type map– Unary with a UnaryOp operator and a valid boolean

operand– Binary with ArithmeticOp with two valid int operands– Binary with RelationalOp with two valid int operands– Binary with BooleanOp with two valid boolean

operands

Page 16: Imperative Programming

Formal Validity of Expressions

• More formally:

cOp}{Arithmeti e.op int )e.term2,tm typeOf( s a Binary if e i int)e.term1,tm typeOf(

tm)V(e.term2tm)V(e.term1, Variable if e is atme

Value if e is atruetmTypeMapeExpressionV

,

),(

Page 17: Imperative Programming

Validity of Expressions

! e.op

Unaryif e is a booleantmtermetypeOfm)V(e.term,t

}{BooleanOp e.op boolean)e.term2,tm typeOf( s a Binary if e i boolean)e.term1,tm typeOf(

tm)V(e.term2tm)V(e.term1,lOp}{Relationa e.op int)e.term2,tm typeOf(

s a Binary if e i int)e.term1,tm typeOf( tm)V(e.term2tm)V(e.term1,

tmTypeMapeExpressionV

),.(

,

,),(

Page 18: Imperative Programming

Expression Example

• Validity of x+2*y– Note recursive nature of V

inttm)ypeOf(2*y, t cOp Arithmeti int)ypeOf(x,tm t

V(2*y,tm)V(x,tm) 2*y,tm)V(x

since

Page 19: Imperative Programming

Expression Example

valueaissince trueVtmsince ytrueyV

cOp Arithmetie * sinc int ,tm)typeOf(2*y variablence x is a si int tm(x)m)typeOf(x,t

intOf(y,tm) type cOp Arithmetince * si intOf(2,tm) type

V(y,tm) V(2,tm)V(2*y,tm)tmce x sin true V(x,tm)

inttm)ypeOf(2*y, t cOp Arithmetie sinc int)ypeOf(x,tm t

V(2*y,tm)V(x,tm) 2*y,tm)V(x

2 )2( )(

Page 20: Imperative Programming

Semantics of Jay• Semantic domains

– Integers (I)– Boolean (B)

• Meaning of a Jay Expression can be defined functionally:

• ApplyBinary : Computes a value given a binary operator and two operands• ApplyUnary : Computes a value given a unary operator and one operand• Uses the properties of the underlying semantic domains

ryf e is una i )) .term,y(e.op,M(e ApplyUnars binary) if e i2,),M(e.terme.term1,ry(e.op,M( ApplyBina

e a variabl if e is (e) valueif e is a e.val

)e on e, StatM(Expressi

Page 21: Imperative Programming

ApplyBinary FunctionValueValueValueOperatoryApplyBinar :

/)(

*

),,(

212

1

21

21

21

21

op ifvvsignvvfloor

op if vv op if vv op if vv

vValuevValueopOperatoryApplyBinar

Page 22: Imperative Programming

ApplyBinary, Cont.

|| &&

!

),,(

21

21

21

21

21

21

21

21

21

op if vv op if vv op if vv op if vv op if vv op if vv op if vv op if vv

vValuevValueopOperatoryApplyBinar

Page 23: Imperative Programming

Semantics Example

• Meaning of expression x+2*y– Note recursive definitions

10)14,4,(

))7,2(*,,4,())),(),,2((*,,4,(

)),*2(),,(,(),*2(

yApplyBinaryApplyBinaryApplyBinar

yMMyApplyBinaryApplyBinaryMxMyApplyBinaryxM

}7,,4,{ yx

Page 24: Imperative Programming

Semantics• ApplyBinary depends on the meaning of the

semantic domain of I and B• Sometimes it is possible to define the meanings

directly without using domains, e.g. for the definitions of && and || without using and

|| &&

),,( 21

op if else v then trueif v op ifelse false then vvif

vValuevValueopOperatoryApplyBinar

21

21

Using the Short Circuit evaluation method

Page 25: Imperative Programming

Elementary Data Types

• Skipping from book– Nibble, byte, word, quadword, etc.– IEEE 754 number format– Unicode– Operator overloading, type conversion (e.g. int/float)

• See textbook for similarity in C++ and Java operators– Book uses ?: for conditional

• E.g. x = (y>0) ? 1 : 2; – If (y>0) x=1; else y=2;

Page 26: Imperative Programming

Syntax and Semantics of Jay

• Recall the following concrete and abstract syntax for Jay statements

• We can define validity for statements:

mentWhileStatetIfStatemenAssignmentBlockStatement ||||;

LooplConditionaAssignmentBlockSkipStatement ||||

Page 27: Imperative Programming

Semantics of Skip

• Skip

),( StatesSkipM

• Skip statement can’t change the state

Page 28: Imperative Programming

Semantics of Assignment

• Discussed in chapter 3

• For x=a+b

}),.(,.{) a, (

:

sourceaMtargetaUStateAssignmentM

AssignmentM

}4,,1,,3,{}),(,{),;(

}88,,1,,3,{

xbabaMxUbaxM

xba

Page 29: Imperative Programming

Semantics of Conditional

otherwiseelsebranchcMtrueistestcMifthenbranchcM

StateclConditionaM

),.( ),.(),.(

),(

If (a>b) max=a; else max=b

;),;(max ),(),;(max

),b;max elsea;b)max(a if(}1,3,{

otherwisebMtrueisbaMifaM

Mba

Page 30: Imperative Programming

Conditional, continued

}3max,,1,,3,{ }3max,{

),(),;(max ),b;max elsea;b)max(a if(

}1,3,{

baU

trueisbaMsinceaMM

ba

Page 31: Imperative Programming

Semantics of Block

• Block is just a sequence of statements

• Example for Block b:fact = fact * i;i = i – 1;

nn bbbbifbStatementMbBlockMbif

StatebBlockM

...)),)((,)((

),(

211...2

Page 32: Imperative Programming

Block example

• b1 = fact = fact * i;

• b2 = i = i – 1;

• M(b,σ) = M(b2,M(b1,σ))

= M(i=i-1,M(fact=fact*i,σ))= M(i=i-1,M(fact=fact*i,{<i,3>,<fact,1>}))=M(i=i-1,{<i,3>,<fact,3>})={<i,2>,<fact,3>}

b

Page 33: Imperative Programming

Semantics of Loop

• Loop = Expression test; Statement body

• Recursive definition

otherwisetestlMifbodylMlM

StatelLoopM

trueis ),.()),.(,(

),(

Page 34: Imperative Programming

Loop Example

• Initial state σ={<N,3>}

fact=1;i=N;while (i>1) {

fact = fact * i;i = i -1;

}

After first two statements, σ = {<fact,1>,<N,3>,<i,3>}

Page 35: Imperative Programming

Loop Example

σ = {<fact,1>,<N,3>,<i,3>}M(while(i>1) {…}, σ) = M(while(i>1) {…}, M(fact=fact*i; i=i-1;, σ)= M(while(i>1) {…}, {<fact,3>,<N,3>,<i,2>})= M(while(i>1) {…}, {<fact,6>,<N,3>,<i,1>})= M(σ)={<fact,6>,<N,3>,<i,1>}

Page 36: Imperative Programming

Syntax and Semantics for Real Languages

• For Loop– Concrete Syntax

• ForStatement for (Assign1opt; Expropt; Assign2opt) Statement– Abstract Syntax

• Identical to Abstract Syntax for While– See text for details

• Do statements– Concrete Syntax

• DoStatement do Statement while (Expression)– Abstract Syntax

• Identical to Abstract Syntax for While• Different semantics, must make sure body is execute once

Page 37: Imperative Programming

Syntax and Semantics of Real Languages

• Switch statement– Multi-way IF statement– See book for details, straightforward extension

• Break/Continue statement– Break terminates switch or while– Continue terminates current iteration of while and jumps back to

the loop test– Semantics must be specified in definitions for switch and while

• E.g. break statement in a switch:– Meaning if no break is Meaning of first matching true statement and all

subsequent statements– Meaning if break is Meaning of first matching true statement, all

subsequent statements until one contains a break

Page 38: Imperative Programming

Scoping

• Skipping scope, visibility, and lifetime– Should be familiar with this from Java– Static scope

• Scope computed at compile time– Dynamic scope

• Scope compute at run time

Page 39: Imperative Programming

Extension to Methods• Suppose we would like to extend Jay to include methods (functions)• Must augment the concrete syntax:

ents}ons Statem{Declarati MainMethodifierType IdentParameter

,ParameterParameters|Parameter ParametersType

ments}ions State){Declaratametersifier (ParType IdentMethod ethod|Methods MMethods

d} MainMethons MethodsDeclaratior { IdentifieProgram

opt

main() void

void|boolean |int

package

Page 40: Imperative Programming

Sample Program

Page 41: Imperative Programming

Syntax for Methods

• Must modify BNF rules for statements to allow method calls as a statement or a factor within an expression:

)s (ArgumentIdentifierCall n)(ExpressioCall |Literal | |IdentifierFactor

n ExpressioArguments,n | ExpressioArgumentsn; Expressioement ReturnStat

);tsr (Argumen IdentifieentCallStatemementReturnStat|entCallStatem|eStatement Whil

t|IfStatemen|Assignment|Block ;|Statement

opt

opt

return

Page 42: Imperative Programming

Abstract Syntax for Methods

• Underlined rules indicate changes

Page 43: Imperative Programming

Static Type Checking for Methods

• New validity rules now need to be added:– Every method and global variable must have a unique ID– All local variables and parameters within a method must be unique

with valid types– All statements and expressions within the body of each method must

be valid with respect to the variables and parameters accessible to them

– A return appears in every method with a nonvoid Type, and the type of the Expression in the return must be identical with the method’s Type

– Every call has a name identical with the name of a method in the program and has the same number of arguments as the method

– Every argument in a call has the same type as the type given in the corresponding parameter in the method of that name

• See book for denotational semantics to implement these rules